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

使用For Loop统计Python/Pandas指定列的行数如何实现

你可以先将需要统计的4个指定列存入列表,再通过For Loop遍历列表执行统计逻辑即可,和原有代码输出完全一致的实现如下:

# 定义需要统计的目标列集合
target_columns = ['Column_1', 'Column_2', 'Column_3', 'Column_4']

for col in target_columns:
    print(f'{col}:', batch_df.groupby(col).size().sum())

如果不需要保留原有groupby的写法,还可以用更高效的.count()方法实现等价效果,.count()会直接返回对应列的非空行数,不需要执行分组逻辑,运行速度更快:

target_columns = ['Column_1', 'Column_2', 'Column_3', 'Column_4']

for col in target_columns:
    print(f'{col}:', batch_df[col].count())

内容的提问来源于stack exchange,提问作者Devanshi Tripathi-Reese

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 08:48:00