是否可以使用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
的变体也都失败了。
我希望将列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
答案 0 :(得分:2)
从the docs开始,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')
答案 1 :(得分:2)
您可以使用字典进行分组,但是(与操作中的任何组一样)您需要先设置索引列。
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])]