猿问

pd.Serie 每行的平均“分数”基于通过另一个分数系列映射的内容

我有一个(非常大的)系列,其中包含关键字(例如,每行包含多个由“-”分隔的关键字)


In[5]: word_series

Out[5]: 

0    the-cat-is-pink

1           blue-sea

2      best-job-ever

dtype: object

我有另一个系列,其中包含每个单词的分数属性(单词是索引,分数是值),例如:


In[7]: all_scores

Out[7]: 

the     0.34

cat     0.56

best    0.01

ever    0.77

is      0.12

pink    0.34

job     0.01

sea     0.87

blue    0.65

dtype: float64

我的 word_series 中的所有单词都出现在我的分数中。我试图根据 all_scores 中每个单词的平均分数,找到将分数归因于 word_series 的每一行的最快方法。如果一行是 n/a,则分数应该是分数的平均值。


我试过用这种方式应用,但它太慢了。


scores = word_series.apply(

        lambda x: all_scores[x.split('-')].mean()).fillna(

        all_scores.mean())

然后我想我可以使用 str.replace 将 all_words 拆分为列,并且可能使用这个新矩阵 M 和我的单词 M.mul(all_scores) 执行矩阵乘法类型的操作,其中 M 中的每一行都与基于索引的值匹配的 all_scores。这将是第一步,为了得到平均值,然后我可以除以每行非 na 的数量


In[9]: all_words.str.split('-', expand=True)

Out[9]: 

      0    1     2     3

0   the  cat    is  pink

1  blue  sea  None  None

2  best  job  ever  None

这样的手术可行吗?还是有另一种快速的方法来实现这一目标?


撒科打诨
浏览 193回答 2
2回答

繁星淼淼

在 Pandas 中处理字符串数据很慢,所以使用 map by Seriesand 的列表理解mean:from statistics import meanL = [mean(all_scores.get(y) for y in x.split('-')) for x in word_series]a = pd.Series(L, index=word_series.index)print (a)0    0.3400001    0.7600002    0.263333dtype: float64或者:def mean(a):    return sum(a) / len(a)L = [mean([all_scores.get(y) for y in x.split('-')]) for x in word_series]a = pd.Series(L, index=word_series.index)如果可能的一些值不匹配的附加参数np.nan,以get和使用numpy.nanmean:L = [np.nanmean([all_scores.get(y, np.nan) for y in x.split('-')]) for x in word_series]a = pd.Series(L, index=word_series.index)或者:def mean(a):    return sum(a) / len(a)L = [mean([all_scores.get(y, np.nan) for y in x.split('-') if y in all_scores.index])       for x in word_series]

慕妹3146593

这是一个方法打印(一)             words0  the-cat-is-pink1         blue-sea2    best-job-ever打印(b)      all_scoresthe         0.34cat         0.56best        0.01ever        0.77is          0.12pink        0.34job         0.01sea         0.87blue        0.65b = b.reset_index()打印(b)  index  all_scores0   the        0.341   cat        0.562  best        0.013  ever        0.774    is        0.125  pink        0.346   job        0.017   sea        0.878  blue        0.65a['score'] = a['words'].str.split('-').apply(lambda x: sum([b[b['index'] == w].reset_index()['all_scores'][0] for w in x])/len(x))输出             words     score0  the-cat-is-pink  0.3400001         blue-sea  0.7600002    best-job-ever  0.263333
随时随地看视频慕课网APP

相关分类

Python
我要回答