gpt4 book ai didi

python - pd.Serie 的每一行的平均 "score"基于其通过另一个分数 Series 映射的内容

转载 作者:太空宇宙 更新时间:2023-11-04 02:05:35 27 4
gpt4 key购买 nike

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

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

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

最佳答案

在 pandas 中处理字符串数据很慢,因此请使用 Seriesmean 的 map 列表理解:

from statistics import mean

L = [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.340000
1 0.760000
2 0.263333
dtype: 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]

关于python - pd.Serie 的每一行的平均 "score"基于其通过另一个分数 Series 映射的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54822308/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com