[英]Pandas retrieve value in one column(s) corresponding to the maximum value in another
[英]Keep the value corresponding to the maximum of another column in a dataframe
我有一個 DataFrame
day type price
0 10900 2 300
1 10900 1 500
2 10900 3 200
3 10901 5 100
4 10901 2 400
5 10901 1 300
6 10902 2 100
7 10902 3 300
8 10902 1 200
9 10902 4 400
我希望每天保持最高類型的價格並復制當天的所有價格,因此結果將是:
day type price
0 10900 2 200
1 10900 1 200
2 10900 3 200
3 10901 5 100
4 10901 2 100
5 10901 1 100
6 10902 2 400
7 10902 3 400
8 10902 1 400
9 10902 4 400
所以這就是我正在做的事情,我想知道這是否是最好的方法,或者是否有辦法不使用合並並以另一種方式進行分組:
tmp_df=df[df.groupby('day')['type'].transform('max') == df['type']].reset_index()
df=df[['day','type']].merge(tmp_df[['day','price']],on='day')
df["price"] = df.groupby("day", as_index=False)["price"].transform(
lambda x: df.loc[df.loc[x.index, "type"].idxmax(), "price"]
)
print(df)
印刷:
day type price
0 10900 2 200
1 10900 1 200
2 10900 3 200
3 10901 5 100
4 10901 2 100
5 10901 1 100
6 10902 2 400
7 10902 3 400
8 10902 1 400
9 10902 4 400
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.