简体   繁体   中英

Add pandas Series as a column to DataFrame filling levels of multi-index

I have a dataframe with multi-index, and a series:

import pandas as pd
import numpy as np

df = pd.DataFrame({'foo':['A','A','A','B','B','B','C','C','C'],
                   'bar':[1,2,3,1,2,3,1,2,3],
                   'vals':np.random.randn(9)})
df.set_index(['foo','bar'], inplace=True)

s = pd.Series(['ham','eggs','cheese'])

I want to add the series as a new column, filling each level of foo. Can anyone point out an efficient way of doing this?

Thanks

You can use get_level_values for creating new column by index values, change index of Serie by foo values and map them by dictionary created to_dict :

s.index = ['A','B','C']
print s
A       ham
B      eggs
C    cheese
dtype: object

df['new'] = df.index.get_level_values('foo')
print df
             vals new
foo bar              
A   1   -2.877779   A
    2   -0.661478   A
    3    0.705928   A
B   1   -0.358598   B
    2    0.731982   B
    3   -0.036367   B
C   1    0.588914   C
    2   -0.779635   C
    3    0.476337   C

df['new'] = df['new'].map(s.to_dict())
print df
             vals     new
foo bar                  
A   1   -2.877779     ham
    2   -0.661478     ham
    3    0.705928     ham
B   1   -0.358598    eggs
    2    0.731982    eggs
    3   -0.036367    eggs
C   1    0.588914  cheese
    2   -0.779635  cheese
    3    0.476337  cheese

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