【发布时间】:2017-08-24 08:43:03
【问题描述】:
在 pandas 中,我一直在寻找一个通用流程来按特定列对数据帧进行分组,对组执行重要的操作,然后再次将组重新组成一个大数据帧(通过有效地将它们堆叠在顶部彼此的)。
假设我有一个 DataFrame df:
+----+-------+---+---+---+
| | A | B | C | D |
+----+-------+---+---+---+
| 0 | Green | 1 | 4 | 5 |
| 1 | Red | 2 | 3 | 2 |
| 2 | Red | 1 | 4 | 3 |
| 3 | Green | 2 | 2 | 2 |
| 4 | Green | 1 | 1 | 1 |
| 5 | Blue | 2 | 1 | 5 |
| 6 | Red | 2 | 1 | 6 |
| 7 | Blue | 7 | 8 | 9 |
| 8 | Green | 7 | 6 | 5 |
| 9 | Red | 0 | 9 | 0 |
| 10 | Blue | 4 | 5 | 4 |
+----+-------+---+---+---+
我想 groupby() 列 A,然后对每个组执行操作。通常,此操作涉及通过将一行中的值与该行中的值对所有行进行比较来创建新行,因此我不会说它可以通过应用于组的 lambda 函数来完成。然后,我想将这些组重新组合到数据框中,有效地采用与上述相同的格式,但插入了行。
到目前为止,我的一般做法是“缓慢而愚蠢”的方式,即:
group_list = []
g = df.groupby("A")
for i, group in g:
###Perform some weird operation on group that can't really be reduced to a
#lambda function applied to each group.
group_list.append(group)
reconstituted = group_list[0]
for i in range(1,len(group_list)):
reconstituted = reconstituted.append(group_list[i], ignore_index=True)
显然,这不是特别熊猫式的,所以这是我的问题 - 对组本身进行操作然后重组它们的更好方法是什么?
【问题讨论】:
-
不确定你想做什么,但可以按列的值排序吗? df.sort_values("A") 或 df.sort("A")
标签: python pandas dataframe group-by pandas-groupby