我有一个如下所示的 DataFrame:
one | two
a | 2 | 5
b | 3 | 6
NaN | 0 | 0
如何用字符串替换索引中的 NaN,比如“无标签”?
我试过了:
df = df.replace(np.NaN, "No label")
和
df.index = df.index.replace(np.NaN, "No label")
但是得到了
TypeError: expected string or buffer
最佳答案
您可以先将原始索引作为系列处理,然后重新分配索引:
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
关于pandas - 替换 DataFrame 索引中的 NaN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32506689/