简体   繁体   English

获取列名列表所有值在 Python 中都是 NaN

[英]Get list of column names all values are NaNs in Python

Can I use Python to get a list of the column names in which all values are NaN s, return c and d as result from dataframe below?我可以使用 Python 获取所有值都是NaN的列名列表,从下面的数据帧返回cd作为结果吗? Thanks.谢谢。

df = pd.DataFrame({'a': [1,2,3],'b': [3,4,5], 'c':[np.nan, np.nan, np.nan],
                   'd':[np.nan, np.nan, np.nan]})

   a  b   c   d
0  1  3 NaN NaN
1  2  4 NaN NaN
2  3  5 NaN NaN

Use Boolean indexing with df.columns :df.columns使用布尔索引:

res = df.columns[df.isnull().all(0)]

# Index(['c', 'd'], dtype='object')

@ahbon , you can try df.any() . @ahbon ,你可以试试df.any() See the following sequence of statements executed on Python's interactive terminal.请参阅以下在 Python 交互式终端上执行的语句序列。

Check http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.any.html检查http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.any.html

>>> import numpy as np
>>> import pandas as pd
>>>
>>> df = pd.DataFrame({'a':[1,2,3],'b':[3,4,5],'c':[np.nan, np.nan, np.nan],'d':[np.nan, np.nan, np.nan]})
>>> df
   a  b   c   d
0  1  3 NaN NaN
1  2  4 NaN NaN
2  3  5 NaN NaN
>>>
>>> # Remove all columns having all NaN values using DataFrame.any()
...
>>> df_new = df.any()
>>> df_new
a     True
b     True
c    False
d    False
dtype: bool
>>>

Finally,最后,

>>> columns = []
>>>
>>> for key, value in df_new.iteritems():
...     if value:
...         columns.append(key)
...
>>> df = pd.DataFrame({'a':[1,2,3],'b':[3,4,5],'c':[np.nan, np.nan, np.nan],'d':[np.nan, np.nan, np.nan]}, columns=columns)
>>>
>>> df
   a  b
0  1  3
1  2  4
2  3  5
>>>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM