python - 如何在不引用列的情况下过滤 pandas DataFrame?

标签 python pandas

在 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/

相关文章:

python - pandas 系列中的部分字符串替换

python - 如何获取 Pandas Dataframe 中特定列值之后的 n 行之前或之后

python - Pandas 多索引数据透视表转换为字典列表

python - 向单个绘图添加标题或标签

python - 如何将这个嵌套的 for 循环写成列表理解?

python - "stale association proxy, parent object has gone out of scope"与 Flask-SQLAlchemy

python - 对 pandas 数据框进行分组,同时对某些列中的值进行平均

python - 如何忽略日期不在 pandas 索引中的错误?

python - 替换为 pandas 中的默认值

python - 如何使用封闭类的类型键入提示方法?