使用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
相关产品推荐
相关产品推荐

