簡體   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