python 返回一个匹配超过2个数字并排匹配

slhcrj9b  于 2023-01-01  发布在  Python
关注(0)|答案(2)|浏览(133)

我有一个名为df1的 Dataframe ,其中1行有6个数字,另一个名为df2的 Dataframe 中有超过500行的ID和6个数字。在df1中,我想查找6个数字,并在df2中找到它们,只返回匹配超过2个并排数字的匹配数字。它可以是df1中的任何6个数字,只要它匹配超过2个并排数字。我在下面创建了一个小例子,

import pandas as pd 

df1 = pd.DataFrame([[2,4,6,8,9,10]], columns = 
['Num1','Num2','Num3','Num4','Num5','Num6'])

df2    = pd.DataFrame([[100,1,2,4,5,6,8],
                       [87,1,6,20,22,23,34],
                       [99,1,12,13,34,45,46],
                       [64,1,10,14,29,32,33],
                       [55,1,22,13,23,33,35],
                       [66,1,6,7,8,9,10],
                       [77,1,2,3,5,6,8],
                       [811,1,2,5,6,8,10], 
                       [118,1,7,8,22,44,56],
                       [117,1,66,44,47,87,91],
                       [299,2,4,7,20,21,22],
                       [187,3,6,10,12,25,39],
                       [199,4,12,24,34,56,57],
                       [264,3,7,8,9,10,33],
                       [50,6,8,10,23,33,35],
                       [212,4,6,12,18,19,20],
                       [45,3,7,23,35,56,88],
                       [801,1,2,4,6,28,39], 
                       [258,2,3,4,9,10,41],
                       [220,5,6,10,27,57,81]],
                       columns = ['Id', 'Num1','Num2','Num3','Num4','Num5','Num6'])

我希望我的结果像下面这样。

result = pd.DataFrame([[66,1,6,7,8,9,10],
                        [811,1,2,5,6,8,10], 
                        [264,3,7,8,9,10,33],
                        [50,6,8,10,23,33,35],
                        [801,1,2,4,6,28,39], 
                        [258,2,3,4,9,10,41],
                        [220,4,6,10,27,57,81]],
                        columns = ['Id', 'Num1','Num2','Num3','Num4','Num5','Num6'])

为什么是这些数字。因为这些数字匹配两个以上的数字

66, 8,9,10
811, 6,8,10         
264, 8,9,10         
50, 6,8,10
801, 2,4,6
258, 4,9,10
220, 4,6,10

我也试过下面的代码,但它只返回一个匹配,有超过2个,但不是并排。希望我是有意义的。

vals_to_find = set(df1.iloc[0])
mask = df2.loc[:, "Num1":].apply(lambda x: 
len(vals_to_find.intersection(x)) > 2, axis=1)
print(df2[mask])
sd2nnvve

sd2nnvve1#

我想这正是你想要的

import numpy as np
import pandas as pd

# Save the numbers in df1 in a list as their order does not matter
key = df1.T[0].to_list()

# Check to see how many of those numbers are in df2
temp = df2[df2.isin(key)]

我写了一个自定义函数,它获取每一行并检查是否有两个以上的连续数字并排,它使用jezrael的答案,你可以找到here
x一个一个一个一个x一个一个二个x

6uxekuva

6uxekuva2#

下面是一个方法:

(df2.loc[df2.loc[:,'Num1':].isin(np.ravel(df1))
.apply(lambda x: x.diff().ne(0).cumsum().where(x).value_counts(),axis=1)
.eq(3).any(axis=1)])

输出:

Id  Num1  Num2  Num3  Num4  Num5  Num6
5    66     1     6     7     8     9    10
7   811     1     2     5     6     8    10
13  264     3     7     8     9    10    33
14   50     6     8    10    23    33    35
17  801     1     2     4     6    28    39
18  258     2     3     4     9    10    41

相关问题