[英]Pandas merge on aggregated columns
假设我创建了一个DataFrame:
import pandas as pd
df = pd.DataFrame({"a": [1,2,3,13,15], "b": [4,5,6,6,6], "c": ["wish", "you","were", "here", "here"]})
像这样:
a b c
0 1 4 wish
1 2 5 you
2 3 6 were
3 13 6 here
4 15 6 here
...然后按几列分组和汇总......
gb = df.groupby(['b','c']).agg({"a": lambda x: x.nunique()})
产生以下结果:
a
b c
4 wish 1
5 you 1
6 here 2
were 1
是否可以将df
与新聚合的表gb
合并,以便在df中创建一个新列,包含来自gb
的相应值? 像这样:
a b c nc
0 1 4 wish 1
1 2 5 you 1
2 3 6 were 1
3 13 6 here 2
4 15 6 here 2
我尝试做最简单的事情:
df.merge(gb, on=['b','c'])
但是这给出了错误:
KeyError: 'b'
这是有道理的,因为分组表具有多索引而b
不是列。 所以我的问题是双重的:
gb
DataFrame的多索引转换回列(以便它具有b
和c
列)吗? df
和gb
吗? 每当你想将groupby操作中的一些聚合列添加回df时你应该使用transform
,这会生成一个其索引与你的orig df对齐的Series:
In [4]:
df['nc'] = df.groupby(['b','c'])['a'].transform(pd.Series.nunique)
df
Out[4]:
a b c nc
0 1 4 wish 1
1 2 5 you 1
2 3 6 were 1
3 13 6 here 2
4 15 6 here 2
无需重置索引或执行其他合并。
使用reset_index()
有一种简单的方法。
df.merge(gb.reset_index(), on=['b','c'])
给你
a_x b c a_y
0 1 4 wish 1
1 2 5 you 1
2 3 6 were 1
3 13 6 here 2
4 15 6 here 2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.