1

I Have a df and I am trying to update the value of some labels in the multiIndex based on the value of the columns on the same row.

At the moment, I drop the index level and use some masking as if it was a value column, but I feel there must be a much cleaner way of doing this

iterables = [['bar', 'baz', 'foo', 'qux'], ['A', 'B']]
index = pd.MultiIndex.from_product(iterables, names=['loadcase', 'location'])
df = pd.DataFrame(np.random.randn(8, 3), index=index, columns=['fx','fy','fz'])
df

                        fx       fy       fz
loadcase location                           
bar      A        -3.8e-01  2.3e-01 -2.3e+00
         B        -1.4e+00 -7.4e-01  2.6e-01
baz      A         1.1e+00 -1.1e+00 -1.2e-01
         B         5.6e-01  3.7e-01  2.8e+00
foo      A         6.2e-02 -6.2e-02 -9.7e-01
         B        -5.7e-01 -6.4e-01 -1.1e+00
qux      A         2.5e+00 -1.0e-01  4.1e-02
         B        -9.2e-01  9.8e-02 -1.0e+00

# drop the index location so it can be easily searched for.    
df.reset_index(level="location", inplace=True)

mask = (df["location"] == 'A') & (df["fx"] < 0)
df["location"].loc[mask] = "{}_NEG".format('A')

mask2 = df["location"] == 'A'
df["location"].loc[mask2] = "{}_POS".format('A')

#returning the index like it is the standard
df.reset_index(inplace=True)
df.set_index(["loadcase","location"], inplace=True)

This gives me the expected result:

                        fx       fy       fz
loadcase location                           
bar      A_NEG    -3.8e-01  2.3e-01 -2.3e+00
         B        -1.4e+00 -7.4e-01  2.6e-01
baz      A_POS     1.1e+00 -1.1e+00 -1.2e-01
         B         5.6e-01  3.7e-01  2.8e+00
foo      A_POS     6.2e-02 -6.2e-02 -9.7e-01
         B        -5.7e-01 -6.4e-01 -1.1e+00
qux      A_POS     2.5e+00 -1.0e-01  4.1e-02
         B        -9.2e-01  9.8e-02 -1.0e+00

But it is quite ugly and I would prefer not to drop the index to a regular column. How can you mask a dataframe and at the same time access the label (or a specific column) to change the values?

Additionally, I get the error SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame, which after looking at the doc still cannot make sense out of it.

Thanks!

3
  • 2
    Your data frame has two columns named fx. This could be very dangerous when you use values fx to change things. Apr 15, 2019 at 15:21
  • updated the typo, shoud have been fz
    – AlexP
    Apr 15, 2019 at 15:24
  • 1
    Indices are immutable
    – mch56
    Apr 15, 2019 at 16:18

1 Answer 1

0

I finally got around it with DataFrame.rename() function

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.