首页 > 解决方案 > 如何匹配来自多个数据帧的字符串并使用 AND 和 OR 选项返回索引

问题描述

这是我要搜索并取回匹配行号的数据框。 '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

我将要搜索的字符串来自这个较小的数据框。必须将每一行搜索为 AND,以获取数据框 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: unhashable type: 'list'results = df2.isin( [ term ] )

对于 OR 应该很容易购买必须排除已经在第一部分中计算的 AND 部分

React2=df2.isin([X]).any(1).index.tolist()
React2

标签: pythonpandasdataframe

解决方案


这不是您期望的输出,但我要求 AND 条件中的索引。输出的结果列表包含 df 逐行的 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]]

推荐阅读