简体   繁体   中英

Pandas/Python - Dataframe transpose/pivot

I have a dataframe from "df.groupby("symbol").tail(2)" such as below

ID symbol prices
0 BNBBTC 0.009545
1 BNBBTC 0.009455
2 ONEUSDT 0.220050
3 ONEUSDT 0.220055

and I would like to transpose/pivot the data to get

ID symbol Last_Price Current_Price
0 BNBBTC 0.009545 0.009455
1 ONEUDST 0.220050 0.220055

Is it achievable with Pandas?

Thanks

Maybe you can use groupby + agg :

new_df = df.groupby('symbol')['prices'].agg(Last_Price='first', Current_Price='last').reset_index()

Output:

>>> new_df
    symbol  Last_Price  Current_Price
0   BNBBTC    0.009545       0.009455
1  ONEUSDT    0.220050       0.220055

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM