[英]Pandas groupby with dict
是否可以使用dict对列的元素进行分组?
例如:
In [3]: df = pd.DataFrame({'A' : ['one', 'one', 'two', 'three','two', 'two', 'one', 'three'],
...: 'B' : np.random.randn(8)})
In [4]: df
Out[4]:
A B
0 one 0.751612
1 one 0.333008
2 two 0.395667
3 three 1.636125
4 two 0.916435
5 two 1.076679
6 one -0.992324
7 three -0.593476
In [5]: d = {'one':'Start', 'two':'Start', 'three':'End'}
In [6]: grouped = df[['A','B']].groupby(d)
此(和其他变体)返回一个空的groupby对象。 我使用.apply
变化.apply
都失败了。
我想将列A
的值与字典的键匹配,并将行放入由值定义的组中。 输出看起来像这样:
Start:
A B
0 one 0.751612
1 one 0.333008
2 two 0.395667
4 two 0.916435
5 two 1.076679
6 one -0.992324
End:
A B
3 three 1.636125
7 three -0.593476
从文档中 ,dict必须从标签映射到组名,所以如果你将'A'
放入索引中,这将有效:
grouped2 = df.set_index('A').groupby(d)
for group_name, data in grouped2:
print group_name
print '---------'
print data
# Output:
End
---------
B
A
three -1.234795
three 0.239209
Start
---------
B
A
one -1.924156
one 0.506046
two -1.681980
two 0.605248
two -0.861364
one 0.800431
列名和行索引都是标签 ,而你把之前'A'
到索引中,元素'A'
的值 。
如果您在索引中有其他信息使得set_index()
变得棘手,您可以使用map()
创建一个分组列:
df['group'] = df['A'].map(d)
grouped3 = df.groupby('group')
您可以使用字典进行分组,但是(与操作中的任何组一样)您需要先设置索引列。
grouped = df.set_index("A").groupby(d)
list(grouped)
# [('End', B
# A
# three -1.550727
# three 1.048730
#
# [2 rows x 1 columns]), ('Start', B
# A
# one -1.552152
# one -2.018647
# two -0.968068
# two 0.449016
# two -0.374453
# one 0.116770
#
# [6 rows x 1 columns])]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.