gpt4 book ai didi

python pandas - groupby 使用列号/位置(用于循环)

转载 作者:太空宇宙 更新时间:2023-11-03 11:18:54 24 4
gpt4 key购买 nike

我想通过多个 groupby 连续循环我的数据框,我想使用列号(或者它是列位置?)作为 groupby 索引,即。

数据框

col1 | col2 | col3 | col4
-------------------------
12 22 13 14
13 23 15 16
14 24 17 18

我的代码:

for i in range(1:df.shape[1])
grouped = df.groupby([i-1, i])
#grouping by col1+col2, col2+col3, etc.

不幸的是,它向我抛出关键错误:

File "C:\Program Files\Python\Python36\lib\site-packages\pandas\core\groupby.py", line 2690, in _get_grouper
raise KeyError(gpr)
KeyError: 1

如何使用列号进行 pandas groupby?

最佳答案

看来你需要rolling + 一些像sum这样的函数:

df = df.rolling(2,axis=1, min_periods=1).sum()
print (df)
col1 col2 col3 col4
0 12.0 34.0 35.0 27.0
1 13.0 36.0 38.0 31.0
2 14.0 38.0 41.0 35.0

但也许需要这样的东西:

for i in range(1, df.shape[1]):
grouped = df.groupby(df.columns[[i-1, i]].tolist())

关于python pandas - groupby 使用列号/位置(用于循环),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46927638/

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