在使用 MultiIndex 读取 Excel 工作表后,我发现 np.nan 出现在索引中,因为某些值是“N/A”,并且 pd.read_excel 认为转换它们是个好主意。但是我想将它们保留为“N/A”以保留多索引。我认为使用 MultiIndex.fillna 将它们更改回来很容易,但我收到此错误:
index = pd.MultiIndex(levels=[[u'foo', u'bar'], [u'one', np.nan]],
codes=[[0, 0, 1, 1], [0, 1, 0, 1]],
names=[u'first', u'second'])
df = pd.DataFrame(index=index, columns=['A', 'B'])
df
df.index.fillna("N/A")
输出:
---------------------------------------------------------------------------
NotImplementedError Traceback (most recent call last)
<ipython-input-17-09e14dcdc74f> in <module>
----> 1 df.index.fillna("N/A")
/anaconda3/envs/torch/lib/python3.7/site-packages/pandas/core/indexes/multi.py in fillna(self, value, downcast)
1456 fillna is not implemented for MultiIndex
1457 """
-> 1458 raise NotImplementedError("isna is not defined for MultiIndex")
1459
1460 @Appender(_index_shared_docs["dropna"])
NotImplementedError: isna is not defined for MultiIndex
更新:
更新代码以反射(reflect) Pandas 1.0.2。在版本 0.24.0 之前,pd.MultiIndex
的 codes
属性称为 labels
。此外,回溯详细信息从 isnull is not Defined
更改为 isna is not Defined
,如上所述。
最佳答案
接受的解决方案对我来说也不起作用。即使单独检查 df.index.levels 没有显示 NA 值,它仍然在索引中留下 NA 值。
豪尔赫的solution为我指明了正确的方向,但也不太适合我的情况。这是我的方法,包括处理单个 Index
情况,如已接受答案的评论中所讨论的。
if isinstance(df.index, pd.MultiIndex):
df.index = pd.MultiIndex.from_frame(
df.index.to_frame().fillna(my_fillna_value)
)
else:
df.index = df.index.fillna(my_fillna_value)
关于pandas - 替换 Pandas MultiIndex 的所有级别中的 NaN 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39502404/