I’m trying to multiply all the values of the following multiindex df for which the first multiindex equals Property_2 with a scalar:
JavaScript
x
8
1
(index_1,index_2) Col1
2
Property_1 A 1
3
B 2
4
C 3
5
Property_2 D 1
6
E 2
7
F 3
8
I’ve tried various ways:
JavaScript
1
3
1
df.loc[Property_2,:] = df.loc[Property_2,:]*0.01
2
df.loc[(Property_2,:),:] = df.loc[(Property_2,:),:]*0.01
3
but I am getting back nan’s in the relevant places.
Advertisement
Answer
That’s because the indices don’t match. One way to get around the issue is to assign the underlying numpy array:
JavaScript
1
2
1
df.loc['Property_2', 'Col1'] = df.loc['Property_2', 'Col1'].mul(0.01).to_numpy()
2
or you could use mask
:
JavaScript
1
2
1
df['Col1'] = df['Col1'].mask(df.index.get_level_values(0) == 'Property_2', df['Col1']*0.01)
2
Output:
JavaScript
1
9
1
Col1
2
index_1 index_2
3
Property_1 A 1.00
4
B 2.00
5
C 3.00
6
Property_2 D 0.01
7
E 0.02
8
F 0.03
9