Replace NaN in DataFrame index
Asked Answered
M

3

7

I have a DataFrame which looks like this:

      one | two 
a   |  2  |  5
b   |  3  |  6
NaN |  0  |  0

How do I replace the NaN in the index with a string, say "No label"?

I tried:

df = df.replace(np.NaN, "No label") 

and

df.index = df.index.replace(np.NaN, "No label") 

But got

TypeError: expected string or buffer
Matabele answered 10/9, 2015 at 16:2 Comment(0)
P
9

You can process the original index as a Series first and then re-assign the index:

import pandas as pd
import numpy as np
df = pd.DataFrame({'one': [2, 3, 0], 'two': [5, 6, 0]}, index=['a', 'b', np.nan])
df.index = pd.Series(df.index).replace(np.nan, 'No label')
print df

Output:

          one  two
a           2    5
b           3    6
No label    0    0
Playtime answered 10/9, 2015 at 16:16 Comment(2)
Dohhh! that's what I should've thought off. This does what I was looking for. Thanks!Matabele
There is a to_series method for converting an Index to Series: df.index = df.index.to_series().fillna('No label') will work finePolonaise
P
6

Use Index.fillna:

df.index = df.index.fillna('No label')
print (df)
          one  two
a           2    5
b           3    6
No label    0    0
Poe answered 5/2, 2019 at 14:31 Comment(1)
Note: This does not work with MultiIndex.Janenejanenna
O
2

In case anyone needs handling for the MultiIndex case too:

if isinstance(df.index, pd.MultiIndex):
    df.index = pd.MultiIndex.from_frame(
        df.index.to_frame().fillna("No label")
    )
else:
    df.index = df.index.fillna("No label")
Orison answered 12/4, 2021 at 14:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.