[英]Word Count Distribution Pandas Dataframe
需要從 dataframe 中進行字數分布計數。 有誰知道如何解決?
原始數據:
word
apple pear
pear
best apple pear
所需的 output:
word count
apple 2
pear 3
best 1
運行此代碼:
rawData = pd.concat([rawData.groupby(rawData.word.str.split().str[0]).sum(),rawData.groupby(rawData.word.str.split().str[-1]).sum()]).reset_index()
收到此錯誤:
ValueError: cannot insert keyword, already exists
使用str.split
然后explode
每個列表分解為一列,最后使用value_counts
計算每個單詞的出現次數:
out = df['word'].str.split().explode().value_counts()
print(out)
# Output:
pear 3
apple 2
best 1
Name: word, dtype: int64
一步步:
>>> df['word'].str.split()
0 [apple, pear]
1 [pear]
2 [best, apple, pear]
Name: word, dtype: object
>>> df['word'].str.split().explode()
0 apple
0 pear
1 pear
2 best
2 apple
2 pear
Name: word, dtype: object
>>> df['word'].str.split().explode().value_counts()
pear 3
apple 2
best 1
Name: word, dtype: int64
更新
要准確獲得您的預期結果:
>>> df['word'].str.split().explode().value_counts(sort=False) \
.rename('count').rename_axis('word').reset_index()
word count
0 apple 2
1 pear 3
2 best 1
更新 2
按國家/地區獲取值計數:
data = {'country': [' US', ' US', ' US', ' UK', ' UK', ' UK', ' UK'],
'word': ['best pear', 'apple', 'apple pear',
'apple', 'apple', 'pear', 'apple pear ']}
df = pd.DataFrame(data)
out = df.assign(word=df['word'].str.split()) \
.explode('word').value_counts() \
.rename('count').reset_index()
print(out)
# Output:
country word count
0 UK apple 3
1 UK pear 2
2 US apple 2
3 US pear 2
4 US best 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.