Daniel Zuluaga
Daniel Zuluaga

Reputation: 72

Multiply pandas dataframe with factor from other dataframe

The columns of a multi-index data frame, say,

df_multi = pd.DataFrame({'angles': [0, 3, 4, 4, 5, 6],
                 'degrees': [360, 180, 360, 360, 540, 720]},
                index=[['A', 'A', 'A', 'B', 'B', 'B'],
                       ['circle', 'triangle', 'rectangle',
                        'square', 'pentagon', 'hexagon']])
df_scale = pd.DataFrame({'factor': [0,1]},index = ['A','B'])
             angles  degrees
A circle          0      360
  triangle        3      180
  rectangle       4      360
B square          4      360
  pentagon        5      540
  hexagon         6      720

   factor
A       0
B       1

should be multiplied by a scaling factor from another data frame where the indices on a given level match. I tried

df_scale.mul(df_multi, level = 0, axis = 'index')

but this does produce three columns with NaN values, instead of

             angles  degrees
A circle          0        0
  triangle        0        0
  rectangle       0        0
B square          4      360
  pentagon        5      540
  hexagon         6      720

Upvotes: 3

Views: 111

Answers (1)

Andrej Kesely
Andrej Kesely

Reputation: 195438

x = df_multi.mul(df_scale["factor"], level=0, axis="index")
print(x)

Prints:

             angles  degrees
A circle          0        0
  triangle        0        0
  rectangle       0        0
B square          4      360
  pentagon        5      540
  hexagon         6      720

Upvotes: 2

Related Questions