python - 从 Pandas 的索引中获取类
问题描述
我有两个数据框
df1=pd.DataFrame({'index':[1,2,3,4],'Name':['Andi','Boby','Charlie','Daniel'],'Occupation':['x','xxx','xxx','x']})
和
df2=pd.DataFrame({'index':[1,2,3,4],'Occupation':['x','xxx','xxx','x'],'Class':[1,0,1,0]})
基于索引我想获得基于索引的类,所以我通过合并 df1 和 df2 创建另一个数据框。我用了
data1=df1.merge(df2,on='index',how='left')
结果是我有两列 Occupation_x 和 Occupation_y。我如何在没有那些 Occupation_x 和 Occupation_y 列的情况下合并数据框,因此这些列将是索引、名称、职业、类
解决方案
试试这个,在合并之前添加这一行
df2.pop('Occupation') # this line needs to be added
data1=df1.merge(df2,on='index', how='left')
如果您有多个这样的列,请尝试以下方法
cols = ['Col1', 'Col2'] # Add required columns of df2 here
data1=df1.merge(df2[cols],on='index', how='left')
推荐阅读
- robotframework - Robot Framework 是否支持 Gherkin 数据表?
- string - 用 SQLite 中的某些字符替换部分字符串
- qt - 如何创建具有 2 种离散颜色的圆形边框?
- git - 在合并和推送期间忽略文件
- python - 从外部访问托管在 Azure VM(Windows 操作系统)上的 python 应用程序
- javascript - 如何在站点和json文件中添加应删除的删除按钮
- java - java 8中的.net列表分组?
- c# - 为什么在使用 Xamarin 表单打开画廊时调用 OnDisappearing() 方法
- grep - 如何从 grep 中排除一些匹配项?
- php - DDD / CQRS / ES - 如何以及在何处实施警卫