python - 将 groupby 与多个索引列或索引一起使用时

标签 python pandas

我有一个如下所示的数据框:

idx=pd.MultiIndex.from_arrays([[1,1,1,2],[1,1,2,2]])
df=pd.DataFrame(columns=idx,index=[1,2,3]).fillna(1)

现在我想根据两层列求和,首先想到的是groupbysum

df.sum(level=[0,1],axis=1)
   1     2
   1  2  2
1  2  1  1
2  2  1  1
3  2  1  1

df.groupby(level=[0, 1], axis=1).sum() #same output as above

df.groupby(df.columns.labels, axis=1).sum()#same output as above

由于我们groupby所有列,为了减少手工输入的工作量,我尝试用df.columns代替level=[0, 1],但这里显示有线输出,它将多个索引转换为元组 (这是有道理的,因为多个索引是元组列表的另一种布局)

df.groupby(df.columns,axis=1).sum()
   (1, 1)  (1, 2)  (2, 2)
1       2       1       1
2       2       1       1
3       2       1       1

此外,当我不执行诸如 transform 之类的聚合函数时,输出恢复正常

df.groupby(df.columns,axis=1).transform('sum')
   1        2
   1  1  2  2
1  2  2  1  1
2  2  2  1  1
3  2  2  1  1

问:为什么会这样。如果 groupby 将多索引更改为 tuple ,它是否也应该更改 transform 调用?

最佳答案

我认为这与 transform 相关,它被编码为处理数据帧中的列。即使您按行分组,转换仍然只将列传递给函数。

def f(x):
    print(x)

df.groupby(df.columns,axis=1).transform(f)

输出:

1  1    1
   1    1
Name: 1, dtype: int64
1  1    1
   1    1
Name: 2, dtype: int64
1  1    1
   1    1
Name: 3, dtype: int64
   1   
   1  1
1  1  1
2  1  1
3  1  1
1  2    1
Name: 1, dtype: int64
1  2    1
Name: 2, dtype: int64
1  2    1
Name: 3, dtype: int64
2  2    1
Name: 1, dtype: int64
2  2    1
Name: 2, dtype: int64
2  2    1
Name: 3, dtype: int64

传递给自定义函数 f 的每个系列的名称是索引,但只有一列被传递。并非所有列。

关于python - 将 groupby 与多个索引列或索引一起使用时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54318915/

相关文章:

python - 在 pandas DataFrame 中查找和替换行特定数据的最快方法

python - 对数据集的所有连接节点进行分组

python - 按 ListProperty (NDB) 对查询进行排序

javascript - 使用 jquery 和 javascript 改变图像的大小

python - 使用PyInstaller编译python程序后如何输入参数

python - curl 到 python 请求错误 : "no api key supplied"

python - pandas 人类索引排序

python - 在 ST2 中导入 Pandas 时出现 Numexpr 错误

python - 带有 pyarrow 的消费者-生产者模式

python - python中的透视投影和旋转