Pandas按字典分组

8

能否使用字典对列的元素进行分组?

例如:

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
2个回答

5

根据文档,该字典必须从标签映射到组名称,因此如果将'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')

谢谢 - 感谢您关于快速创建新列的提示。 - Christopher Short

5

你可以使用字典进行分组,但是(与任何分组操作一样),你需要先设置索引列。

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])]

谢谢(还有Mariu的贡献)-那么只有数据框中的列才能进行自身分组? - Christopher Short
意外的“回车” - Christopher Short
索引需要保留 - 它是5分钟的时间间隔(超过13年)。所以,如果我想要像上面的(一,二)和(三)的分组,适当的选项是创建一个具有该映射的新列,然后在该新列上进行分组? - Christopher Short
@ChristopherShort:如果你真的不能改变索引,那么最好通过创建分组列来实现,详见我的编辑答案。 - Marius

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接