【问题标题】:how to calculate value counts when we have more than one value in a colum in pandas dataframe当我们在熊猫数据框中的一列中有多个值时如何计算值计数
【发布时间】:2017-10-29 02:44:40
【问题描述】:

df,

Name
Sri
Sri,Ram
Sri,Ram,kumar
Ram

我正在尝试计算每个值的值计数。 使用时我没有得到输出

 df["Name"].values_count()

我想要的输出是,

 Sri     3
 Ram     3
 Kumar   1

【问题讨论】:

    标签: python pandas dataframe data-analysis


    【解决方案1】:

    split 列,stack 为长格式,然后count

    df.Name.str.split(',', expand=True).stack().value_counts()
    
    #Sri      3
    #Ram      3
    #kumar    1
    #dtype: int64
    

    或许:

    df.Name.str.get_dummies(',').sum()
    
    #Ram      3
    #Sri      3
    #kumar    1
    #dtype: int64
    

    或在value_counts之前连接:

    pd.value_counts(pd.np.concatenate(df.Name.str.split(',')))
    
    #Sri      3
    #Ram      3
    #kumar    1
    #dtype: int64
    

    时间

    %timeit df.Name.str.split(',', expand=True).stack().value_counts()
    #1000 loops, best of 3: 1.02 ms per loop
    
    %timeit df.Name.str.get_dummies(',').sum()
    #1000 loops, best of 3: 1.18 ms per loop
    
    %timeit pd.value_counts(pd.np.concatenate(df.Name.str.split(',')))
    #1000 loops, best of 3: 573 µs per loop
    
    # option from @Bharathshetty 
    from collections import Counter
    %timeit pd.Series(Counter((df['Name'].str.strip() + ',').sum().rstrip(',').split(',')))
    # 1000 loops, best of 3: 498 µs per loop
    
    # option inspired by @Bharathshetty 
    %timeit pd.value_counts(df.Name.str.cat(sep=',').split(','))
    # 1000 loops, best of 3: 483 µs per loop
    

    【讨论】:

    • 如果索引第 2 行有小写“sri”,我也想包含它
    • 如果您想忽略大小写,您可以在继续之前将其转换为小写/大写。 df.Name.str.lower()....
    • 我不确定你的意思是什么应用忽略大小写。我不认为你可以在计算价值时做ignore casestr.lower() 怎么了?
    • 值得为受启发的选项投票:)。我在想只加入并忘记猫。真的很不错。
    • 继续关注堆栈溢出尝试回答问题,学习熊猫的最佳方式。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    • 2016-04-09
    • 2021-07-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多