python - 如何在条件下应用公式以生成新列并应用两种类型的排名?
问题描述
输入:
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'])
- 我需要应用这个公式。
IF Petrol_Price>80: Petrol_Price=80 else: Petrol_Price 在数据框中给出
新价格 = Existing_Fare+Petrol_Price+2*Salary_Hike
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
解决方案
国际大学联盟:
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
推荐阅读
- c# - 将新数据添加到 LocalDB 后如何更新组合框
- python - 仅在带有硒的特定“id”中按“类”查找元素
- javascript - 一键切换多个类
- mysql - Node API 可以构建在顶级 MySQL 数据库上吗?
- typescript - 计算的属性名称不可分配给记录类型
- php - 当查询太大时,Axios 返回错误:“网络错误”
- c# - 为什么全局变量 DbContext 不能 SaveChanges?
- java - 使用 Google Maps Android - 读取 CSV 文件问题
- javascript - 使用javascript将图像添加/替换到活动元素
- php - 会话值始终等于最后一个实例