Python 检查同一位置的第二个数据帧(甚至作为子字符串)字符串中是否存在一个数据帧字符串
我试图在两个不同的数据帧中计算,第一个数据帧中有多少字符串包含在第二个数据帧中。例如:Python 检查同一位置的第二个数据帧(甚至作为子字符串)字符串中是否存在一个数据帧字符串,python,pandas,Python,Pandas,我试图在两个不同的数据帧中计算,第一个数据帧中有多少字符串包含在第二个数据帧中。例如: import numpy as np import pandas as pd df_1 = pd.DataFrame([["hello, world", "hello, world"]] * 3, columns=['A', 'B']) df_2 = pd.DataFrame([["hello", "hello"]] * 3,
import numpy as np
import pandas as pd
df_1 = pd.DataFrame([["hello, world", "hello, world"]] * 3, columns=['A', 'B'])
df_2 = pd.DataFrame([["hello", "hello"]] * 3, columns=['A', 'B'])
如果我选择,idx\u row=0
,我希望总和为2,因为在第二个数据框“hello,world”
中'a'
和'B'
两列都包含单词“hello,world”
对于regex或
,您可以通过|
与联接值一起使用,这意味着已测试的所有值都是针对hello
或hello
进行测试的:
idx_row = 0
a = df_1.iloc[idx_row, :].str.count('|'.join(df_2.iloc[idx_row,:])).sum()
print (a)
2
每行测试值的旧答案:
您可以使用连接第一行,然后通过中的应用中的测试值,最后一次求和Trues通过求和:
idx_row = 0
a = (pd.concat([df_2.iloc[idx_row,:], df_1.iloc[idx_row, :]], axis=1, keys=('a','b'))
.apply(lambda x: x.a in x.b, axis=1)
.sum())
print (a)
2
如果需要测试所有行(匹配索引、列值):
因此,您正在尝试查看第二个数据帧字符串(甚至作为子字符串)中是否有一个数据帧字符串位于相同的位置?如果它是
['hello','yellow']
,则总和是多少?完全相同
idx_row = 0
a = (pd.concat([df_2.iloc[idx_row,:], df_1.iloc[idx_row, :]], axis=1, keys=('a','b'))
.apply(lambda x: x.a in x.b, axis=1)
.sum())
print (a)
2
s = (pd.concat([df_2, df_1], axis=1, keys=('a','b'))
.stack()
.apply(lambda x: x.a in x.b, axis=1)
.sum(level=0))
print (s)
0 2
1 2
2 2
dtype: int64