【问题标题】:How to aggregate and then expand frequency values in pandas dataframe如何在熊猫数据框中聚合然后扩展频率值
【发布时间】:2020-10-14 04:37:11
【问题描述】:

我有一个如下形状的数据框:

import pandas as pd
l = []

l.append({"t":'a', 'w': 'x'})
l.append({"t":'a', 'w': 'x'})
l.append({"t":'a', 'w': 'y'})
l.append({"t":'b', 'w': 'y'})
l.append({"t":'b', 'w': 'y'})
l.append({"t":'b', 'w': 'z'})
l.append({"t":'b', 'w': 'y'})
df = pd.DataFrame(l)

我想首先基于 t colmun 进行聚合,然后在 w 列中展开以显示每个项目的频率。换句话说,我想要以下结果:

   t  w  freq
0  a  x     2
1  a  y     1
2  b  y     3
3  b  z     1

这怎么可能?我尝试了很多不同的方法都没有结果。

【问题讨论】:

标签: python pandas dataframe aggregate


【解决方案1】:

value_counts 现在接受两列

df.value_counts(['t','w'])
Out[6]: 
t  w
b  y    3
a  x    2
b  z    1
a  y    1
dtype: int64
 

【讨论】:

    【解决方案2】:

    df我们试试groupby().value_counts():

    df.groupby(['t'])['w'].value_counts().reset_index(name='freq')
    

    另外,groupby().size():

    df.groupby(['t','w']).size().reset_index(name='freq')
    

    输出:

       t  w  freq
    0  a  x     2
    1  a  y     1
    2  b  y     3
    3  b  z     1
    

    【讨论】:

      猜你喜欢
      • 2023-02-25
      • 2021-01-05
      • 2022-01-21
      • 1970-01-01
      • 2018-01-07
      • 2019-08-02
      • 2020-12-08
      • 1970-01-01
      • 2021-05-26
      相关资源
      最近更新 更多