我有一個 DataFrame df: "merged"
| 數量 總價 | 速度 | 速率1 |
|---|---|---|
| 2000000 | 15 | 14.5 |
I want to create a new column based on the following criteria:
1-) if 0 > row A(Quantity Total Price) <= 50000000 :row C(Rate1) will be same with row B(Rate) with another result column
2-) if 50000000 > row A(Quantity Total Price) <= 500000000 :row C(Rate1) will be calculated like another result column >>>> merged['Rate']*0.9 merged['Rate1']*0.1
3-) if 500000000 > row A(Quantity Total Price) <= 2000000000 :row C(Rate1) will be calculated like another result column >>>> merged['Rate']*0.8 merged['Rate1']*0.2
4-) if 2000000000 > row A(Quantity Total Price) <= 4000000000 :row C(Rate1) will be calculated like another result column >>>> merged['Rate']*0.5 merged['Rate1']*0.5
5-) if 4000000000 > row A(Quantity Total Price) <= 6000000000 :row C(Rate1) will be calculated like another result column >>>> merged['Rate']*0.25 merged['Rate1']*0.75
6-)if 6000000000 > row A(Quantity Total Price) <= 99999999999999 :row C(Rate1) will be stay same at another result column.
我的預期輸出(所有條件的示例)
?f 數量總計 首先假設第一個結果:20.000.000
?f 數量總計 首先假設第二個結果:100.000.000
?f 數量總計 首先假設第三個結果:700.000.000
?f Quantity Total 首先假設第四個結果:3.000.000.000
?f 數量總計 首先假設第五個結果:5.000.000.000
?f 數量總計 首先假設第六個結果:7.000.000.000
| 結果 |
|---|
| 15 |
| 14.95 |
| 14.9 |
| 14.75 |
| 14.625 |
| 14.5 |
對于典型的 if else 情況,我會執行 np.where 但出現類似 ValueError: Length of values (5) does not match length of index (1) 的錯誤
My code;
merged['Rate1'] = np.where(
[merged['Quantity Total First'] <= 500000000,
(merged["Quantity Total First"] >= 50000000) & (merged["Quantity Total First"] <= 500000000),
(merged["Quantity Total First"] >= 500000000) & (merged["Quantity Total First"] <= 2000000000),
(merged["Quantity Total First"] >= 2000000000) & (merged["Quantity Total First"] <= 4000000000),
(merged["Quantity Total First"] >= 4000000000) & (merged["Quantity Total First"] <= 6000000000),
],
[merged['Rate'],
merged['Rate']*0.9 merged['Rate1']*0.1,
merged['Rate']*0.8 merged['Rate1']*0.2,
merged['Rate']*0.5 merged['Rate1']*0.5,
merged['Rate']*0.25 merged['Rate1']*0.75
],
data_state2['Rate1']
)
你能幫幫我嗎?您可以從頭開始編碼。謝謝
uj5u.com熱心網友回復:
您可以使用pandas.cut映射您的值。
注意。為了清楚起見,我將所有值除以 100 萬。
# list of bins used to categorize the values
bins = [0, 50, 500, 2000, 4000, 6000, float('inf')]
# matching factors to map ]0-50] -> 1 ; ]50-500] -> 0.9, etc.
factors = [1, 0.9, 0.8, 0.5, 0.25, 0]
# get the factors and convert to float
f = pd.cut(df['Quantity Total Price'], bins=bins, labels=factors).astype(float)
# use the factors in numerical operation
df['Result'] = df['Rate']*f df['Rate1']*(1-f)
輸出:
Quantity Total Price Rate Rate1 Result
0 20 15 14.5 15.000
1 100 15 14.5 14.950
2 700 15 14.5 14.900
3 3000 15 14.5 14.750
4 5000 15 14.5 14.625
5 7000 15 14.5 14.500
使用的輸入:
df = pd.DataFrame({'Quantity Total Price': [20, 100, 700, 3000, 5000, 7000],
'Rate': [15]*6, 'Rate1': [14.5]*6})
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/496712.html
