Python 多重数据帧中的多重赋值

Python 多重数据帧中的多重赋值,python,pandas,Python,Pandas,假设我有一个多索引数据帧,如下所示 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.9

假设我有一个多索引数据帧,如下所示

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)
但这不是在多索引数据帧中进行多个赋值的正确方法


谢谢

一种方法是通过
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  

我喜欢你的答案,但我希望新值是dataframe旧列的函数。有办法吗?非常感谢。