Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace NaN in DataFrame index

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
like image 900
Boosted_d16 Avatar asked Sep 10 '15 16:09

Boosted_d16


People also ask

How do I remove NaN values from a data frame?

By using dropna() method you can drop rows with NaN (Not a Number) and None values from pandas DataFrame. Note that by default it returns the copy of the DataFrame after removing rows. If you wanted to remove from the existing DataFrame, you should use inplace=True .


2 Answers

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
like image 183
YS-L Avatar answered Sep 30 '22 18:09

YS-L


Use Index.fillna:

df.index = df.index.fillna('No label')
print (df)
          one  two
a           2    5
b           3    6
No label    0    0
like image 26
jezrael Avatar answered Sep 30 '22 18:09

jezrael