Skip to main content
 首页 » 编程设计

python之如何根据另一个数据框中的变量从数据框中选择列

2024年12月31日9Free-Thinker

我只想从 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 

请您参考如下方法:

使用intersection或 isin对于 bool 掩码:

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

或者:

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