ste*_*esu 2 python nan multi-index dataframe pandas
使用重现我的确切问题的 DataFrame 进行更新
我有一个问题,NaN出现在索引中会导致非唯一行(自NaN !== NaN)。我需要删除NaN索引中出现的所有行。我之前的问题有一个带有单行的示例 DataFrame NaN,但是原始解决方案没有解决我的问题,因为它没有满足这个广告不佳的要求:
(请注意,在实际数据中,我有数千个这样的行,包括重复的行,因此
NaN !== NaN这在索引上是允许的)
(来自我原来的帖子)
>>>import pandas as pd
>>>import numpy as np
>>> df = pd.DataFrame([[1,1,"a"],[1,2,"b"],[1,3,"c"],[1,np.nan,"x"],[1,np.nan,"x"],[1,np.nan,"x"],[2,1,"d"],[2,2,"e"],[np.nan,1,"x"],[np.nan,2,"x"],[np.nan,1,"x"]], columns=["a","b","c"])
>>>df
c
a b
1.0 1.0 a
2.0 b
3.0 c
NaN x
NaN x
NaN x
2.0 1.0 d
2.0 e
NaN 1.0 x
2.0 x
1.0 x
Run Code Online (Sandbox Code Playgroud)
注意重复的行:(1.0, NaN)和(NaN, 1.0)
我尝试过一些简单的事情,例如:
>>>df = df[pandas.notnull(df.index)]
Run Code Online (Sandbox Code Playgroud)
但这会失败,因为notnull没有针对 MultiIndex 实现。
早期的答案之一还建议:
>>>df = df.reindex(df.index.dropna())
Run Code Online (Sandbox Code Playgroud)
但是,这失败并出现错误:
Exception: cannot handle a non-unique multi-index!
Run Code Online (Sandbox Code Playgroud)
>>>df
c
a b
1.0 1.0 a
2.0 b
3.0 c
2.0 1.0 d
2.0 e
Run Code Online (Sandbox Code Playgroud)
(所有NaN索引行都被删除,消除任何非唯一行)
选项 1
reset_index、dropna、 以及set_index再次。
c = df.index.names
df = df.reset_index().dropna().set_index(c)
df
c
a b
1.0 1.0 a
2.0 b
3.0 c
2.0 1.0 d
2.0 e
2.0 x
1.0 x
Run Code Online (Sandbox Code Playgroud)
如果您MultiIndex是独一无二的,您可以使用...
选项 2
df.index.dropna和df.reindex
df = df.reindex(df.index.dropna())
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2591 次 |
| 最近记录: |