简体   繁体   中英

Merge a Dataframe and a Series with the same index

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!

You can use for add DataFrame by DataFrame.join :

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

If need add Series :

df = df.join(s.rename('Weather'))

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM