我有一个数据框 df
ID |
Price |
Region |
1 |
23 |
AUS |
1 |
45 |
DXB |
2 |
25 |
GER |
2 |
18 |
TUN |
我想用 python 编写代码以获得以下输出
ID |
Price |
Region |
1 |
45 |
DXB |
2 |
25 |
TUN |
我尝试使用 pandasql 来获取输出,但它没有给出我想要的输出
我尝试过的代码是
import pandas as pd
import pandasql as ps
#to read table
df=pd.read_excel("test.xlsx")
ps.sqldf("select ID, max(Price), Region from df order by ID")
如果 python 本身(不使用 pandasql)有任何其他代码可以得到上述输出,请告诉我
您可以使用groupby.transform
output_df = df[df['Price'].eq(df.groupby("ID")['Price'].transform("max"))]
Or with ps.sqldf
使用窗口函数获取最高价格,然后返回价格等于最高价格的行:
output_df = ps.sqldf("""select ID,Price,Region from
(select *, max(Price) over (partition by ID) max_Price from df)
where Price = max_Price""")
ID Price Region
0 1 45 DXB
1 2 25 GER
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)