首页 > 解决方案 > 如何根据另一个数据框中的变量从数据框中选择列

问题描述

我只想从 df2 中选择那些等于 python pandas 中 df1 变量的列

df1

parameter (column name)

a
b
c

df2

w  x  a  c  z
3  1  5  6  1
5  67 4  3  56
8  12 6  1  23

我的预期输出是

a c
5 6
4 3
6 1

标签: pythonpandasdataframe

解决方案


使用intersectionorisin布尔掩码:

df3 = df2[df.columns.intersection(df1['parameter'])]

或者:

df3 = df2.loc[:, df.columns.isin(df1['parameter'])]

推荐阅读