This question already has answers here:
Pandas: add a column to a multiindex column dataframe
(2个答案)
去年关门了。
假设我有一个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)

但这不是在多索引数据帧中进行多个赋值的正确方法。
谢谢你

最佳答案

一种方法是通过pd.concat,将现有的数据文件连接到所需列的新数据框(由MultiIndex.from_product创建的两个列表的组合)和您的值IE。

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

关于python - Multindex Pandas Dataframe中的多重分配,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52244667/

10-12 22:13