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
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
Use Index.fillna
:
df.index = df.index.fillna('No label')
print (df)
one two
a 2 5
b 3 6
No label 0 0