我有一个数据框 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
使用窗口函数获取最高价格,然后返回价格等于最高价格的行: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
关于python - 在 Pandas 数据帧上运行 sql 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65600692/