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

如何在Python/Pandas中统计第0列值为"I"的行数并输出结果?

解决方法:统计CSV中第0列为"I"的记录数并格式化输出

步骤1:统计目标行数

你可以通过布尔索引筛选出第0列值为"I"的行,再统计数量,两种简洁写法任选:

  • 先筛选再统计行数:
filtered_rows = df[df[0] == "I"]
i_count = filtered_rows.shape[0]
  • 直接对布尔结果求和(更高效):
i_count = (df[0] == "I").sum()

原理:df[0] == "I"会生成一个布尔序列,True代表该行符合条件,sum()会将True视为1、False视为0,求和后直接得到符合条件的记录数。

步骤2:用f-string格式化输出

把统计结果代入f-string的占位符,直接输出指定格式的语句:

print(f'{i_count} number of records were inserted successfully where an "I" exists.')

完整代码示例

import pandas as pd

# 读取无表头的CSV文件
df = pd.read_csv('file.csv', header=None)
# 统计第0列为"I"的记录数
i_count = (df[0] == "I").sum()
# 输出结果
print(f'{i_count} number of records were inserted successfully where an "I" exists.')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 12:35:19