Python 计算包含两个精确字符串的行数

Python 计算包含两个精确字符串的行数,python,pandas,Python,Pandas,这是我的df1 df1 = pd.DataFrame( [ ["apple,orange,milk"], ["orange,watermelon,apple"], ["milk,banana,apple"] ], columns=['fruits'] ) df1 0 apple,orange,milk 1 orange,watermelon,apple 2 milk,banana,apple 这是我的df2 df2

这是我的df1

df1 = pd.DataFrame(
    [
        ["apple,orange,milk"],
        ["orange,watermelon,apple"],
        ["milk,banana,apple"]
    ], 
    columns=['fruits']
)

df1

0 apple,orange,milk
1 orange,watermelon,apple
2 milk,banana,apple
这是我的df2

df2 = pd.DataFrame(["apple","orange","banana"], columns=['fruits'])

df2

0 apple
1 orange
2 banana
我想找出两个字符串同时出现的行数。例如,当苹果和牛奶一起出现在行中时,计算行数 这是我的密码

for i,row in df2.iterrows():
    for j,rows in df1.iterrows():
        b = (rows.str.contains('(?:\s|\S|[,;])milk(?:\s|\S|[,;])') & rows.str.contains('(?:\s|\S|[,;])+df2.iloc[i]+(?:\s|\S|[,;])')).sum()
        if b>0:
            c=c+1
    print(c)
我从这里得到的输出总是0

0
0
0
输出应为:

2
1
1

首先,数据帧的构造函数不起作用,因为它拼写错误,并且提供了错误的输入。更正为:

df1 = pd.DataFrame(["apple,orange,milk", "orange,watermelon,apple", "milk,banana,apple"])
df2 = pd.DataFrame(["apple", "orange", "banana"])
第二,你的问题不清楚。如果我要换一种说法,我会这样说:“我想找出两个搜索词在同一个单元格中出现的次数,超过一组搜索词。”。我不是100个人,但这更清楚。也就是说


创建一个使用字符串的函数,该字符串包含两个特定参数(以及用于标识其应搜索位置的必要项):

这样做的目的是询问整个列中是否有任何行包含搜索词
s1
s2
。然后将两者相交,并对结果数求和。执行:

df2[0].apply(lambda i: find2(df1, 0, 'milk', i))
Out[10]: 
0    2
1    1
2    1
Name: 0, dtype: int64

首先,数据帧的构造函数不起作用,因为它拼写错误,并且提供了错误的输入。更正为:

df1 = pd.DataFrame(["apple,orange,milk", "orange,watermelon,apple", "milk,banana,apple"])
df2 = pd.DataFrame(["apple", "orange", "banana"])
第二,你的问题不清楚。如果我要换一种说法,我会这样说:“我想找出两个搜索词在同一个单元格中出现的次数,超过一组搜索词。”。我不是100个人,但这更清楚。也就是说


创建一个使用字符串的函数,该字符串包含两个特定参数(以及用于标识其应搜索位置的必要项):

这样做的目的是询问整个列中是否有任何行包含搜索词
s1
s2
。然后将两者相交,并对结果数求和。执行:

df2[0].apply(lambda i: find2(df1, 0, 'milk', i))
Out[10]: 
0    2
1    1
2    1
Name: 0, dtype: int64

首先,正如@ifly6所发布的,您的问题需要修复数据帧的创建

其次,我假设(与另一个答案不同)您希望找到
df2
中定义的每个
df1
行显示多少连续字符串。一种解决方案是首先从
df2
创建可能的连续字符串,然后遍历
df1
,查看是否存在匹配项以及匹配项包含多少单词。比如说,

import pandas as pd
import itertools

def contiguous_indices(xs):
    n = len(xs)
    indices = list(range(n+1))
    for i,j in itertools.combinations(indices,2):
        yield xs[i:j]

df1=pd.DataFrame(["apple,orange,milk","orange,watermelon,apple","milk,banana,apple"])
df2=pd.DataFrame(["apple","orange","banana"])

# Define the list of possible contiguous strings in df2
s_list = []
for indx_list in contiguous_indices(range(df2[0].size)):
    s = ''
    for indx in indx_list:
        s += df2[0][indx] + ','
    s_list.append(s[:-1])
print(s_list) 
# ['apple', 'apple,orange', 'apple,orange,banana', 'orange', 'orange,banana', 'banana']

# Iterate through df1 and count max number of contiguous strings matches
for i, s1 in df1.iterrows():
    c_max = 0
    s_save = ''
    for s in s_list:
        if s in s1[0] and len(s.split(',')) > c_max:
            c_max = len(s.split(','))
            s_save = s
    print(i, c_max, s_save)
输出将是:

0 2 apple,orange
1 1 apple
2 1 apple

首先,正如@ifly6所发布的,您的问题需要修复数据帧的创建

其次,我假设(与另一个答案不同)您希望找到
df2
中定义的每个
df1
行显示多少连续字符串。一种解决方案是首先从
df2
创建可能的连续字符串,然后遍历
df1
,查看是否存在匹配项以及匹配项包含多少单词。比如说,

import pandas as pd
import itertools

def contiguous_indices(xs):
    n = len(xs)
    indices = list(range(n+1))
    for i,j in itertools.combinations(indices,2):
        yield xs[i:j]

df1=pd.DataFrame(["apple,orange,milk","orange,watermelon,apple","milk,banana,apple"])
df2=pd.DataFrame(["apple","orange","banana"])

# Define the list of possible contiguous strings in df2
s_list = []
for indx_list in contiguous_indices(range(df2[0].size)):
    s = ''
    for indx in indx_list:
        s += df2[0][indx] + ','
    s_list.append(s[:-1])
print(s_list) 
# ['apple', 'apple,orange', 'apple,orange,banana', 'orange', 'orange,banana', 'banana']

# Iterate through df1 and count max number of contiguous strings matches
for i, s1 in df1.iterrows():
    c_max = 0
    s_save = ''
    for s in s_list:
        if s in s1[0] and len(s.split(',')) > c_max:
            c_max = len(s.split(','))
            s_save = s
    print(i, c_max, s_save)
输出将是:

0 2 apple,orange
1 1 apple
2 1 apple

为什么是熊猫?您需要将结果存储在内部吗?你是如何选择巫婆词来搜索的?对不起,我是python的初学者。我以为df2.iloc[I]可以选择要搜索的单词,但结果不是这样显示的。这是我的问题,根据“查找两个字符串同时出现的行数”输出是否正确?如果是这样,你能提供更多关于输出的解释吗?“2”应该表示有两行苹果和牛奶一起出现…谢谢我得到了这个。那么为什么要休息[1,1]行呢?另一个有效的问题是:如何选择要搜索的单词?为什么?您需要将结果存储在内部吗?你是如何选择巫婆词来搜索的?对不起,我是python的初学者。我以为df2.iloc[I]可以选择要搜索的单词,但结果不是这样显示的。这是我的问题,根据“查找两个字符串同时出现的行数”输出是否正确?如果是这样,你能提供更多关于输出的解释吗?“2”应该表示有两行苹果和牛奶一起出现…谢谢我得到了这个。那么为什么要休息[1,1]行呢?另一个有效的问题是:如何选择要搜索的单词?