我有一個基于多個 if 陳述句創建新變數的問題。編程語言——python。
#for demonstration
import pandas as pd
example = {
"blue": [1, 1, 0, 0, 1],
"red": [1, 1, 0, 1, 1],
"green": [0,0, 2, 0, 1]
}
#load into df:
example = pd.DataFrame(example)
print(example)
應基于此條件創建新變數:如果藍色或/和紅色 = 1 和綠色 = 0。
所以,我想出了這個解決方案,它只允許我列印結果
if example["blue"].iloc[0]==1 or example["red"].iloc[0]==1:
if example["blue"].iloc[0]==1 and example["red"].iloc[0]==1:
if example["green"].iloc[0]==0:
print("Flower A")
else:
print("Flower B")
我試圖解決的兩個問題:
- 有沒有辦法根據多個 if 陳述句的結果創建變數?
- 有沒有辦法同時對資料框的所有元素執行此操作而不是使用 iloc?
因此,我計劃有一個包含四列的資料框,如下所示:
expected_result = {
"blue": [1, 1, 0, 0, 1],
"red": [1, 1, 0, 1, 1],
"green": [0,0, 2, 0, 1],
"flower type": ["Flower A", "Flower A", "Flower B", "Flower A", "Flower B"]
}
#load into df:
expected_result = pd.DataFrame(expected_result)
print(expected_result)
非常感謝!
uj5u.com熱心網友回復:
使用np.where:
In [1367]: import numpy as np
In [1368]: example['flower type'] = np.where(((example.blue.eq(1) | example.red.eq(1)) & example.green.eq(0)), 'Flower A', 'Flower B')
In [1369]: example
Out[1369]:
blue red green flower type
0 1 1 0 Flower A
1 1 1 0 Flower A
2 0 0 2 Flower B
3 0 1 0 Flower A
4 1 1 1 Flower B
uj5u.com熱心網友回復:
您可以結合使用布爾掩碼numpy.where:
# is either blue/red (or both) equal to 1?
m1 = example[['blue', 'red']].eq(1).any(axis=1)
# is green equal to 0?
m2 = example['green'].eq(0)
# if both conditions are True, then "Flower A", else "Flower B"
import numpy as np
example['flower type'] = np.where(m1&m2, 'Flower A', 'Flower B')
輸出:
blue red green flower type
0 1 1 0 Flower A
1 1 1 0 Flower A
2 0 0 2 Flower B
3 0 1 0 Flower A
4 1 1 1 Flower B
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/491316.html
