python - Pandas groupby 与 dict

标签 python pandas

是否可以使用字典对列的元素进行分组?

例如:

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/

相关文章:

python - GAE 和数据存储 - 使用 python 过滤和删除实体

python - 'utf- 8' codec can' t 解码字节 0xa3 在位置 28 : invalid start byte

python - 使用列表选择 Pandas 列

python - Pandas 创建一个新列来说明文件是否存在

python - Python Pandas 中 R 函数 'ave' 的等价物

python - 如何根据配置文件(文本或CSV)中的用户输入过滤pandas数据框配置将告诉过滤器值和过滤列

python - matplotlib.pyplot.hist 错误的规范属性

python - SQLAlchemy:是否可以在不绑定(bind) session 的情况下操作查询?

python - 使用 Regex 和 Pandas 格式化问题

python - 删除 QTableView + QAbstractItemModel 中的几行