Multindex Pandas数据框中的多重分配

时间:2018-09-09 12:45:53

标签: python pandas

假设我有一个像下面这样的multindex数据框

In [221]: df
Out[221]:
first        bar                 baz
second       one       two       one       two
A      -1.089798  2.053026  0.470218  1.440740
B       0.488875  0.428836  1.413451 -0.683677
C      -0.243064 -0.069446 -0.911166  0.47837

我想在每个第一级列“ bar”和“ baz”中添加第三列和第四列。

我一直在尝试使用:

df[['bar','baz'],['third','forth']]=prices_df.apply(
    lambda row: pd.Series(get_bond_metrics(row))
    , axis=1)

但这不是在多索引数据框中进行多个分配的正确方法。

谢谢

1 个答案:

答案 0 :(得分:0)

一种方法是通过pd.concat,将现有数据框与所需列的新数据框(由MultiIndex.from_product创建,它提供两个列表的组合)和值即

连接起来
df
first        bar                 baz          
second       one       two       one       two
0      -0.122485  0.943154  1.253930 -0.955231
1      -0.293157 -1.167648 -0.864481  1.251452

values = np.random.randn(2,4) # here goes your values

df2 = pd.DataFrame(values, columns=pd.MultiIndex.from_product([['bar','baz'],['third','forth']]))

# Column wise concatenation followed by sorting of index for better view
ndf = pd.concat([df,df2],axis = 1).sort_index(level='first',axis=1,sort_remaining=False)

输出:

first        bar                                     baz                      \
second       one       two     third     forth       one       two     third   
0      -0.122485  0.943154 -0.419076  0.667690  1.253930 -0.955231 -0.858656   
1      -0.293157 -1.167648  0.516346 -0.907558 -0.864481  1.251452  0.429894   

first             
second     forth  
0       0.237544  
1      -0.521049