1

I have a dataframe called df1 that is:

               0
103773708  68.50
103773718  57.01
103773730  30.80
103773739  67.62

I have another one called df2 that is:

               0
103773739  37.02
103773708  30.25
103773730  15.50
103773718  60.54
105496332  20.00

I'm wondering how I would get them to combine to end up looking like df3:

               0      1
103773708  30.25  68.50
103773718  60.54  57.01
103773730  15.50  30.80
103773739  37.02  67.62
105496332  20.00  00.00

As you can see sometimes the index position is not the same, so it has to append the data to the same index. The goal is to append column 0 from df1, into df2 while pushing column 0 in df2 over one.

3 Answers3

0

Simply merge on index, and then relabel the columns:

df = pd.merge(df1, df2, left_index=True, right_index=True, how='outer')
df.columns = [0,1]
df = df.fillna(0)
Rocky Li
  • 5,641
  • 2
  • 17
  • 33
0
 result = df1.join(df2.rename(columns={0:1})).fillna(0)
it's-yer-boy-chet
  • 1,917
  • 2
  • 12
  • 21
0
df1.columns = ['1']         # Rename the column from '0' to '1'. I assume names as strings.
df=df2.join(df1).fillna(0)  # Join by default is LEFT

df
               0      1
103773739  37.02  67.20
103773708  30.25  68.50
103773730  15.50  30.80
103773718  60.54  57.01
105496332  20.00   0.00
cph_sto
  • 7,189
  • 12
  • 42
  • 78