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

如何统计DataFrame中指定列Col1的所有字符串空格总数?

统计DataFrame中Col1列的空格总数

可以通过Pandas的字符串方法快速实现需求:

  1. 先构造目标DataFrame(若已有现成DataFrame可跳过此步骤):
import pandas as pd

df = pd.DataFrame({
    'Col1': ['AAA A', 'B BBB', 'CC CC', 'DDDDD', 'AAAAX'],
    'Col2': ['XYZ', 'XYZ', 'RST', 'XYZ', 'WXY'],
    'file_name': ['test1.csv', 'test1.csv', 'test1.csv', 'test2.csv', 'test3.csv']
})
  1. 统计Col1列所有字符串的空格总数:
num_of_spaces = df['Col1'].str.count(' ').sum()
print(f"num_of_spaces = {num_of_spaces}")

执行代码后会输出:

num_of_spaces = 3

逻辑说明

  • df['Col1'].str.count(' '):对Col1列的每个字符串单独统计空格数量,返回一个存储各字符串空格数的Series
  • .sum():将Series中的所有数值求和,最终得到Col1列的总空格数

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 05:55:16