[英]how to calculate value counts when we have more than one value in a colum in pandas dataframe
df, df
Name
Sri
Sri,Ram
Sri,Ram,kumar
Ram
I am trying to calculate the value counts for each value. 我正在尝试计算每个值的值计数。 I am not getting my output when using 使用时我没有得到输出
df["Name"].values_count()
my desired output is, 我想要的输出是
Sri 3
Ram 3
Kumar 1
split
the column, stack
to long format, then count
: split
列, stack
为长格式,然后count
:
df.Name.str.split(',', expand=True).stack().value_counts()
#Sri 3
#Ram 3
#kumar 1
#dtype: int64
Or maybe: 或者可能:
df.Name.str.get_dummies(',').sum()
#Ram 3
#Sri 3
#kumar 1
#dtype: int64
Or concatenate before value_counts : 或在value_counts之前连接:
pd.value_counts(pd.np.concatenate(df.Name.str.split(',')))
#Sri 3
#Ram 3
#kumar 1
#dtype: int64
Timing : 时间 :
%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.