Python 将熊猫系列作为列添加到多索引的数据帧填充级别

Python 将熊猫系列作为列添加到多索引的数据帧填充级别,python,pandas,dataframe,Python,Pandas,Dataframe,我有一个具有多索引的数据帧,以及一系列: 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'], inpl

我有一个具有多索引的数据帧,以及一系列:

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'])
我想将该系列添加为一个新列,填充每个级别的foo。有人能指出一种有效的方法吗

感谢

您可以通过索引值创建新列,通过
foo
值更改
系列
的索引,并通过创建的字典更改它们:


但是保持一个多索引索引为['foo','bar',并将's'作为一个新列?太好了!这将有助于减少我的新手脚本中的代码行。非常感谢。如果我的回答有帮助,别忘了。谢谢
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