我有一个数据框df
ID | 价钱 | 地区 |
---|---|---|
1个 | 23 | 出 |
1个 | 45 | DXB |
2 | 25 | 德国 |
2 | 18岁 | 去做 |
我想在python中编写代码以获取以下输出
ID | 价钱 | 地区 |
---|---|---|
1个 | 45 | DXB |
2 | 25 | 去做 |
我尝试使用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"))]
或ps.sqldf
使用窗口函数获取最高价格,然后返回Price等于最高价格的行:
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句