python - python计算不同数据帧中两个列表之间的匹配

标签 python pandas list

我想计算一个数据框中的一个列表中的单词出现在另一个数据框中的另一个列表中的频率。 我的数据如下所示:

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/

相关文章:

python - 列表中每个单词的首字母大写;栏全部大写的单词

java - Java 中按日期顺序对 List<String[]> 进行排序

python - 多行正则表达式替换

python - 保存带有时间戳的视频帧

python - Scrapy爬取数据到mysql

python - Pandas 将列中的所有值置于特定值之后 1

Python26、Win32、ZBar - 导入错误 : DLL load failed

python - 按小时对 Pandas 数据框进行分组的问题

python - 基于两列在其他 DataFrame 中查找值

python - 从 Python 创建动态 SQL 查询