如何像这样连接两个数据框
a 1
b 2
c 2
c 5
d 3
我想根据其他有条件的数据框添加列。
a io
b pk
c dea
d ak
所以输出将是:
a 1 io
b 2 pk
c 2 dea
c 5 dea
d 3 ak
答案 0 :(得分:1)
您可以使用简单的pd.merge()
,
df3 = pd.merge(df2, df1, how='inner')
使用map()
,
import pandas as pd
data_1 = {'key':['a','b','c','c','d'],'value':[1,2,2,5,3]}
data_2 = {'key':['a','b','c','d'],'value':['io','pk','dea','ak']}
df_1 = pd.DataFrame.from_dict(data_1)
df_2 = pd.DataFrame.from_dict(data_2)
dd = {k:v for k, v in zip(df_2['key'], df_2['value'])}
df_1['mapped'] = df_1['key'].map(dd)
print(df_1)