gpt4 book ai didi

python - 如果所有列都为空字符串,则从 pandas 数据框中删除行

转载 作者:行者123 更新时间:2023-12-05 08:20:05 32 4
gpt4 key购买 nike

我有一个数据框如下

    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)]

关于python - 如果所有列都为空字符串,则从 pandas 数据框中删除行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61964116/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com