Python 如何匹配来自多个数据帧的字符串并使用and和OR选项返回索引
这是我要搜索的数据帧,并返回匹配的行号。Python 如何匹配来自多个数据帧的字符串并使用and和OR选项返回索引,python,pandas,dataframe,Python,Pandas,Dataframe,这是我要搜索的数据帧,并返回匹配的行号。 'A'和'AB'是完全不同的东西 df2 = pd.DataFrame(np.array(['A','B','AC','AD','NAN','XX','BC','SLK','AC','AD','NAN','XU','BB','FG','XZ','XY','AD','NAN','NF','XY','AB','AC','AD','NAN','XY','LK','AC','AC','AD','NAN','KH','BC','GF','BC','AD']).re
'A'
和'AB'
是完全不同的东西
df2 = pd.DataFrame(np.array(['A','B','AC','AD','NAN','XX','BC','SLK','AC','AD','NAN','XU','BB','FG','XZ','XY','AD','NAN','NF','XY','AB','AC','AD','NAN','XY','LK','AC','AC','AD','NAN','KH','BC','GF','BC','AD']).reshape(5,7),columns=['a','b','c','d','e','f','g'])
a b c d e f g
0 A B AC AD NAN XX BC
1 SLK AC AD NAN XU BB FG
2 XZ XY AD NAN NF XY AB
3 AC AD NAN XY LK AC AC
4 AD NAN KH BC GF BC AD
我将搜索的字符串来自这个较小的数据帧。其中每一行都必须作为和进行搜索,以获取数据帧df2的匹配字符串行索引
df = pd.DataFrame(np.array(['A','B','C','D','AA','AB','AC','AD','NAN','BB','BC','AD']).reshape(6,2),columns=['a1','b1'])
a1 b1
0 A B # present in the first row of df2
1 C D # not present in any row of df2
2 AA AB # not present in any row of df2
3 AC AD # present in the second row of df2
4 NAN BB # present in the second row of df2
5 BC AD # present in the fourth row of df2
和部分
所需输出[0,1,3,4]
import pandas as pd
import numpy as np
index1 = df.index # Finds the number of row in df
terms=[]
React=[]
for i in range(len(index1)): #for loop to search each row of df dataframe
terms=df.iloc[i] # Get i row
terms[i]=terms.values.tolist() # converts to a list
print(terms[i]) # to check
# each row
for term in terms[i]: # to search for each string in the
print(term)
results = pd.DataFrame()
if results.empty:
results = df2.isin( [ term ] )
else:
results |= df2.isin( [ term ] )
results['count'] = results.sum(axis=1)
print(results['count'])
print(results[results['count']==len(terms[i])].index.tolist())
React=results[results['count']==len(terms[i])].index.tolist()
React
获取TypeError:unhable类型:results=df2.isin([term])
对于或应该很容易购买,必须排除已在第一节中说明的零部件
React2=df2.isin([X]).any(1).index.tolist()
React2
这不是您期望的输出,但我要求在AND条件下使用索引。生成的输出列表逐行包含df2索引。这符合你问题的意图吗
output = []
for i in range(len(df)):
tmp = []
for k in range(len(df2)):
d = df2.loc[k].isin(df.loc[i,['a1']])
f = df2.loc[k].isin(df.loc[i,['b1']])
d = d.tolist()
f = f.tolist()
if sum(d) >= 1 and sum(f) >=1:
tmp.append(k)
output.append(tmp)
output
[[0], [], [], [0, 1, 3], [1], [0, 4]]
提高你所谓的“df2”的期望输出。@r初学者非常感谢你的评论。我确实在你的评论后添加了所需的输出。完美这是可行的,但我需要一些时间来测试我的原始数据。请允许我有时12小时就足够我来测试这个了。非常感谢你。