2017-10-15 38 views

回答

1

您可以使用iloc

s.iloc[:3].index 

或者使用head

s.head(3).index 

s 
#index 
#155  14 
#2  555 
#1445  23 
#855  3 
#Name: items, dtype: int64 

s.iloc[:3].index.values 
#array([ 155, 2, 1445], dtype=int64) 

s.head(3).index.values 
#array([ 155, 2, 1445], dtype=int64) 
+0

,但它會給我的價值觀,是不是?我想要不到 –

0

如果z是系列那麼只需要:

L = z.index[:3].tolist() 

編輯的評論:

看來你DataFrameindex是列:

print (type(z)) 
<class 'pandas.core.frame.DataFrame'> 

#set index with column index 
z = z.set_index('index') 
#select values by position and convert to list 
L = z.index[:3].tolist() 
print (L) 
[155, 2, 1445] 

如果索引列是可能的選擇列,然後獲得通過位置前N值與Series.iloc

L = z['index'].iloc[:3].tolist() 

更好的是使用DataFrame.iloc,但需要positi在index柱也由get_loc的:

L = z.iloc[:3, df.columns.get_loc('index')].tolist() 
+0

謝謝。這是我得到的:「RangeIndex(start = 0,stop = 3,step = 1)」...它不包括索引的名稱。 –