首页 > 解决方案 > 从 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 列的情况下合并数据框,因此这些列将是索引、名称、职业、类

标签: pythonpython-3.xpandas

解决方案


试试这个,在合并之前添加这一行

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')

推荐阅读