如何从熊猫系列指数中删除Nan?

时间:2019-02-12 00:03:50

标签: python pandas

import pandas as pd
import numpy as np
df = pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', np.nan])
df.pop(np.nan)

Type error : can not do label indexing on class pandas.core.indexes.base.Index with these index [nan] of class float 

我尝试做

df.reset_index().dropna().set_index('index')

但是当我做df.pop('a')时,它给了我错误

1 个答案:

答案 0 :(得分:1)

如果s是熊猫系列,则s.reset_index()返回一个带有该系列索引的DataFrame作为其列之一(默认情况下命名为index)。请注意,s.reset_index(drop=True)返回一个Series,但放弃该索引。

您任务的一种解决方案是从最后一行建立的DataFrame中选择一个唯一的名为0的列:

# setup with the name "s" to represent a Series (keep "df" for DataFrames)
s = pd.Series([1,2,3,4], index=['a','b','c',np.nan]) 
res1 = s.reset_index().dropna().set_index('index')[0]
res1
index
a    1
b    2
c    3
Name: 0, dtype: int64

另一种选择是通过重新编制系列索引来删除空索引标签:

res2 = s.loc[s.index.dropna()]
res2
a    1
b    2
c    3
dtype: int64
相关问题