如何过滤Pandas的数据帧而不引用列?

2024-05-15 17:29:58 发布

您现在位置:Python中文网/ 问答频道 /正文

在pandas的数据帧中,我寻找一种方法来删除所有包含假值的行

我需要为任何数据帧这样做,这意味着我不知道列的名称,我不能引用它们

例如:

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

目标是过滤结果(就像第二个输出),但不引用列,以便启用不依赖于特定数据帧的过滤器

代码相同:

df = pd.DataFrame( { 'Nantes': np.random.random_integers(0, 10, 10), 'Paris': np.random.random_integers(0, 10, 10) } )

会产生

   Nantes   Paris
3  8        10

Tags: 数据方法integersdataframepandasdfnprandom
1条回答
网友
1楼 · 发布于 2024-05-15 17:29:58

如果条件对所有列都返回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

相关问题 更多 >