![](/img/trans.png)
[英]How to apply if condition with pandas and write it to new column if the condition satisfies?
[英]How to apply formulas on condition to generate a new column and apply two types of ranking?
輸入:
import pandas as pd
data = [['abc1',55,98,100],['abc2',56,97,101],['abc3',13,18,55],['abc4',56,79,100]]
df = pd.DataFrame(data,columns=['Bus','Existing_Fare','Petrol_Price','Salary_Hike'])
如果Petrol_Price> 80:Petrol_Price = 80,否則:數據框中給出的Petrol_Price
新價格=現有票價+汽油價格+ 2 *薪金加息
2.排名正確的順序。
產量
Bus New_Price Rank_Order Rank_duplicates
0 abc1 335 1 2
1 abc2 338 2 1
2 abc3 141 3 3
3 abc4 335 4 2
IIUC:
df.assign(
Petrol_Price=df.Petrol_Price.clip(0, 80)
).eval(
'New_Price=Existing_Fare + Petrol_Price + 2 * Salary_Hike'
).assign(
Rank_Duplicates=lambda d: d.New_Price.rank(method='dense', ascending=False)
)
Bus Existing_Fare Petrol_Price Salary_Hike New_Price Rank_Duplicates
0 abc1 55 80 100 335 2.0
1 abc2 56 80 101 338 1.0
2 abc3 13 18 55 141 3.0
3 abc4 56 79 100 335 2.0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.