python - 如何合并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
有人可以帮忙吗?
解决方案
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]))
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!
推荐阅读
- sql - 如何使用给定数据计算患病率
- javascript - 我应该添加运行时类型保护吗?
- django - 这两种在 Django 中提供静态文件的方法有什么区别?
- firebase - 在 Firebase 中添加自定义 Oauth2 提供程序
- sql - 从多对多表中添加总计和存在聚合的高效 SQL 查询
- git - 在推送更改时创建重复文件
- c# - 等级增加时如何产生障碍物?
- xcode - '无法启动 iphonesimulator 的模拟器 .. 无法启动模拟器 '
- javascript - 按唯一子元素查找父元素,但单击另一个子元素
- reactjs - 如何在我的浅层测试中定义匹配路由器道具