熊猫-有条件地连接两个数据框

时间:2018-10-31 14:03:00

标签: python pandas dataframe data-analysis

我是数据分析的初学者,我正在使用python pandas lib将两个数据框连接在一起。

目标是用第二个表中的所有数据创建一个新的数据框,并将第二个表中的第一个表的'type'联接起来,用第一个表中的字母替换数字。 香港专业教育学院已经尝试了一些合并和联接,但找不到解决方案。 帮助将不胜感激。

#Tables were created with pd.read_csv(path, sep = '\t', encoding = 'ISO-8859-1')
#First Table

ID  type
1   A
2   B
3   C
4   D
5   E
...

#Second Table

ID  type  column2  column3 ... 
1   2     x
2   2     y
3   3     x
4   1     y
5   4     z
...

2 个答案:

答案 0 :(得分:0)

如果我理解正确

df2.type.map(df1.set_index('ID').type)
Out[152]: 
0    B
1    B
2    C
3    A
4    D
Name: type, dtype: object

答案 1 :(得分:0)

尝试一下

print pd.merge(df1,df2,on=['ID']).drop('type_y',axis=1).rename(columns={'type_x':'type'})

输出:

   ID type column2
0   1    A       x
1   2    B       y
2   3    C       x
3   4    D       y
4   5    E       z

当df1中有很多列并希望将其添加到结果中时,请使用pd.merge,否则请使用W-B的解决方案。

相关问题