Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/159.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python pandas-使用列号/位置分组(用于循环)_Python_Pandas_Dataframe - Fatal编程技术网

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

python pandas-使用列号/位置分组(用于循环),python,pandas,dataframe,Python,Pandas,Dataframe,我想在多个groupby中连续循环我的数据帧,并且我想使用列编号(或者是列位置?)作为groupby索引ie 数据帧 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,

我想在多个groupby中连续循环我的数据帧,并且我想使用列编号(或者是列位置?)作为groupby索引ie

数据帧

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
如何使用列号进行分组?

似乎您需要+一些函数,如
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())

你能解释一下你的问题吗?因为这里似乎不可能使用
groupby
。我想按列对数据帧进行分组(每个循环2列),并统计这2列中出现的类似项配对。所以第一个循环类似于
df.groupby(['col1','col2'])
,第二个循环类似于
df.groupby(['col2','col3'])
。但是我想要的不是列名,而是列索引。示例:第一个循环:
df.groupby([0,1])
,第二个循环:
df.groupby([1,2])
,等等。我不想对它求和,我想对它进行分组,并计算两列之间类似的项目配对。我编辑答案。但需要将列的位置转换为列名称。groupby+位置尚未实现。谢谢,这是我想知道的信息(groupby+位置)。我实际上是从R代码翻译过来的。只是一个与此相关的问题。我们如何检查这个功能(groupby+position)是否将在下一个pandas版本中实现?我认为最好的方法是在中创建新线程。