简体   繁体   English

将pandas Series作为列添加到多索引的DataFrame填充级别

[英]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.我想将该系列添加为一个新列,填充 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 :您可以使用get_level_values通过索引值创建新列,通过foo值更改Serie的索引并通过创建的字典map它们mapto_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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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