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
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 .
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With