2

I have a dataframe that I concatenate with an array.

s = pd.concat([dataframe, pd.Series(array)], ignore_index=False, axis=1)

My problem is that the length of the array is shorter which result in leading nan. I want to have trailing nan instead as the value correspond to the latest value at the bottom the frame.

Example:

   col1 col2 col3 
0    23   56   68
1    12   09   21
2    12   93   nan
3    12   64   nan

Should be:

   col1 col2 col3 
0    23   56   nan
1    12   09   nan
2    12   93   68
3    12   64   21

Any help would be appreciated.

delalma
  • 838
  • 3
  • 12
  • 24

2 Answers2

1
pd.concat([df, array.set_axis(df.index[-len(array):])], axis=1)

which sets the series' index to the last len(array) elements of the dataframe first and then concats. array = pd.Series(array) in your code.

to get

   col1  col2  col3
0    23    56   NaN
1    12     9   NaN
2    12    93  68.0
3    12    64  21.0
Mustafa Aydın
  • 17,645
  • 4
  • 15
  • 38
0

What about shifting index:

d = dataframe
s = pd.Series(array)
s.index += 2 # or len(d.index) - len(s.index) 
pd.concat([d,s],axis=1) 
Jacek Błocki
  • 452
  • 3
  • 9