首页 > 解决方案 > 如何在条件下应用公式以生成新列并应用两种类型的排名?

问题描述

输入:

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'])
  1. 我需要应用这个公式。

IF Petrol_Price>80: Petrol_Price=80 else: Petrol_Price 在数据框中给出

新价格 = Existing_Fare+Petrol_Price+2*Salary_Hike

2.排名正确的顺序。

  1. 如果两个分数具有相同的值,则给它们相同的排名

输出

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

标签: pythonpandas

解决方案


国际大学联盟:

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

推荐阅读