-1

I currently have two dataframes which I wish to join:

df1 = {'col1': [1, 2, 3, 4, 5]}

   col1 
0     1     
1     2     
2     3     
3     4    
4     5     

df2 = {'col2': ['nan', 'nan', 3, 4]}

   col2 
0     nan     
1     nan     
2     3     
3     4    
         

Currently I would like to join the two dataframes. However, I would like for the second dataframe (df2) to be added from the bottom as shown below:

   col1  col2
0     1     nan
1     2     nan
2     3     nan
3     4     3
4     5     4

How might I do this? I currently have tried using pandas.join() but have had no luck with this.

Essentially I want to append from the bottom, as shown by the output, there is another null value that is created in the first row of the output.

plebman952
  • 17
  • 2

2 Answers2

1

Idea is set index by DataFrame.set_index in df2 by index of df1 from bottom by indexing for same length and then is used DataFrame.join:

df1 = pd.DataFrame({'col1': [1, 2, 3, 4, 5]})
df2 = pd.DataFrame({'col2': [np.nan, np.nan, 3, 4]})

idx = df1.index[-len(df2):]

df = df1.join(df2.set_index(idx))
print (df)
   col1  col2
0     1   NaN
1     2   NaN
2     3   NaN
3     4   3.0
4     5   4.0
jezrael
  • 629,482
  • 62
  • 918
  • 895
  • @plebman952 - Super! If my answer was helpful, don't forget [accept](https://meta.stackexchange.com/a/5235) it. Thanks. – jezrael Jun 29 '20 at 05:20
1
df1 = pd.DataFrame({'col1': [1, 2, 3, 4, 5]})
df2 = pd.DataFrame({'col2': ['nan', 'nan', 3, 4]})
pd.concat([df1,df2],axis=1)

output

    col1    col2
0   1   nan
1   2   nan
2   3   3
3   4   4
4   5   NaN
NAGA RAJ S
  • 409
  • 4
  • 10