Home > Blockchain >  Merge a Dataframe and a Series with the same index
Merge a Dataframe and a Series with the same index

Time:01-18

I got a Dataframe as below:

            Name     Sales
Datetime
2021-06-01  Amy      1000
2021-06-02  Amy      1500
2021-06-03  Amy      2300
2021-06-01  Joyce    3200
2021-06-02  Joyce    1422
2021-06-03  Joyce    1002

And I got another Series as shown below:

             Weather
Datetime
2021-06-01   Rain
2021-06-02   Clear
2021-06-03   Rain, Cloudy

What I expect is merging the dataframe and the series based on the index:

            Name     Sales   Weather
Datetime
2021-06-01  Amy      1000    Rain
2021-06-02  Amy      1500    Clear
2021-06-03  Amy      2300    Rain, Cloudy
2021-06-01  Joyce    3200    Rain
2021-06-02  Joyce    1422    Clear
2021-06-03  Joyce    1002    Rain, Cloudy

Thanks!

CodePudding user response:

As you posted it, the "Series" is a one column DataFrame. Anyway, all you have to do is make an assignment. pandas will match the index for you.

data

>>> df 
             Name  Sales
Datetime                
2021-06-01    Amy   1000
2021-06-02    Amy   1500
2021-06-03    Amy   2300
2021-06-01  Joyce   3200
2021-06-02  Joyce   1422
2021-06-03  Joyce   1002
>>> df2 
                 Weather
Datetime                
2021-06-01          Rain
2021-06-02         Clear
2021-06-03  Rain, Cloudy

solution

>>> df['Weather'] = df2
>>> df 
             Name  Sales       Weather
Datetime                              
2021-06-01    Amy   1000          Rain
2021-06-02    Amy   1500         Clear
2021-06-03    Amy   2300  Rain, Cloudy
2021-06-01  Joyce   3200          Rain
2021-06-02  Joyce   1422         Clear
2021-06-03  Joyce   1002  Rain, Cloudy

CodePudding user response:

You can use for add DataFrame by DataFrame.join:

df = df.join(df1['Weather'])

If need add Series:

df = df.join(s.rename('Weather'))
  •  Tags:  
  • Related