python - 属性错误: 'str' object has no attribute 'cumsum'

标签 python pandas dataframe cumsum

df["Size"] 应该输出一个新的累计总数,并且不允许总和低于 0:

         Size 
0        11.0
1        18.0
2       -13.0
3        -4.0
4       -26.0
5        30.0

print(df["Cumulative"]) 输出应为:

       Cumulative
0        11
1        29
2        16
3        12
4         0 
5        30

我希望 lambda 可能有所帮助,但我收到错误:

df.Size = df.Size.astype(int)
df["Cumulative"] = df.Size.apply(lambda x: x.cumsum() if x.cumsum() > 0 else 0)
print(df)

输出:

AttributeError: 'int' object has no attribute 'cumsum'

无论输入什么数据类型“str”、“float”都会出现此错误

或者我从以下开始:

df.Size = df.Size.astype(int)
df["Cumulative"] = df.Size.cumsum()

输出:

       Cumulative
0         11
1         29
2         16
3         12
4        -14
5         16

此输出按预期工作,但不会阻止结果降至 0 以下

最佳答案

更新

您必须使用 itertools 中的 accumulate:

from itertools import accumulate

def reset_cumsum(bal, val):
    return max(bal + val, 0)  # Enhanced by @Chrysophylaxs
    # return bal if (bal := bal + val) > 0 else 0

df['Cumulative'] = list(accumulate(df['Size'], func=reset_cumsum, initial=0))[1:]
print(df)

# Output
   Size  Cumulative
0  11.0        11.0
1  18.0        29.0
2 -13.0        16.0
3  -4.0        12.0
4 -26.0         0.0
5  30.0        30.0

您可以使用扩展并计算每次迭代的总和。如果总和大于 0,则返回总和,否则返回 0:

>>> df['Size'].expanding().apply(lambda x: c if (c := x.sum()) > 0 else 0)
0    11.0
1    29.0
2    16.0
3    12.0
4     0.0
5    16.0
Name: Size, dtype: float64

关于python - 属性错误: 'str' object has no attribute 'cumsum' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75348576/

相关文章:

numpy - 如何使用 Pandas 沿 axis=1 填充缺失值?

python - pandas groupby 根据条件替换

r - xtable包: Skipping some rows in the output

python - 获取每行列表中最常用的单词

python - 如何在不停止 python 程序和编辑代码的情况下禁用 pdb.set_trace()

python - 使用 pytest.hookimpl 将 pytest 测试函数返回值写入文件

python - 为什么 sympy 不能计算像 (6-x*x)**(1.5) 这样的分数幂公式?

python - 为什么将 DatetimeIndex 转换为 np.array 时格式会发生变化?

scala - 在 Scala Spark 中加入不同的 Dataframe 时动态选择多个列

python - 使用正则表达式从字符串中删除单词