我需要:

  • Join 表1 and 表2
  • 消除重复
  • Keep the originals from 表1
  • 一本字典,用来说明旧表中哪个是id,哪个是新id

示例:输出如下所示

PS:事实是,表1源于一个已经在生产中的数据库,我这里的id被用于许多其他表中,所以我不能更改已经在表中的内容,只添加尚未在表中的新数据.但我还需要说明数据的新id是什么.

表1

id   name        birthdate     
1    Goku        1997-12-15 
2    Freeza      2000-10-03
3    Vegeta      2003-08-19

表2

id    name        birthdate
1     Krillin     1983-02-28
2     Roshi       1960-06-07
3     Goku        1997-12-15
4     Freeza      1998-10-10

因此,我需要从中生成以下内容

resulting_表1

id    name        birthdate     
1     Goku        1997-12-15 
2     Freeza      2000-10-03
3     Vegeta      2003-08-19
4     Krillin     1983-02-28
5     Roshi       1960-06-07
6     Freeza      1998-10-10

但我还需要一个表格,上面写着一个人在旧桌子上的代码,以及新的代码,这也会,类似于:

从_到_表

id   origin      new_id
1    table_1     1
2    table_1     2
3    table_1     3
1    table_2     4
2    table_2     5
3    table_2     1
4    table_2     6

我try 了很多方法,现在唯一能做的就是逐行插入,每次都判断两个字段,但这需要花费太多时间,使其不可行.

So far the best way I found consists basically in: Joining the two tables -> Grouping the data and generating new id column -> join the grouped table with the joined two tables to create the 从_到_表 problem is, that approach will change the ids I must not change, and I don't know how to keep those.

推荐答案

对于resulting_table1,我建议使用merge作为name列和birthdate列的外部连接,然后重新创建id列:

resulting_table1 = pd.merge(table1, table2, on=['name','birthdate'], how='outer')[['name','birthdate']]
resulting_table1['id'] = range(1, len(resulting_table1)+1)

对于from_to_table,您可以使用另一个外部联接(这次是在所有列上),并使用indicator标志来保留有关源表的信息:

from_to_table = pd.merge(table1, table2, how='outer', indicator='origin').replace({'origin':{'left_only':'table_1', 'right_only':'table_2'}})

最后为新id做一个resulting_table1的左连接:

from_to_table = from_to_table.merge(resulting_table1, on=['name','birthdate'], how="left")

Python相关问答推荐

删除pandas rame时间序列列中未更改的值

PyQt5如何将pyuic 5生成的Python类添加到QStackedWidget中?

Pandas :多索引组

GL pygame无法让缓冲区与vertextPointer和colorPointer一起可靠地工作

将numpy数组存储在原始二进制文件中

Python多处理:当我在一个巨大的pandas数据框架上启动许多进程时,程序就会陷入困境

PywinAuto在Windows 11上引发了Memory错误,但在Windows 10上未引发

如何删除索引过go 的lexsort深度可能会影响性能?' &>

如何根据参数推断对象的返回类型?

通过pandas向每个非空单元格添加子字符串

在Python argparse包中添加formatter_class MetavarTypeHelpFormatter时, - help不再工作""""

从一个系列创建一个Dataframe,特别是如何重命名其中的列(例如:使用NAs/NaN)

如何并行化/加速并行numba代码?

Python列表不会在条件while循环中正确随机化'

解决调用嵌入式函数的XSLT中表达式的语法移位/归约冲突

Flask Jinja2如果语句总是计算为false&

Python Pandas—时间序列—时间戳缺失时间精确在00:00

为什么常规操作不以其就地对应操作为基础?

在Admin中显示从ManyToMany通过模型的筛选结果

pysnmp—lextudio使用next()和getCmd()生成器导致TypeError:tuple对象不是迭代器''