Home > OS >  Using assign to add a Series to a DataFrame in order to create a new DataFrame
Using assign to add a Series to a DataFrame in order to create a new DataFrame

Time:11-05

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!

CodePudding user response:

Did you try

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

CodePudding user response:

Yep, make sure you name your series so it'll have a column name, but you just have to call concat as such:

import pandas as pd
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"), name='Surname')

pd.concat([name, surname], axis=1)
# or
name.assign(Surname=surname)

enter image description here

  • For more complex combinations of dataframes and series (matrices and vectors), look into the pandas docs about merge, concat, join
  • Related