在DataFrame索引中替换NaN [英] Replace NaN in DataFrame index

查看:727
本文介绍了在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

这篇关于在DataFrame索引中替换NaN的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆