假设我有以下数据框df1
:
A B C D
0 foo one 1 0
1 bar two 2 1
2 foo two 3 0
3 bar two 4 1
4 foo two 5 0
5 bar two 6 1
6 foo one 7 0
7 foo two 8 1
我想将其转换为数据框df2
,如下所示:
A B C D
foo [one,two] [1,3,5,7,8] 0
bar [two] [2,4,6] 1
更准确地说:
按
A
分组,即A
列是索引,每行A
的值都是唯一的列
B
和C
包含出现的值的聚合集。对于A = "foo"
,B
是"one"
或"two"
,而对于>“酒吧”
它只是“两个”
。- 从逻辑上讲,这应该是一个集合,其中出现的每个值都只出现一次。它可能是一个 Python
set
,但我也想问用 pandas 表示它的最优雅的方式是什么
- 从逻辑上讲,这应该是一个集合,其中出现的每个值都只出现一次。它可能是一个 Python
列
D
不包含集合,因为对于foo
D
始终为 0,而对于bar
> 它始终为 1。如果索引值和列值之间始终存在 1:1 关系,则该列不应包含集合。
我预计会有一个像 df1.groupby("A").aggregate_like_this()
这样的单行聚合,但到目前为止我还没有找到它。
最佳答案
使用groupby
+ agg
:
f = {'B' : lambda x: np.unique(x).tolist(),
'C' : lambda x: np.unique(x).tolist(),
'D' : 'first'
}
df.groupby('A', as_index=False).agg(f).reindex(columns=df.columns)
A B C D
0 bar [two] [2, 4, 6] 1
1 foo [one, two] [1, 3, 5, 7, 8] 0
<小时/>
如果您无法提前确定 A
的哪些值与 D
具有 1:1 关系,请使用 groupby
+ 进行检查>nunique
,然后相应地过滤您的数据集。
x = df.groupby('A').D.nunique().eq(1)
df = df[df.A.isin(x[x].index)]
df
A B C D
1 bar two 2 1
3 bar two 4 1
5 bar two 6 1
df.groupby('A', as_index=False).agg(f).reindex(columns=df.columns)
A B C D
0 bar [two] [2, 4, 6] 1
关于python - 将 pandas 数据框分组并将多个值收集到集合中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47054318/