首页 > 解决方案 > 如何合并2个数据框?

问题描述

我有这个表1:

  A B C D
0 1 2 k l
1 3 4 e r

df.dtypes给我这个:

A int64
B int64
C object
D object

现在,我想使用此命令创建一个仅包含对象(C 列和 D 列)的 table2 table2=df.select_dtypes(include=[object])

然后,我想使用这个命令对 table2 进行编码pd.get_dummies(table)

它给了我这个表2:

  C D
0 0 1
1 1 0

我要做的最后一件事是将两个表附加在一起(表 1 + 表 2),以便最终表如下所示:

  A B C D
0 1 2 0 1
1 3 4 1 0

有人可以帮忙吗?

标签: pythonpandasdataframe

解决方案


This should do it:

table2=df.select_dtypes(include=[object])
table1.select_dtypes(include=[int]).join(table2.apply(lambda x:pd.factorize(x, sort=True)[0]))

enter image description here

It first factorizes the object typed columns of table 2 (instead of using dummies generator) and then merge it back to the int typed columns of the original dataframe!


推荐阅读