Search code examples
pythondataframeassign

Using assign to add a Series to a DataFrame in order to create a new DataFrame


Given this data frame called 'names' and a series calles 'surnames', which is sorted differently, is it possible to use the assign function to add (on the left) the series to the data frame, to create a new data frame and maintain the order of 'name'?

 name = pd.DataFrame({'name': ['Max', 'Andre', 'Albert'],
     'country': ['Germany', 'France', 'Germany']}, 
      index= ['Max', 'Andre', 'Albert'])

 surname = pd.Series(['Ampere', 'Einstein', 'Planck'],
               index = ("Andre", "Albert", "Max"))
                                                                                                 

I tried several things, but I don't get the column surname neither on the left, nor in the right order...

Thanks a lot for your help!


Solution

  • Did you try

    name = name.assign(surname=surname)[['surname', 'name', 'country']]