[英]How do I convert a dataframe consisting of a column of sentences and a column of scores into one with a column of words and average scores?
我有一個類似於此的Pandas數據幀:
sentence score
"This is a sentence." 5
"Another sentence?" 8
我想要一個類似於此的東西:
word total_score count normalized_score
"sentence" 13 2 6.5
"this" 5 1 5
等等
我該怎么做呢? 我的想法是刪除所有非字母數字字符,然后在包含句子的所有單元格上使用split() ,然后將這些單詞組合成一個集合,然后使用該集合迭代原始數據幀,計算單詞的次數使用和相應的分數。 然而,這似乎是不優雅的,並且可能非常低效。 有一個更好的方法嗎?
注意:不要擔心停用詞並假設所有單詞都用空格分隔
編輯:
實際數據的頭部(在應用wide = df.apply(lambda x: pd.Series(x['score'], index=x['sentence']), axis=1)
)之后是:
score title
0 1 [javascript, kml, compressor, for, google, maps]
1 3 [ktbyte, challenge, programming, game, for, 9, 15, year, olds]
2 4 [worldometers, real, time, world, statistics]
3 1 [apple, s, sales, policies]
4 72 [report, suggests, 21, hours, is, the, ideal, work, week]
5 3 [new, paper, shows, how, to, get, control, without, injecting, new, code]
奇怪的是,unutbu的解決方案適用於前5行,但不適用於添加第6行。 當添加第六個時,Python返回ValueError: cannot reindex from a duplicate axis
(這似乎是Panda模糊定義的重新索引的全部錯誤)。
您可以使用df.itertuples
迭代df
行並構建表單的長格式DataFrame:
In [86]: longframe
Out[86]:
score word
0 5 This
1 5 is
2 5 a
3 5 sentence
4 8 Another
5 8 sentence
6 8 sentence
獲得此格式的數據后,您可以word
分組並對每個單詞的分數求和,並使用value_counts
計算每個單詞的頻率。
import pandas as pd
df = pd.DataFrame(
{'score': [5, 8], 'sentence': ["This is a sentence.", "Another sentence sentence?"]})
df['sentence'] = df['sentence'].str.findall(r'\w+')
longframe = pd.DataFrame([(row.score, word) for row in df.itertuples()
for word in row.sentence],
columns=['score', 'word'])
score = longframe.groupby('word')['score'].sum()
count = longframe['word'].value_counts()
result = pd.DataFrame({'score':score, 'count':count, 'normalized_score':score/count})
result = result.reset_index()
result = result.rename(columns={'index':'word'})
print(result)
產量
word count normalized_score score
0 Another 1 8.0 8
1 This 1 5.0 5
2 a 1 5.0 5
3 is 1 5.0 5
4 sentence 3 7.0 21
您可以在iterrows
上使用iterrows
方法並將每行處理為新的DataFrame,然后將它們連接在一起。 然后,您需要處理重復的單詞。
string
模塊(在標准庫中)有一些字符集合,可以幫助您過濾掉非字母數字的值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.