Skip to main content
 首页 » 编程设计

python之Pandas :返回满足特定条件的列的列标题

2025年05月04日7虾米哥

我有一些数据,想获取样本量较小(例如 < 90% 的总行数)的列的列标题。我如何获得它们的列表,可能以列表或数据框的形式返回?

在下面的例子中,我想得到 FieldC作为输出。

使用 train_df.head() :

<class 'pandas.core.frame.DataFrame'> 
RangeIndex: 2000 entries, 0 to 1999 
Data columns (total 100 columns): 
Id               2000 non-null int64 
FieldA           2000 non-null int64 
FieldB           2000 non-null object 
FieldC           1675 non-null float64 
FieldD           2000 non-null int64 
FieldE           2000 non-null object 
...more fields... 

使用 train_df.count()<2000*0.9 :

Id               False 
FieldA           False 
FieldB           False 
FieldC           True 
FieldD           False 
FieldE           False 
...more fields... 

请您参考如下方法:

>>> _=pandas.DataFrame({'horse':[3,None],'cow':[1,2],'sheep':[None,None]}) 
>>> _ 
   cow  horse sheep 
0    1    3.0  None 
1    2    NaN  None 
>>> criterion2=_.columns[_.count()>2] 
>>> criterion1=_.columns[_.count()>1] 
>>> criterion0=_.columns[_.count()>0] 
>>> criterion2 
Index([], dtype='object') 
>>> criterion1 
Index(['cow'], dtype='object') 
>>> criterion0 
Index(['cow', 'horse'], dtype='object') 
>>> _[criterion2] 
Empty DataFrame 
Columns: [] 
Index: [0, 1] 
>>> _[criterion1] 
   cow 
0    1 
1    2 
>>> _[criterion0] 
   cow  horse 
0    1    3.0 
1    2    NaN 
>>> pandas.__version__ 
'0.22.0' 

'object' 的 pandas.Index 也可以转换为文本字符串序列。