簡體   English   中英

熊貓:在多索引數據框中創建新的(子級別)列並分配值

[英]Pandas: create new (sub-level) columns in a multi-index dataframe and assign values

讓我們得到一個像下面這樣的數據幀:

import pandas as pd 
import numpy as np

a = ['a', 'b']
b = ['i', 'ii']
mi = pd.MultiIndex.from_product([a,b], names=['first', 'second'])
A = pd.DataFrame(np.zeros([3,4]), columns=mi)
first     a         b
second    i   ii    i   ii
0       0.0  0.0  0.0  0.0
1       0.0  0.0  0.0  0.0
2       0.0  0.0  0.0  0.0

我想為所有first級列創建新列iii並分配(匹配大小)新數組的值。 我嘗試了以下方法,但無濟於事。

A.loc[:,pd.IndexSlice[:,'iii']] = np.arange(6).reshape(3,-1)

結果應如下所示:

     a              b
     i   ii  iii    i   ii  iii
0  0.0  0.0  0.0  0.0  0.0  1.0
1  0.0  0.0  2.0  0.0  0.0  3.0
2  0.0  0.0  4.0  0.0  0.0  5.0

由於列中有多個索引,因此我建議創建附加的append df,然后再將其concat

appenddf=pd.DataFrame(np.arange(6).reshape(3,-1),           
              index=A.index,
              columns=pd.MultiIndex.from_product([A.columns.levels[0],['iii']]))

appenddf
    a   b
  iii iii
0   0   1
1   2   3
2   4   5
A=pd.concat([A,appenddf],axis=1).sort_index(level=0,axis=1)
A
first     a             b         
second    i   ii iii    i   ii iii
0       0.0  0.0   0  0.0  0.0   1
1       0.0  0.0   2  0.0  0.0   3
2       0.0  0.0   4  0.0  0.0   5

另一個可行的解決方案

for i,x in enumerate(A.columns.levels[0]):
    A[x,'iii']=np.arange(6).reshape(3,-1)[:,i]
A
first     a         b        a   b
second    i   ii    i   ii iii iii
0       0.0  0.0  0.0  0.0   0   1
1       0.0  0.0  0.0  0.0   2   3
2       0.0  0.0  0.0  0.0   4   5
# here  I did not add `sort_index` 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM