你可以使用isnull
方法在那些索引你有NaN
值,然後對當前步驟,你可以用比較下你的索引查找:
In [48]: s.index[s.isnull()]
Out[48]: Int64Index([3, 4, 5, 9, 10, 11], dtype='int64')
你也可以使用first_valid_index
找到第一個非NaN
值如:
In [49]: s[4:]
Out[49]:
4 NaN
5 NaN
6 7
7 8
8 9
9 NaN
10 NaN
11 NaN
12 10
13 10
dtype: float64
In [50]: s[4:].first_valid_index()
Out[50]: 6
編輯
如果你想爲一個整數索引,你可以使用熊貓指數get_loc
:
b = s[4:]
In [156]: b
Out[156]:
4 NaN
5 NaN
6 7
7 8
8 9
9 NaN
10 NaN
11 NaN
12 10
13 10
dtype: float64
In [157]: b.first_valid_index()
Out[157]: 6
In [158]: b.index.get_loc(b.first_valid_index())
Out[158]: 2
EDIT2
你可以使用get_indexer
讓您擁有NaNs
,並在那裏你有有效值所有指數:
import string
s = pd.Series([5, 6, 5, np.nan, np.nan, np.nan, 7, 8, 9, np.nan, np.nan, np.nan, 10, 10], index = list(string.ascii_letters[:len(s.index)]))
In [216]: s
Out[216]:
a 5
b 6
c 5
d NaN
e NaN
f NaN
g 7
h 8
i 9
j NaN
k NaN
l NaN
m 10
n 10
dtype: float64
valid_indx = s.index.get_indexer(s.index[~s.isnull()])
nan_indx = s.index.get_indexer(s.index[s.isnull()])
In [220]: valid_indx
Out[220]: array([ 0, 1, 2, 6, 7, 8, 12, 13])
In [221]: nan_indx
Out[221]: array([ 3, 4, 5, 9, 10, 11])
或者最簡單的方法將與np.where
:
In [222]: np.where(s.isnull())
Out[222]: (array([ 3, 4, 5, 9, 10, 11], dtype=int32),)
In [223]: np.where(~s.isnull())
Out[223]: (array([ 0, 1, 2, 6, 7, 8, 12, 13], dtype=int32),)
謝謝!我可以得到整數索引而不是自己定義的索引嗎? – xxx222
@ xxx222我認爲你可以這樣做'reset_index(drop = True)'使你的索引從0開始。或者你還需要那些索引來做別的事嗎? –
是的,我想在這之後返回一個插值的系列(所以我想保留這些索引)。 – xxx222