【发布时间】:2021-05-03 09:52:28
【问题描述】:
我有一个数据框,其中单词作为索引,另一列中有相应的情绪分数。然后,我有另一个数据框,其中有一列带有多行的单词列表(令牌列表)。所以每一行都会有一个包含不同列表的列。我想找到特定列表的平均情绪得分。这必须针对大量行进行,因此效率很重要。 我想到的一种方法如下:
import pandas as pd
a = [['a', 'b', 'c'], ['hi', 'this', 'is', 'a', 'sample']]
df = pd.DataFrame()
df['tokens'] = a
'''
df
words
0 [a, b, c]
1 [hi, this, is, a, sample]
'''
def find_score(tokenlist, ref_df):
# ref_df contains two cols, 'tokens' and 'score'
temp_df = pd.DataFrame()
temp_df['tokens'] = tokenlist
return temp_df.merge(ref_df, on='tokens', how='inner')['sentiment_score'].mean(axis=0)
# this should return score
df['score'] = df['tokens'].apply(find_score, axis=1, args=(ref_df))
# each input for find_score will be a list
在不为每个列表创建数据框的情况下,有没有更有效的方法?
【问题讨论】:
标签: python pandas list dataframe multiprocessing