You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何统计Python Pandas列中首个字符前的空格数

统计Pandas DataFrame列的前导空格数

原始数据

columnA columnB
A        10
 B       12
  C      13
  D      14
 010     17

需求

新增counter列,统计columnA中首个非空白字符前的空格数量,最终得到如下结果:

columnA columnB counter
A        10      0
 B       12      1
  C      13      2
  D      14      2
 010     17      1

解决方案

方法1:利用字符串长度差

通过计算原始字符串长度与去除前导空格后的字符串长度之差,直接得到前导空格数:

import pandas as pd

# 构造原始DataFrame
df = pd.DataFrame({
    'columnA': ['A', ' B', '  C', '  D', ' 010'],
    'columnB': [10, 12, 13, 14, 17]
})

# 新增counter列
df['counter'] = df['columnA'].str.len() - df['columnA'].str.lstrip().str.len()

print(df)

方法2:正则表达式捕获前导空格

用正则匹配开头的所有空格,再统计捕获到的空格长度:

df['counter'] = df['columnA'].str.extract(r'^(\s*)')[0].str.len()

两种方法都能得到符合预期的结果,其中方法1更直观易懂,方法2适合需要更复杂正则匹配的场景。

内容的提问来源于stack exchange,提问作者PV8

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 01:24:53