2016-03-01 26 views
1

我想知道是否有可能加入/合并/连接两个表,而不是'外部'我想从第二个表中选择不同的Ids与熊猫内置选项。熊猫合并表:只有不同的第二张表中的ID

现在我做沿东西线和 我有我的代码是不是很优雅的感觉:

a = [['a', '1.2', '4.2'], ['b', '70', '0.03'], ['c', '8', '1']] 
b = [['a', '52', '49'], ['b', '23', '0.05'], ['x', '5', '0']] 
df1 = pd.DataFrame(a, columns=['id_col', 'two', 'three']) 
df2 = pd.DataFrame(b, columns=['id_col', 'two', 'three']) 


# remove df2 entries also in df1 
different_ids = set(df2.id_col).difference(set(df1.id_col)) 
df2 = df2[df2.id_col.isin(different_ids)] 
# merge data frames 
df_merged = pd.concat([df1,df2]) 

合并后的DF应该有项A,B,C从DF1和X从df2开始。

+0

请张贴的输入重复的例子,并且所需的输出 – fernandezcuesta

回答

1

您可以concatdf1df2然后drop_duplicatesid_col

>>> df = pd.concat((df1, df2)) 
>>> print(df.drop_duplicates('id_col')) 
    id_col two three 
0  a 1.2 4.2 
1  b 70 0.03 
2  c 8  1 
2  x 5  0 
+0

请参阅我知道必须有更好的解决方案。谢谢 – dmeu

1

我想你可以做的一切,用id_col子集化df2其不在df1.id_colisin然后CONCAT df1并导致数据帧:

res = pd.concat([df1, df2[~df2.id_col.isin(df1.id_col)]]) 

In [186]: res 
Out[186]: 
    id_col two three 
0  a 1.2 4.2 
1  b 70 0.03 
2  c 8  1 
2  x 5  0 

时间:

In [23]: %timeit pd.concat((df1, df2)).drop_duplicates('id_col') 
100 loops, best of 3: 1.95 ms per loop 

In [24]: %timeit pd.concat([df1, df2[~df2.id_col.isin(df1.id_col)]]) 
100 loops, best of 3: 1.79 ms per loop 

从时间比较这是更快..

+0

这也适用,感谢 - 但我不是'DF2 [DF2布拉布拉]'符号的朋友,所以接受的,如果你柯林斯回答 – dmeu

+0

@dmeu”对时间更加敏感,但我认为科林的解决方案更具可读性。 –

+0

很高兴知道 - 但是,我的首要任务总是有清晰的代码,以便将来我很容易理解;) – dmeu