本文介绍了 pandas :打印列名,缺少值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试打印或获取缺少值的列名列表.例如.
I am trying to print or to get list of columns name with missing values. E.g.
data1 data2 data3
1 3 3
2 NaN 5
3 4 NaN
我想获取['data2','data3'].我写了以下代码:
I want to get ['data2', 'data3'].I wrote following code:
print('\n'.join(map(
lambda x : str(x[1])
,(filter(lambda z: z[0] != False, zip(train.isnull().any(axis=0), train.columns.values)))
)))
效果很好,但我认为应该是更简单的方法.
It works well, but I think should be simpler way.
推荐答案
df.isnull().any()
生成一个布尔数组(如果该列具有缺失值,则为True,否则为False).您可以使用它索引到df.columns
:
df.isnull().any()
generates a boolean array (True if the column has a missing value, False otherwise). You can use it to index into df.columns
:
df.columns[df.isnull().any()]
将返回缺少值的列的列表.
will return a list of the columns which have missing values.
df = pd.DataFrame({'A': [1, 2, 3],
'B': [1, 2, np.nan],
'C': [4, 5, 6],
'D': [np.nan, np.nan, np.nan]})
df
Out:
A B C D
0 1 1.0 4 NaN
1 2 2.0 5 NaN
2 3 NaN 6 NaN
df.columns[df.isnull().any()]
Out: Index(['B', 'D'], dtype='object')
df.columns[df.isnull().any()].tolist() # to get a list instead of an Index object
Out: ['B', 'D']
这篇关于 pandas :打印列名,缺少值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!