我想计算一个数据框中的一个列表中的单词出现在另一个数据框中的另一个列表中的频率。 我的数据如下所示:
df6=pd.DataFrame({'variable':'irreplacable','Words':[['hi','ciao'],
['mine','yours']]})
df7=pd.DataFrame({'text':[['hi','is','this','ciao','ciao'],['hi','ciao']]})
所以现在我想计算 df7.text 的每个单元格中“hi”和“ciao”出现的频率,并在 df7 中创建一个包含此计数的新列
我尝试创建一个“双”for 循环:
count_word = 0
for index,rows in df7.iterrows():
for word in df7.text:
if word in df6.iloc[0,1]:
count_word = count_word +1
df7['counter']=count_word
使用此代码,输出如下所示
text counter
0 [hi, is, this, ciao, ciao] 0
1 [hi, ciao] 0
而不是 3 和 2 作为计数器
最佳答案
使用带有 sum
的生成器来计算 True
值,并使用 in
来测试成员资格:
df7['counter']= df7.text.apply(lambda x: sum(i in df6.iloc[0,1] for i in x))
print (df7)
text counter
0 [hi, is, this, ciao, ciao] 3
1 [hi, ciao] 2
稍微修改解决方案,用于测试新列的所有其他值:
for v in df6['Words']:
df7[', '.join(v)]= df7.text.apply(lambda x: sum(i in v for i in x))
print (df7)
text hi, ciao mine, yours
0 [hi, is, this, ciao, ciao] 3 0
1 [hi, ciao] 2 0
关于python - python计算不同数据帧中两个列表之间的匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56684807/