使用另一个数据帧作为列引用的数据帧查找

2024-06-17 08:26:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我有三列(L、M、N)和N行的DFA,如下所示:

L  M  N
1  2  3
4  5  6
7  8  9

和DF B,具有两列(X和Y)和n行,如下所示:

 X   Y
'L' NaN
'M' 'N'
'N' 'L'

我想要一个有n行的DF,比如:

1  NaN
5   6
9   7

基本上,dfb中的每一行都决定了dfa中要保留哪些列

短暂性脑缺血发作


Tags: dfnandfadfb脑缺血
1条回答
网友
1楼 · 发布于 2024-06-17 08:26:11

使用pandas.Series.reset_index的方式有点老套,但只有一种:

def getloc(index):
    try:
        return df.loc[index[0], index[1]]
    except KeyError:
        return np.nan

new_df = df2.apply(lambda x: x.reset_index().apply(tuple, axis=1)).applymap(getloc)
print(new_df)

输出:

   X    Y
0  1  NaN
1  5  6.0
2  9  7.0

相关问题 更多 >