[英]Run sql query on pandas dataframe
我有一个 dataframe df
ID | 价格 | 地区 |
---|---|---|
1 | 23 | 澳大利亚 |
1 | 45 | DXB |
2 | 25 | GER |
2 | 18 | 屯 |
我想在 python 中写一段代码得到下面的 output
ID | 价格 | 地区 |
---|---|---|
1 | 45 | DXB |
2 | 25 | 屯 |
我尝试使用 pandasql 来获取 output 但它没有给出我想要的 output
我试过的代码是
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)有任何其他代码可以得到上述output,请告诉我
您可以使用groupby.transform
output_df = df[df['Price'].eq(df.groupby("ID")['Price'].transform("max"))]
或者使用ps.sqldf
使用 window function 获得最高价格,然后返回价格等于最高价格的行:
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
你可以做:
df.sort_values('Price').drop_duplicates('ID', keep='last')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.