在 pandas 的 Dataframe 中,我寻找一种方法来删除包含 False 值的所有行。
我需要对任何 DataFrame 执行此操作,这意味着我不知道列的名称,也无法引用它们。
例如:
df = pd.DataFrame( { 'a': np.random.random_integers(0, 10, 10), 'b': np.random.random_integers(0, 10, 10) } )
# filter without referencing columns:
print( df[ df % 2 == 0] )
# filter with column referencing :
print( df[ (df.a % 2 == 0) & (df.b % 2 == 0)] )
..产生结果:
a b
0 NaN NaN
1 NaN 6.0
2 4.0 NaN
3 8.0 10.0
4 10.0 NaN
5 4.0 NaN
6 NaN 2.0
7 NaN NaN
8 6.0 NaN
9 0.0 NaN
a b
3 8 10
目标是过滤结果(如第二个输出),但不引用列,以便启用不依赖于特定 DataFrame 的过滤器。
使用相同的代码:
df = pd.DataFrame( { 'Nantes': np.random.random_integers(0, 10, 10), 'Paris': np.random.random_integers(0, 10, 10) } )
会产生
Nantes Paris
3 8 10
最佳答案
添加DataFrame.all
如果条件对所有列都返回 True,则在 axis=1
上返回 True:
np.random.seed(2019)
df = pd.DataFrame( { 'a': np.random.random_integers(0, 10, 10),
'b': np.random.random_integers(0, 10, 10) } )
print ((df % 2 == 0))
a b
0 True True
1 True False
2 False False
3 True True
4 True True
5 True False
6 True False
7 True True
8 True False
9 False True
print (df[(df % 2 == 0).all(axis=1)])
a b
0 8 8
3 8 0
4 6 2
7 0 8
print( df[ (df.a % 2 == 0) & (df.b % 2 == 0)] )
a b
0 8 8
3 8 0
4 6 2
7 0 8
关于python - 如何在不引用列的情况下过滤 pandas DataFrame?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59468412/