包含单词列表的列的单词分数总和 - python

我有一个词专栏:

> print(df['words'])
0       [awww, thats, bummer, shoulda, got, david, car...   
1       [upset, that, he, cant, update, his, facebook,...   
2       [dived, many, time, ball, managed, save, rest,...   
3       [whole, body, feel, itchy, like, it, on, fire]   
4       [no, it, not, behaving, at, all, im, mad, why,...   
5       [not, whole, crew]

另一个用于每个单词的“情感”值的情感栏:

> print(sentiment) 
           abandon  -2
0        abandoned  -2
1         abandons  -2
2         abducted  -2
3        abduction  -2
4       abductions  -2
5            abhor  -3
6         abhorred  -3
7        abhorrent  -3
8           abhors  -3
9        abilities   2
...

对于df['words']中的每一行单词,我想总结它们各自的情感值。对于情绪中不存在的单词,等于0。

这是我到目前为止所拥有的:

df['sentiment_value'] = Sum(df['words'].apply(lambda x: ''.join(x+x for x in sentiment))

预期结果

print(df['sentiment_value'])
0        -5   
1         2   
2        15  
3        -6   
4        -8   
...

参考方案

如果您将分数设为系列,则以单词作为标签:

In [11]: s  # e.g. sentiment.set_index("word")["score"]
Out[11]:
abandon     -2
abandoned   -2
abandons    -2
abducted    -2
abduction   -2
Name: score, dtype: int64

然后,您可以查找列表的分数:

In [12]: s.loc[["abandon", "abducted"]].sum()
Out[12]: -4

因此,适用条件为:

df['words'].apply(lambda ls: s.loc[ls])

如果您需要支持缺少的单词(不在s中),则可以使用reindex:

In [21]: s.reindex(["abandon", "abducted", "missing_word"]).sum()
Out[21]: -4.0

df['words'].apply(lambda ls: s.reindex(ls))

Python-Excel导出 - python

我有以下代码:import pandas as pd import requests from bs4 import BeautifulSoup res = requests.get("https://www.bankier.pl/gielda/notowania/akcje") soup = BeautifulSoup(res.cont…

Python:如何根据另一列元素明智地查找一列中的空单元格计数? - python

df = pd.DataFrame({'user': ['Bob', 'Jane', 'Alice','Jane', 'Alice','Bob', 'Alice'], 'income…

R'relaimpo'软件包的Python端口 - python

我需要计算Lindeman-Merenda-Gold(LMG)分数,以进行回归分析。我发现R语言的relaimpo包下有该文件。不幸的是,我对R没有任何经验。我检查了互联网,但找不到。这个程序包有python端口吗?如果不存在,是否可以通过python使用该包? python参考方案 最近,我遇到了pingouin库。

用大写字母拆分字符串,但忽略AAA Python Regex - python

我的正则表达式:vendor = "MyNameIsJoe. I'mWorkerInAAAinc." ven = re.split(r'(?<=[a-z])[A-Z]|[A-Z](?=[a-z])', vendor) 以大写字母分割字符串,例如:'我的名字是乔。 I'mWorkerInAAAinc”变成…

Python:传递记录器是个好主意吗? - python

我的Web服务器的API日志如下:started started succeeded failed 那是同时收到的两个请求。很难说哪一个成功或失败。为了彼此分离请求,我为每个请求创建了一个随机数,并将其用作记录器的名称logger = logging.getLogger(random_number) 日志变成[111] started [222] start…