python - 在熊猫数据框中只保留非零缺失值
问题描述
如何从数据框中按降序仅选择非空列。
这是数据框:
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")
这看起来冗长而多余。有没有更好的办法 ?
解决方案
这很困惑filter
,因为它适用于索引,而不是值
df.isnull().sum().loc[lambda x : x>0].sort_values(ascending=False)
Out[147]:
a 2
c 3
dtype: int64
推荐阅读
- xamarin.forms - 发生 xamarin 地理位置未捕获的异常
- html - 我的导航栏有问题。当鼠标悬停在它上面时,所有按钮都在移动
- c# - SQlite 连接中的非法字符 (C#)
- node.js - 未找到反应内容 heroku 部署
- pandas - 合并两个 pd.DataFrames 并检查重复的 Data ('lastname', 'name')
- reactjs - 反应组件中 this.props 的使用无效
- kotlin - 如何在 Kotlin 中创建带有 Type 参数的 ArrayList
- java - Android:当用户输入特定位置时收到通知
- php - 重新加载后不要发布
- python - 在 KeyboardInterrupt 上关闭异步循环 - 运行停止例程