在DataFrame索引中替换NaN

问题描述:

我有一个看起来像这样的DataFrame:

I have a DataFrame which looks like this:

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

如何用一个字符串替换索引中的NaN,说无标签"?

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

我尝试过:

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

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

但是得到了

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

输出:

          one  two
a           2    5
b           3    6
No label    0    0