[英]Pandas Dataframe: Count unique words in a column and return count in another column
[英]Pandas DataFrame: Find unique words in string column, count their occurrence and sum values in another column on condition
我有以下 dataframe:
import pandas as pd
data = {'String': ['foo bar hello world this day', 'foo bar', 'hello bar world'],
'Value' : [ 10, 2, 5]}
df = pd.DataFrame(data, columns = ['String', 'Value'])
我想知道的是單詞出現在'String'
中時的唯一單詞、它們的出現和值的總和。 因此,所需的 output 是:
Unique word Occurrence Value sum
bar 3 17
world 2 15
foo 2 12
hello 2 15
day 1 10
this 1 10
我可以通過以下方式獲得獨特的單詞及其出現:
pd.Series(' '.join(df.String).split()).value_counts()
我應該如何添加價值總和?
我的 pandas 版本 = 0.24.2
對於接受的答案,pandas 的版本應該至少升級到0.25.0
你可以這樣做:
df['Unique Word'] = df['String'].str.split()
res = df.drop('String', 1).explode('Unique Word').groupby(['Unique Word'])['Value'].agg(['count', 'sum']).reset_index()
print(res)
Output
Unique Word count sum
0 bar 3 17
1 day 1 10
2 foo 2 12
3 hello 2 15
4 this 1 10
5 world 2 15
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.