需要從資料幀中進行單詞分布計數。有誰知道怎么修?
原始資料:
word
apple pear
pear
best apple pear
所需的輸出:
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
uj5u.com熱心網友回復:
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/362564.html
