如何将包含一列句子和一列分数的数据框转换为一列包含一列单词和平均分数?

时间:2016-05-30 01:52:24

标签: python pandas split

我有一个类似于此的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模糊定义的重新索引的全部错误)。

2 个答案:

答案 0 :(得分:3)

您可以使用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

答案 1 :(得分:0)

您可以在DataFrame上使用iterrows方法并将每一行处理为新的DataFrame,然后将它们连接在一起。然后,您需要处理重复的单词。

string模块(在标准库中)有一些字符集可以帮助您过滤掉非字母数字的值。