根据另一个的列名选择数据框中的行 [英] Selecting rows in a dataframe based on the column names of another
本文介绍了根据另一个的列名选择数据框中的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
说我有两个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
的列,以获取以下数据框
and I would like to use df2
to select the columns of df
row by row in order to get the following dataframe
sel
1 2
2 4
3 3
4 7
5 10
其中前两个值来自 df
的B列,第三个值来自col C,第四个值来自col D,最后一个值来自colC.熊猫?
where the first two values are from the column B of df
, the third from col C, the fourth from col D and the last from col C. Is there a natural way to do it in pandas?
推荐答案
使用 查找
,索引
在两个 df
中必须相同:
Use lookup
, indexes
have to be same in both 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
这篇关于根据另一个的列名选择数据框中的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文