gpt4 book ai didi

python - 在 Pandas 中减少(折叠)

转载 作者:太空宇宙 更新时间:2023-11-03 11:44:14 25 4
gpt4 key购买 nike

Pandas DataFrame 是否有任何缩减/折叠实现?例如,我想获取数据帧 df 中名为 cost 的列中的数字总和,使用类似 lambda acc, x 的方法,其中 x 是一个 DataFrame 行。

我该怎么办?

附言我知道 .sum(),但还有许多其他可能的 \acc,x -> ... 函数。

最佳答案

可以通过以下方式实现快速折叠(将 plus 替换为您自己的函数):

import numpy as np
def accum(op,ser):
u_op = np.frompyfunc(op, 2, 1) # two inputs, one output
return u_op.accumulate(ser, dtype=np.object)
def plus(x,y):
return x+y
accum(plus,np.arange(10))

你得到:

array([0, 1, 3, 6, 10, 15, 21, 28, 36, 45], dtype=object)

这适用于 numpy 系列,因此也适用于 pandas 数据帧的组件。如果有一个直接在数据帧上工作的解决方案会很有趣,这样就可以组合多个系列。

关于python - 在 Pandas 中减少(折叠),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43075384/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com