繁体   English   中英

在熊猫数据框中的一个列中有多个值时如何计算值计数

[英]how to calculate value counts when we have more than one value in a colum in pandas dataframe

df

Name
Sri
Sri,Ram
Sri,Ram,kumar
Ram

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

 df["Name"].values_count()

我想要的输出是

 Sri     3
 Ram     3
 Kumar   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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM