将字典应用回数据框架

2024-04-16 06:07:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个不是很Python的方式来做我想要的,但不知道是否有一个更快的方式,因为这不适合规模。你知道吗

d = {'Text' : pandas.Series([['A','B'],['A','C'],['D']])}
Combined['Text'] = pandas.DataFrame(d)
word_model = {"A": 0.1, "B": 0.25, "C": 0.33, "D":1.01}
Combined['model_score'] = 0
for i in xrange(Combined.shape[0]):
    words = Combined['Text'][i]
    wordlist = words.split(' ')
    for j in xrange(len(wordlist)):
        Combined['model_score'][i] = Combined['model_score'][i] + word_model[wordlist[j]]
    Combined['model_score'][i] = Combined['model_score'][i]/(j+1)

这为我们提供了综合的['model_score']取值:

0.175
0.215
1.01

Tags: textindataframepandasformodel方式word
1条回答
网友
1楼 · 发布于 2024-04-16 06:07:51

当然,这是另一种使用pd.Series.apply的方法。你知道吗

import pandas as pd

df = pd.DataFrame({'Text': [['A', 'B'], ['A', 'C'], ['D']]})

d = {'A': 0.1, 'B': 0.25, 'C': 0.33, 'D':1.01}

df['Avg Score'] = df['Text'].apply(lambda x: sum(map(d.get, x)) / len(x))

#      Text  Avg Score
# 0  [A, B]      0.175
# 1  [A, C]      0.215
# 2     [D]      1.010

如果需要将默认值设置为0.5(例如):

df['Avg Score'] = df['Text'].apply(lambda x: sum((d.get(i, 0.5) for i in x)) / len(x))

相关问题 更多 >