是否可以使用字典对列的元素进行分组?
例如:
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
的变体也都失败了。
我想将 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
最佳答案
来自 the docs , dict 必须从 labels 映射到组名称,因此如果将 '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')
关于python - Pandas groupby 与 dict,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25736127/