gpt4 book ai didi

python - 使用 raw=False 的自定义扩展功能

转载 作者:行者123 更新时间:2023-12-04 10:49:03 24 4
gpt4 key购买 nike

考虑以下数据框:

df = pd.DataFrame({
'a': np.arange(1, 5),
'b': np.arange(1, 5) * 2,
'c': np.arange(1, 5) * 3
})

a b c
0 1 2 3
1 2 4 6
2 3 6 9
3 4 8 12

我想计算列中每一行的累积总和:
def expanding_func(s):
return s.sum()

df.expanding(1, axis=1).apply(expanding_func, raw=True)

# As expected:
a b c
0 1.0 3.0 6.0
1 2.0 6.0 12.0
2 3.0 9.0 18.0
3 4.0 12.0 24.0

但是,如果我设置 raw=False , expanding_func不再有效:
df.expanding(1, axis=1).apply(expanding_func, raw=False)
ValueError: Length of passed values is 3, index implies 4

documentationexpanding_func

Must produce a single value from an ndarray input if raw=True or a single value from a Series if raw=False.



这正是我正在做的。为什么 expanding_func失败时 raw=False ?

备注 : 这只是一个人为的例子。我想知道如何编写自定义滚动函数,而不是如何计算跨列的累积总和。

最佳答案

看来这是 Pandas 的一个错误。

如果你这样做:

df.iloc[:3].expanding(1, axis=1).apply(expanding_func, raw=False)

它确实有效。似乎当作为一个系列传递时,pandas 出于某种原因试图用数据帧的行数检查返回的列数。 (它应该比较df的列数)

一种解决方法是转置 df,应用您的函数并转回似乎有效的方法。该错误似乎仅在轴设置为 1 时影响。
df.T.expanding(1, axis=0).apply(expanding_func, raw=False).T
a b c
0 1.0 3.0 6.0
1 2.0 6.0 12.0
2 3.0 9.0 18.0
3 4.0 12.0 24.0

关于python - 使用 raw=False 的自定义扩展功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59572728/

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