Python Concat two dataframe after grouping and sort

Question:

i have two pandas frame and i want to get one

     asks_price  asks_qty exchange_name_ask
0      20156.51  0.000745          Coinbase
1      20156.52  0.050000          Coinbase
     bids_price  bids_qty exchange_name_bid
2      20153.28  0.000200          Coinbase
3      20153.27  0.051000          Coinbase


Get ====>

     asks_price  asks_qty exchange_name_ask     bids_price  bids_qty exchange_name_bid
0      20156.51  0.000745          Coinbase      20153.28  0.000200          Coinbase
1      20156.52  0.050000          Coinbase      20153.27  0.051000          Coinbase

ask_snapshot = ask_snapshot.groupby('asks_price')['asks_qty'].sum().reset_index()
bid_snapshot = bid_snapshot.groupby('bids_price')['bids_qty'].sum().reset_index()
ask_snapshot = ask_snapshot.sort_values(by='asks_price').reset_index()
bid_snapshot = bid_snapshot.sort_values(by='bids_price', ascending=False).reset_index()
ask = ask_snapshot.head(20)
bid = bid_snapshot.head(20)

snapshot = pd.concat([ask, bid], axis=1, join='inner')

in the snapshot the exchange_name column disappear, i dont know why
Thanks

Asked By: Nathan

||

Answers:

You can try this

snapshot = pd.concat([ask_snapshot.reset_index(drop=True),
    bid_snapshot.reset_index(drop=True)], axis=1)
Answered By: Troll

The two columns exchange_name.. doesn’t disappear when you use pandas.concat but they simply doesn’t exist in the two dataframes passed as arguments.

Try this :

ask_snapshot = ask_snapshot.groupby(['asks_price', 'exchange_name_ask'], as_index=False)['asks_qty'].sum()
bid_snapshot = bid_snapshot.groupby(['bids_price', 'exchange_name_bid'], as_index=False)['bids_qty'].sum()
ask_snapshot = ask_snapshot.sort_values(by='asks_price').reset_index()
bid_snapshot = bid_snapshot.sort_values(by='bids_price', ascending=False).reset_index()
ask = ask_snapshot.head(20)
bid = bid_snapshot.head(20)

snapshot = pd.concat([ask, bid], axis=1)
Answered By: abokey
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.