gpt4 book ai didi

python - 如何将由一列句子和一列分数组成的数据框转换为由一列单词和平均分数组成的数据框?

转载 作者:行者123 更新时间:2023-11-30 22:55:06 26 4
gpt4 key购买 nike

我有一个与此类似的 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 行,但在添加第六行时则不起作用。当添加第六个时,Python 返回 ValueError:无法从重复轴重新索引(这似乎是 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

获得此格式的数据后,您可以按单词分组并对每个单词的分数求和,并使用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

关于python - 如何将由一列句子和一列分数组成的数据框转换为由一列单词和平均分数组成的数据框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37516660/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com