Home > Back-end >  How to check if a value is negative in a pandas MultiIndex and change it?
How to check if a value is negative in a pandas MultiIndex and change it?

Time:07-01

I have panda MultiIndex Series like

MultiIndex([('WELT', 'N24 DOKU'),
            ('WELT',     'WELT')],
           names=['mandant', 'brand'])

if I print it, I got

mandant  brand
WELT     N24 DOKU    -2064766.36
         WELT       -34179650.21

Now the question is, how can I check if is there a negative value and if so, set it to 0.

CodePudding user response:

IIUC for get all negative values use boolean indexing:

out = s[s.lt(0)]

If need absolute values use Series.abs:

out = s.abs()

If need replace negative to to 0 use Series.clip:

out = s.clip(lower=0)

print (out)
mandant  brand   
WELT     N24 DOKU    0.0
         N24 DOKU    0.0
Name: a, dtype: float64

Or some another value use Series.mask:

out = s.mask(s.lt(0), 1)
print (out)
mandant  brand   
WELT     N24 DOKU    1.0
         N24 DOKU    1.0
Name: a, dtype: float64

CodePudding user response:

put array indexes according to your code

df.index.get_level_values(0).drop_duplicates()[-2:]
  • Related