python - 如果所有列都有空字符串,则从熊猫数据框中删除行
问题描述
我有一个数据框如下
Name Age
0 Tom 20
1 nick 21
2
3 krish 19
4 jack 18
5
6 jill 26
7 nick
所需的输出是
Name Age
0 Tom 20
1 nick 21
3 krish 19
4 jack 18
6 jill 26
7 nick
不应更改索引,如果可能的话,如果我不必将空字符串转换为 NaN 会很好。''
仅当所有列都有空字符串时才应将其删除
解决方案
你可以做:
# df.eq('') compare every cell of `df` to `''`
# .all(1) or .all(axis=1) checks if all cells on rows are True
# ~ is negate operator.
mask = ~df.eq('').all(1)
# equivalently, `ne` for `not equal`,
# mask = df.ne('').any(axis=1)
# mask is a boolean series of same length with `df`
# this is called boolean indexing, similar to numpy's
# which chooses only rows corresponding to `True`
df = df[mask]
或者在一行中:
df = df[~df.eq('').all(1)]
推荐阅读
- tomcat7 - 如何解决 Tomcat jmxproxy 返回“属性不能为空”?
- azure-logic-apps - Azure 逻辑/服务总线队列 - “当队列中收到消息时”一次有多少条消息?
- sql - 按 5 分钟时间间隔对数据进行分组,SQL
- asp.net - 日期字段的 GridView 超链接未使用 vb.net 显示
- java - 从字符串到整数的转换
- ms-access - 为什么 Access 中的表格灰显且不可删除?
- pixel - ImageJ 中的 rawintden 测量值是什么意思?
- node.js - 节点redis ETIMEOUT问题
- laravel - 如何在laravel中填充选择选项?来自硬编码选项
- reactjs - 我可以从 React 上下文 (useContext) 中记住一个 setter 函数吗