2017-03-01 158 views
-1

的独特combbination我有两个DataFrames具有不同尺寸和不同数量的列,例如:比较两个dataframes并找到列

DF1: 
index col1 col2 col3 
1  AA A12 SH7B 
2  Ac DJS 283 
3  ZH 28S 48d 

DF2: 
index col1 col2 col3 col4 
2  AA cc2 SH7B hd5 
7  Ac DJS 283,dhb re 
10  ZH 28S SJE,48d 385d 
23 3V4 38D 350,eh4 sm4 
44  S3 3YE 032,she 3927 

所以索引是不同的。并且在第一个数据框中有一些与其他数据框相似的数据的独特组合,我想查找它们。因此,我想循环遍历第二个数据框的行并查找每行的每个数据组合(例如:( 7,Ac,DJS,283,re)和(7,Ac,DJS,dhb,re)是索引7的两种组合,因为列中有多个值),并将其与第一个数据框的行进行比较并打印如果在第二个数据帧中有相同的组合,它也会出来。

result: 
1  Ac DJS 283 
2  ZH 28S 48d 

谢谢

+0

定义除非有相似性的正式定义,否则您的问题无法通过算法解决。 – DyZ

+0

我在例子中解释过,类似的我的意思是相同的...例如(Ac,DJS,283)的组合可以在两个数据帧中找到,所以这是结果数据帧的行之一 – faranak777

+0

但是没有'283 '在第二张桌子。有'283,dhb'代替。 – DyZ

回答

0

您需要从数据帧2中,首先拆分COL3,然后用数据帧1把它合并;分割数据帧2的COL3,一个常用的方法是分开并展平,而COL3使用numpy.repeat使其它列的相等长度:“相似的”

import pandas as pd 
import numpy as np 
from itertools import chain 

# count how many repeats are needed for other columns based on commas 
repeats = df2.col3.str.count(",") + 1   

# repeat columns except for col3, split and flatten col3 and merge it back with df1 
(df2.drop('col3', 1).apply(lambda col: np.repeat(col, repeats)) 
.assign(col3 = list(chain.from_iterable(df2['col3'].str.split(',')))) 
.merge(df1)) 

# col1 col2 col4 col3 
#0 Ac DJS  re  283 
#1 ZH 28S 385d  48d 
+0

谢谢你,我得到这个错误:不能从dtype('float64')根据规则'安全'投射数组数据dtype('int64')“ – faranak777

+0

不完全确定发生了什么,你可以尝试将数据帧转换为str类型:'df1 = df1.astype(str); df2 = df2.astype(str)'。 – Psidom