[英]pandas multiple conditions based on multiple columns
我正在嘗試根據兩個條件對 pandas dataframe 的點進行着色。 例子:
IF value of col1 > a AND value of col2 - value of col3 < b THEN value of col4 = string
ELSE value of col4 = other string.
我現在嘗試了很多不同的方法,我在網上找到的所有東西都只取決於一個條件。
我的示例代碼總是引發錯誤:
The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
這是代碼。 嘗試了幾種變體都沒有成功。
df = pd.DataFrame()
df['A'] = range(10)
df['B'] = range(11,21,1)
df['C'] = range(20,10,-1)
borderE = 3.
ex = 0.
#print df
df['color'] = np.where(all([df.A < borderE, df.B - df.C < ex]), 'r', 'b')
順便說一句:我明白,它說什么,但不知道如何處理它。
選擇標准使用布爾索引:
df['color'] = np.where(((df.A < borderE) & ((df.B - df.C) < ex)), 'r', 'b')
>>> df
A B C color
0 0 11 20 r
1 1 12 19 r
2 2 13 18 r
3 3 14 17 b
4 4 15 16 b
5 5 16 15 b
6 6 17 14 b
7 7 18 13 b
8 8 19 12 b
9 9 20 11 b
將 IF 包裝在一個函數中並應用它:
def color(row):
borderE = 3.
ex = 0.
if (row.A > borderE) and( row.B - row.C < ex) :
return "somestring"
else:
return "otherstring"
df.loc[:, 'color'] = df.apply(color, axis = 1)
產量:
A B C color
0 0 11 20 otherstring
1 1 12 19 otherstring
2 2 13 18 otherstring
3 3 14 17 otherstring
4 4 15 16 somestring
5 5 16 15 otherstring
6 6 17 14 otherstring
7 7 18 13 otherstring
8 8 19 12 otherstring
9 9 20 11 otherstring
對我來說@Alexander 的解決方案在我的特定情況下不起作用,我必須使用列表來傳遞這兩個條件,然后轉置輸出,我的解決方案也適用於這種情況:
df['color'] = np.where([df.A < borderE] and [df.B - df.C < ex], 'r', 'b').transpose()
產量:
A B C color
0 0 11 20 r
1 1 12 19 r
2 2 13 18 r
3 3 14 17 b
4 4 15 16 b
5 5 16 15 b
6 6 17 14 b
7 7 18 13 b
8 8 19 12 b
9 9 20 11 b
出現問題中的錯誤是因為 OP 使用all()
function 而不是按位&
運算符將多個比較鏈接在一起。
鏈接多重比較的另一種方法是通過eval()
方法評估表達式。 下面檢查每行的 A 值是否小於borderE
並且(B - C)
值是否小於ex
。
df.eval('A < @borderE and B - C < @ex')
將其結果用作numpy.where()
條件,您可以通過
df['color'] = np.where(df.eval('A < @borderE and B - C < @ex'), 'r', 'b')
如果你安裝了 numexpr ( pip install numexpr
),這個方法應該和通過&
鏈接一樣執行。 優點是(i)它更具可讀性(imo)和(ii)您不再需要擔心括號()
and
/ &
等,因為字符串表達式中的優先順序與那個相同在 Python 中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.