1

I have a multi-indexed dataframe df1 with three indices whose values only belong to the first index. However, after a merge, the dataframe got split up which resulted in various 0. Now I want to replace the 0 with the values belonging to the first index level.

Here is an extraction from the dataframe:

FID_Weser_Catchments_134_WQ_Stations_FINAL_LAEA... SNR1  gridcode_1               
1                                                  6631  2           543738.387186
                                                         3           543738.387186
                                                         4           543738.387186
                                                   6632  1           543738.387186
                                                         2           543738.387186
                                                         3           543738.387186
                                                         4           543738.387186
                                                   6633  2                0.000000
                                                         3                0.000000
                                                   6634  2                0.000000
                                                   6636  1           543738.387186
                                                         2           543738.387186
                                                         3           543738.387186
                                                         4           543738.387186
                                                   9473  2           543738.387186
                                                         3           543738.387186
                                                   9673  2           543738.387186
                                                         3           543738.387186
                                                         4           543738.387186
                                                   16054 1           543738.387186

FID_Weser_Catchments..., SNR1 and gridcode_1 are the indices but the values only originate from index(level=0). There are in total 133 index(level=0) so I want to find a general function to replace the 0 with the affiliated value.

1 Answer 1

1

Use Series.mask with replacement by Series created by GroupBy.transform with GroupBy.first by first level of MultiIndex:

first = s.groupby(level=0).transform('first')

s = s.mask(s == 0, first)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.