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

如何为Pandas DataFrame添加多列非零值计数列?

统计Pandas DataFrame中每行非零日期值的数量

问题背景

现有如下Pandas DataFrame,包含_id列和多个日期格式的列:

import pandas as pd
df = pd.DataFrame({
    '_id': ['633739b043e8750c660feabd', '63373966bf5eb50c6d593b1f', '633738aa43e8750c660fe90e', '63373853bf5eb50c6d5938c1'],
    '2022-10-01': ['1', '0', '0', '2'],
    '2022-10-02': ['0', '1', '0', '0'],
    '2022-10-03': ['2', '8', '3', '9'],
    '2022-10-04': ['0', '0', '0', '2'],
    '2022-10-05': ['9', '0', '0', '2'],
    '2022-10-06': ['1', '0', '3', '2'],
})

需要新增一列No_of_Days,统计每个_id对应日期列中的非零值数量,期望结果如下:

import pandas as pd
df = pd.DataFrame({
    '_id': ['633739b043e8750c660feabd', '63373966bf5eb50c6d593b1f', '633738aa43e8750c660fe90e', '63373853bf5eb50c6d5938c1'],
    '2022-10-01': ['1', '0', '0', '2'],
    '2022-10-02': ['0', '1', '0', '0'],
    '2022-10-03': ['2', '8', '3', '9'],
    '2022-10-04': ['0', '0', '0', '2'],
    '2022-10-05': ['9', '0', '0', '2'],
    '2022-10-06': ['1', '0', '3', '2'],
    'No_of_Days': ['4', '2', '2', '5']
})

解决方案

实现代码

import pandas as pd

# 初始化原始DataFrame
df = pd.DataFrame({
    '_id': ['633739b043e8750c660feabd', '63373966bf5eb50c6d593b1f', '633738aa43e8750c660fe90e', '63373853bf5eb50c6d5938c1'],
    '2022-10-01': ['1', '0', '0', '2'],
    '2022-10-02': ['0', '1', '0', '0'],
    '2022-10-03': ['2', '8', '3', '9'],
    '2022-10-04': ['0', '0', '0', '2'],
    '2022-10-05': ['9', '0', '0', '2'],
    '2022-10-06': ['1', '0', '3', '2'],
})

# 提取日期列并转换为数值类型
date_columns = df.drop('_id', axis=1).astype(int)
# 统计每行非零值数量并转为字符串格式
df['No_of_Days'] = (date_columns != 0).sum(axis=1).astype(str)

print(df)

代码说明

  • df.drop('_id', axis=1):移除_id列,仅保留日期相关的列。
  • .astype(int):将日期列中字符串类型的数值转为整数,确保能正确判断非零值。
  • (date_columns != 0):生成布尔值DataFrame,非零值对应True,零值对应False。
  • .sum(axis=1):按行求和(True视为1,False视为0),得到每行的非零值数量。
  • .astype(str):将统计结果转为字符串类型,匹配期望结果的格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 17:01:05