Home > Back-end >  Python Pandas concat or update
Python Pandas concat or update

Time:09-28

I'm looking for a function that allows me to concat and update quickly

    exchange_name_bid  bids_price  bids_qty
0                 Ftx     18990.0    0.0846
1                 Ftx     18989.0    0.4097
2                 Ftx     18988.0    0.5834

and concat with

    exchange_name_bid  bids_price  bids_qty
0                 Ftx     18988.0    0.9854

If the price already exists I want to replace the quantity and keep the same price and name. And if the price does not exist I want to enter the line and do a normal concat

    exchange_name_bid  bids_price  bids_qty
0                 Ftx     18990.0    0.0846
1                 Ftx     18989.0    0.4097
2                 Ftx     18988.0    0.9854

else with a new price

    exchange_name_bid  bids_price  bids_qty
0                 Ftx     18938.0    0.2354

get

    exchange_name_bid  bids_price  bids_qty
0                 Ftx     18990.0    0.0846
1                 Ftx     18989.0    0.4097
2                 Ftx     18938.0    0.2354

Thanks for help

CodePudding user response:

IIUC use:

 df = pd.concat([df1, df2]).drop_duplicates(['exchange_name_bid','bids_price'], keep='last')

CodePudding user response:

Using a for to keep the order:

for i, row2 in df2.iterrows():
    cond = (df1["exchange_name_bid"] == row2["exchange_name_bid"]) & (df1["bids_price"] == row2["bids_price"])
    if any(cond):
        df1[cond] = row2
    else:
        df1 = df1.append(row2)
  • Related