首页 > 解决方案 > 在熊猫数据框中只保留非零缺失值

问题描述

如何从数据框中按降序仅选择非空列。

这是数据框:

df = pd.DataFrame( { 'a': [1,2,np.nan,np.nan],
                    'b':  [10,20,30,40],
                   'c': [1,np.nan,np.nan,np.nan]})
     a   b    c
0  1.0  10  1.0
1  2.0  20  NaN
2  NaN  30  NaN
3  NaN  40  NaN

我可以做这个:

df.isnull().sum().sort_values(ascending=False)
c    3
a    2
b    0

但我想将多个命令链接到一行,以便在一行中给出结果。

我试过了: df.isnull().sum().sort_values(ascending=False).filter(lambda x: x>0) 失败了

我知道这个:

temp = df.isnull().sum().sort_values(ascending=False)
temp[temp>0]
c    3
a    2

但我正在寻找在 ONE-LINE 中链接延续的方法。

必需的:

df.isnull().sum().sort_values(ascending=False).somefunction( x > 0)

更新
我找到了一种将系列转换为数据框然后使用查询的方法。

df.isnull().sum().sort_values(ascending=False).to_frame().rename(columns={0:'temp'}).query("temp > 0")

这看起来冗长而多余。有没有更好的办法 ?

标签: pythonpandas

解决方案


这很困惑filter,因为它适用于索引,而不是值

df.isnull().sum().loc[lambda x : x>0].sort_values(ascending=False)
Out[147]: 
a    2
c    3
dtype: int64

推荐阅读