简体   繁体   中英

Division with MultiIndex Dataframes

I have a dataframe that looks like this

data = {'0': {('Field A', '0'): 10,
              ('Field A', '1'): 10,
              ('Field A', '2'): 10,
              ('Field B','0'): 6,
              ('Field B','1'): 6,
              ('Field B', '2'): 6},
       '48': {('Field A', '0'): 5,
              ('Field A', '1'): 2,
              ('Field A', '2'): 1,
              ('Field B', '0'): 3,
              ('Field B', '1'): 2,
              ('Field B', '2'): 1}}

df = pd.DataFrame(data)
df.index.names = ['field', 'well']
df.T.index.names = ['interval']

print(df)

    interval                          0  48
    field                      well        
    field A                    0     10   5
                               1     10   2
                               2     10   1
    field B                    0      6   3
                               1      6   2
                               2      6   1

I'm trying to figure out how to divide all the columns element-wise by the column "Interval 0".

The result should be :

interval                           0        48
field                      well               
Total Number of End Points 0     1.0  0.500000
                           1     1.0  0.200000
                           2     1.0  0.100000
Total Vessel Length        0     1.0  0.500000
                           1     1.0  0.333333
                           2     1.0  0.166667

You can use div() method(same as divide() with parameter axis set as 0 to perform along row element-wise division:

df.div(df['0'], axis = 0)

#interval         0       48
#field   well       
#Field A    0   1.0 0.500000
#           1   1.0 0.200000
#           2   1.0 0.100000
#Field B    0   1.0 0.500000
#           1   1.0 0.333333
#           2   1.0 0.166667

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM