簡體   English   中英

基於多個條件Python Pandas刪除行

[英]Deleting rows based on multiple conditions Python Pandas

我想在滿足幾個條件時刪除行:

例如,生成一個隨機DataFrame:

import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(10, 4), columns=['one', 'two', 'three', 'four'])
print df

表的一個實例如下所示:

        one       two     three      four
0 -0.225730 -1.376075  0.187749  0.763307
1  0.031392  0.752496 -1.504769 -1.247581
2 -0.442992 -0.323782 -0.710859 -0.502574
3 -0.948055 -0.224910 -1.337001  3.328741
4  1.879985 -0.968238  1.229118 -1.044477
5  0.440025 -0.809856 -0.336522  0.787792
6  1.499040  0.195022  0.387194  0.952725
7 -0.923592 -1.394025 -0.623201 -0.738013
8 -1.775043 -1.279997  0.194206 -1.176260
9 -0.602815  1.183396 -2.712422 -0.377118

我想根據以下條件刪除行:

行的值為col'one','two' 'three'大於0; 並且應刪除col'four'小於0的值。

然后我嘗試實現如下:

df = df[df.one > 0 or df.two > 0 or df.three > 0 and df.four < 1]

但是,導致如下錯誤消息:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

有人可以根據多種情況幫助我如何刪除嗎?

對於不是100%我清楚的原因pandas扮演與位邏輯運算符不錯| & ,但不是布爾值or and

試試這個:

df = df[(df.one > 0) | (df.two > 0) | (df.three > 0) & (df.four < 1)]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM