熊猫,删除空列

时间:2021-07-03 16:17:37

标签: pandas

如何检查是否有一列仅填充了“无”值? 如何删除该列?

所以类似于:

If column in dataframe is None:
    drop column

这是一个虚拟数据示例,其中解决方案应将第 5 列标识为空并删除该列:

import pandas as pd
import numpy as np

# dictionary of lists
dict = {'First Score':[100, np.nan, np.nan, 95],
        'Second Score': [30, np.nan, 45, 56],
        'Third Score':[52, np.nan, 80, 98],
        'Fourth Score':[60, 67, 68, 65],
        'Fifth Score':[ np.nan,  np.nan,  np.nan,  np.nan]
        }

# creating a dataframe from dictionary
df = pd.DataFrame(dict)
df = df.where(pd.notnull(df), None)

1 个答案:

答案 0 :(得分:2)

试试这个:

df_out = df.dropna(how='all', axis=1)

输出:

  First Score Second Score Third Score  Fourth Score
0       100.0         30.0        52.0            60
1        None         None        None            67
2        None         45.0        80.0            68
3        95.0         56.0        98.0            65

根据文档,pd.DataFrame.dropna 有参数“how”,我们可以将其设置为“all”。