Python 根据其他列中的值填充列(EXCEL 行和列查找的索引匹配)

Python fill column based on values in other column (EXCEL INDEX MATCH FOR ROW AND COLUMN LOOKUP)

我想通过查找 dataframe2 中的值来填充 dataframe1 中的新列,但是查找是基于 dataframe1 列中的值。

例如,dataframe1 中决定在 dataframe2 中查找的两列是:

Lookup security_type
Country!not_in_list Equity
Country!empty FX Forward

dataframe2 的列数:

Lookup Equity FX Forward
Country!not_in_list 0,561686374 0,194140542
Country!empty 0,743154272 0,684586895

dataframe1 应该有一个名为 Score 的新列,其中包含在 dataframe 2 中查找的值:

Lookup security_type Score
Country!not_in_list Equity 0,561686374
Country!empty FX Forward 0,684586895

当前代码:

n=0
for i in dataframe1["Lookup"]:
    dataframe1["Score"]=""
    dataframe1.loc[n, "Score"] = dataframe2.loc[dataframe1["Lookup"][n], 
    [dataframe1["security_type"][n]]].values
    n += 1

你可以melt and merge:

out = df1.merge(df2.melt(id_vars='Lookup',
                         var_name='security_type', value_name='Score'),
                on=['Lookup', 'security_type']
                )

输出:

                Lookup security_type        Score
0  Country!not_in_list        Equity  0,561686374
1        Country!empty    FX Forward  0,684586895