Home > OS >  Pandas/Python - Dataframe transpose/pivot
Pandas/Python - Dataframe transpose/pivot

Time:02-11

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

CodePudding user response:

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
  • Related