我有一个大的数据框(价格),其中包含长说明和与该说明相关的价格。我生成了另一个数据框(字),该数据框保留了那些长说明中包含的所有唯一字。我想做的是从价格数据框中获取特定单词的平均价格,然后将其存储在单词数据框中,与单词所在的行相同。
我设法获得了特定单词的平均值,但是当我尝试遍历单词数据帧时,它花费了太多时间。
这适用于单个值:
prices.loc[prices['TEXT'].str.contains("PREMIUM", na=False)]['PRICE'].mean()
这是我尝试运行的循环:
for ind in words.index:
words['avgs'][ind]=prices.loc[prices['TEXT'].str.contains(words['WORD'][ind], na=False)]['PRICE'].mean()
有什么方法可以使此代码更快?谢谢!
您需要以下内容:
# create example dataframes
prices = pd.DataFrame({'TEXT': ['this is a sentence', 'hello world', 'apple orange strawberry'],
'PRICE': [1000, 2000, 3000]})
words = pd.DataFrame({'WORD':['world', 'orange']})
TEXT PRICE
0 this is a sentence 1000
1 hello world 2000
2 apple orange strawberry 3000
WORD
0 world
1 orange
解决方案:
m = prices['TEXT'].str.contains('|'.join(words['WORD']))
prices.loc[m, 'PRICE'].mean()
2500.0