【问题标题】:how to count the occurences of a value如何计算一个值的出现次数
【发布时间】:2021-07-16 13:25:06
【问题描述】:

如何使用数据框计算直方图的出现次数

d = {'color': ["blue", "green", "yellow", "red, blue", "green, yellow", "yellow, red, blue"],}
df = pd.DataFrame(data=d)

你是怎么走的

color
blue
green
yellow
red, blue
green, yellow
yellow, red, blue

color occurance
blue 3
green 2
yellow 3

【问题讨论】:

    标签: pandas dataframe histogram


    【解决方案1】:

    让我们尝试 split 通过正则表达式 ,s\* 使用零个或多个空格的逗号,然后将 explode 插入行并使用 value_counts 获取值的计数:

    s = (
        df['color'].str.split(r',\s*')
            .explode()
            .value_counts()
            .rename_axis('color')
            .reset_index(name='occurance')
    )
    

    或者可以split然后展开stack

    s = (
        df['color'].str.split(r',\s*', expand=True)
            .stack()
            .value_counts()
            .rename_axis('color')
            .reset_index(name='occurance')
    )
    

    s:

        color  occurance
    0    blue          3
    1  yellow          3
    2   green          2
    3     red          2
    

    【讨论】:

      【解决方案2】:

      这是使用.str.get_dummies()的另一种方式

      df['color'].str.get_dummies(sep=', ').sum()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-05-12
        • 2017-09-03
        • 2013-12-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多