Referencing columns using column headers of other dataframe

Viewed 38

I have the following dataframe "A":

             1   2   3
Date                  
1971-01-04  46  47   9
1971-01-05  95  58   6
1971-01-06  30  52  85

and the following empty dataframe "B", with the same row indices as "A", and multi-index columns:

              1         
level_1       1         2         3
Date                               
1971-01-04  
1971-01-05  
1971-01-06  

I'm trying to fill "B" using either of the two levels of the column headers to identify the column of "A" to get the data from.

So, when using the first column headers level [1, 1, 1], this is the expected output:

1971-01-04  46  46  46
1971-01-05  95  95  95
1971-01-06  30  30  30

and this is the expected output when using the second column headers level [1, 2, 3]:

1971-01-04  46  47   9
1971-01-05  95  58   6
1971-01-06  30  52  85

I could iterate through columns but I guess there's a better way. Thanks

1 Answers

Unless I'm misunderstanding, you can just index directly into A without having to create B at all

A = pd.DataFrame({
    'Date': ['1971-01-04', '1971-01-05', '1971-01-06'],
    1: [46, 95, 30],
    2: [47, 58, 52],
    3: [9, 6, 85],
})

A = A.set_index('Date')


print(A[[1,1,1]])
#              1   1   1
# Date                  
# 1971-01-04  46  46  46
# 1971-01-05  95  95  95
# 1971-01-06  30  30  30

print(A[[1,2,3]])
#              1   2   3
# Date                  
# 1971-01-04  46  47   9
# 1971-01-05  95  58   6
# 1971-01-06  30  52  85


#here's how you could "reset" the column names
print(A[[2,2,3]].set_axis(range(3), axis=1))
Related