如何将一列从Pandas中的另一个数据帧添加到数据帧中,但类似于SQL中的左联接,同时更改列名



我有以下数据帧df1和df2:

df1 = pd.DataFrame({'ISIN': ['A1kT23', '4523', 'B333', '49O33'],
'Name': ['Example A', 'Name Xy', 'Example B', 'Test123'],
'Debt_Equity': [-65.56, 0.55, 0, 37],
'EV_Sales': [9.28, 0.53, 11.3, 45]})
df2 = pd.DataFrame({'ISIN': ['123', '4523', 'B333', '789'],
'Name': ['Example 123', 'Name Xy', 'Example B', 'Test789'],
'Country': ['USA', 'USA', 'Germany', 'Turkey'],
'Sector': ['IT', 'Materials', 'Communication', 'IT']})

我很想在SQL中进行类似的左联接,只将df2的列ISIN添加到df1,但df2的ISIN将获得列名"Bestand",因此我得到以下结果df:

df = pd.DataFrame({'ISIN': ['A1kT23', '4523', 'B333', '49O33'],
'Name': ['Example A', 'Name Xy', 'Example B', 'Test123'],
'Debt_Equity': [-65.56, 0.55, 0, 37],
'EV_Sales': [9.28, 0.53, 11.3, 45],
'Bestand': ['', '4523', 'B333', '']})

我尝试了合并功能,但不知怎么的,我不太成功:

df = pd.merge(df1, df2[['ISIN']], on=["ISIN"],  how="left")

如何创建df?

尝试:

df["Bestand"] = np.where(df1.ISIN.isin(df2.ISIN), df1.ISIN, "")
print(df)

打印:

ISIN       Name  Debt_Equity  EV_Sales Bestand
0  A1kT23  Example A       -65.56      9.28        
1    4523    Name Xy         0.55      0.53    4523
2    B333  Example B         0.00     11.30    B333
3   49O33    Test123        37.00     45.00        

一个简单的方法是复制"ISIN"列,称其为"Bestand",然后只合并这两列:

df2['Bestand'] = df2['ISIN']
df = pd.merge(df1, df2[['ISIN', 'Bestand']], on=["ISIN"], how='left')

如果需要,可以使用fillna('')清除NaN。

据我所知,您希望连接具有相同名称的行,将df2.ISIN添加为df.Bestand

  • 要将名称更改为Bestand,您需要在合并之前对其进行重命名
  • 在这种情况下,ISIN不是您的合并条件,Name
>>> df = df1.merge(df2[['ISIN', 'Name']].rename(columns={'ISIN': 'Bestand'}), on='Name', how='left')
>>> df
ISIN       Name  Debt_Equity  EV_Sales Bestand
0  A1kT23  Example A       -65.56      9.28     NaN
1    4523    Name Xy         0.55      0.53    4523
2    B333  Example B         0.00     11.30    B333
3   49O33    Test123        37.00     45.00     NaN

这里,how='left'指定当右侧缺少行时,我们不删除左侧的行。默认情况下,缺少的值为NaN

尝试在合并函数中添加left_on和right_on,而不是仅添加on。

最新更新