Bil*_*ill 5 nan multi-index dataframe pandas
在使用 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
Run Code Online (Sandbox Code Playgroud)
df.index.fillna("N/A")
Run Code Online (Sandbox Code Playgroud)
输出:
---------------------------------------------------------------------------
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
Run Code Online (Sandbox Code Playgroud)
更新:
更新代码以反映 Pandas 1.0.2。在版本 0.24.0 之前,codes的属性pd.MultiIndex称为labels。此外,回溯详细信息从 更改isnull is not defined为isna is not defined如上所述。
接受的解决方案对我来说也不起作用。即使单独检查df.index.levels没有显示 NA 值,它仍然在索引中留下 NA 值。
豪尔赫的解决方案为我指明了正确的方向,但也不太适合我的情况。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)
Run Code Online (Sandbox Code Playgroud)