假设我有两个 dfs
df = pd.DataFrame({'A': [1, 2, 3,4,5],
'B': [2, 4,2,4,5], 'C': [1, -1, 3,5,10],'D': [3, -4,3,7,-3]}, columns=['A', 'B', 'C', 'D'])
df = df.set_index(['A'])
df2 = pd.DataFrame({'A': [1, 2, 3,4,5],
'J': ['B', 'B','C','D','C']}, columns=['A', 'J'])
df2 = df2.set_index(['A'])
我想使用df2
逐行选择df
的列以获得以下数据框
sel
1 2
2 4
3 3
4 7
5 10
其中前两个值来自 df 的 B 列,第三个值来自 col C,第四个值来自 col D,最后一个值来自 col C。有没有一种自然的方法可以做到这一点 Pandas ?
最佳答案
使用lookup
,索引
在两个df
中必须相同:
print (df.lookup(df2.index, df2['J']))
[ 2 4 3 7 10]
df = pd.DataFrame({'sel':df.lookup(df2.index, df2['J'])}, index=df.index)
print (df)
sel
A
1 2
2 4
3 3
4 7
5 10
关于python - 根据另一个数据框中的列名选择数据框中的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45977523/