【问题标题】:Pandas merge tables: only distinct Ids from second tablePandas 合并表:仅与第二个表不同的 ID
【发布时间】:2016-06-13 14:52:18
【问题描述】:

我想弄清楚是否可以加入/合并/合并两个表,而不是“外部”,我想使用 pandas 内置选项从第二个表中选择不同的 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 应该有来自 df1 的条目 a、b、c 和来自 df2 的 x。

【问题讨论】:

  • 请发布输入和所需输出的可重现示例

标签: python pandas merge concat


【解决方案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

【讨论】:

  • 看,我知道一定有更好的解决方案。谢谢
【解决方案2】:

我认为您可以通过将不在df1.id_col 中的id_col 子集df2isin 然后连接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

从时间比较来看,这更快..

【讨论】:

  • 这也有效,谢谢 - 但我不是 df2[df2 blabla] 符号的朋友,因此接受了科林斯的回答
  • @dmeu 如果您对更快的时间感兴趣,但我认为@Colin 的解决方案更具可读性。
  • 很高兴知道 - 但是是的,我的首要任务始终是拥有清晰的代码,以便将来我可以轻松理解它;)
猜你喜欢
  • 2020-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多