替换 DataFrame 索引中的 NaN
Replace NaN in DataFrame index
我有一个如下所示的 DataFrame:
one | two
a | 2 | 5
b | 3 | 6
NaN | 0 | 0
如何用字符串替换索引中的 NaN,比如 "No label"?
我试过了:
df = df.replace(np.NaN, "No label")
和
df.index = df.index.replace(np.NaN, "No label")
但是得到了
TypeError: expected string or buffer
可以先将原索引处理成Series,再重新赋值:
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
使用Index.fillna
:
df.index = df.index.fillna('No label')
print (df)
one two
a 2 5
b 3 6
No label 0 0
如果有人也需要处理 MultiIndex 案例:
if isinstance(df.index, pd.MultiIndex):
df.index = pd.MultiIndex.from_frame(
df.index.to_frame().fillna("No label")
)
else:
df.index = df.index.fillna("No label")
我有一个如下所示的 DataFrame:
one | two
a | 2 | 5
b | 3 | 6
NaN | 0 | 0
如何用字符串替换索引中的 NaN,比如 "No label"?
我试过了:
df = df.replace(np.NaN, "No label")
和
df.index = df.index.replace(np.NaN, "No label")
但是得到了
TypeError: expected string or buffer
可以先将原索引处理成Series,再重新赋值:
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
使用Index.fillna
:
df.index = df.index.fillna('No label')
print (df)
one two
a 2 5
b 3 6
No label 0 0
如果有人也需要处理 MultiIndex 案例:
if isinstance(df.index, pd.MultiIndex):
df.index = pd.MultiIndex.from_frame(
df.index.to_frame().fillna("No label")
)
else:
df.index = df.index.fillna("No label")