我有一个数据帧:
import pandas as pd
test_df = pd.DataFrame({
'_id': ['1a','2b','3c','4d'],
'column': ['und der in zu',
'Kompliziertereswort something',
'Lehrerin in zu [Buch]',
'Buch (Lehrerin) kompliziertereswort']})
还有一本字典:
{'und': 20,
'der': 10,
'in': 40,
'zu': 10,
'Kompliziertereswort': 2,
'Buch': 5,
'Lehrerin': 5}
我想向dataframe添加一个新列,它表示该行中单词值的平均值。如果这个词不在那本字典里,就应该忽略它
_id column score
1a und der in zu 20
2b Kompliziertereswort something 2
3c Lehrerin in zu [Buch] 15
4d Buch (Lehrerin) kompliziertereswort 5
我做了一些我认为很愚蠢的事情,例如:把数据框写成一个文本文件,读每一行;我列出了字典中所有的键,然后用正则表达式检查那一行是否包含单词。可能是因为括号的缘故,它不起作用
我还尝试拆分dataframe行,但它只是将其拆分为单独的字母:
for index, values in test_df.iterrows():
pos = 1
for x in values[1]:
print(pos, x)
pos += 1
首先,应将词典转换为数据帧:
然后使用pandas的explode()函数分离列中的单词并将其与d_df连接:
计算每个id的平均值:
现在您可以将row_means连接到主数据帧(test_df)并向其中添加mean列
我们可以使用字典中的键构造一个正则表达式模式,然后从每一行提取该模式的所有匹配项,然后
map
将字典中的分数d
转换为匹配字符串,并在level=0
上取mean
得到平均值结果
相关问题 更多 >
编程相关推荐