Home > Enterprise >  Python: concat rows of two dataframes of different shapes
Python: concat rows of two dataframes of different shapes

Time:02-13

I have two dataframes:

df1 = pd.DataFrame(index = [0,1,2], columns=['USD', 'CAD'])
df1['USD'] = [1,2,3]
df1['CAD'] = [4,5,6]
df1:
    USD CAD
0   1   4
1   2   5
2   3   6

df2 = pd.DataFrame(index = [0,1], columns = ['currency','balance'])
df2['currency'] = ['USD', 'CAD']
df2['balance'] = [2,3]
df2:
    currency    balance
0   USD         2
1   CAD         3

I would like to add a row to df1 at index 0, and fill that row with the balance of df2 based on currency. So the final df should look like this:

df:
    USD CAD
0   2   3
1   1   4
2   2   5
3   3   6

How can I do this in a pythonic way? Thank you

CodePudding user response:

Try the following code:

df = pd.concat([df2.set_index('currency').T, df1], axis=0, ignore_index=True)
  • Related