gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 06:41:32 25 4
gpt4 key购买 nike

我有一些数据,想获取样本量较小(例如 < 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 也可以转换为文本字符串序列。

关于python - Pandas :返回满足特定条件的列的列标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42639207/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com