2013-12-10 58 views
143

Bazı satırları kaldırdığım bir veri çerçevem ​​var. Sonuç olarak, indeksin bir şeye benzediği bir veri çerçevesini alıyorum: [1,5,6,10,11] ve bunu [0,1,2,3,4]'a sıfırlamak istiyorum. Nasıl yapabilirim?pandalar veri çerçevesindeki indeks nasıl sıfırlanır?

df = df.reset_index() 
del df['index'] 

aşağıdaki çalışmıyor:

df = df.reindex() 

cevap

318

reset_index() aradığınız budur

iş gibi görünüyor aşağıdaki

EKLENDİ. bunu bir sütun olarak kaydedilmiş istemiyorsanız, o zaman yapın:

df = df.reset_index(drop=True) 
+47

+1 'drop = True' – Rhubarb

+53

Veriyi aynı değişkene yeniden atamak yerine' inplace = True' argümanı ayarlayabilirsiniz. – ahuelamo

+1

"inplace = True" durumunda, yöntemin Hiçbiri – alyaxey

8

Başka çözümler atama RangeIndex veya range şunlardır:

df.index = pd.RangeIndex(len(df.index)) 

df.index = range(len(df.index)) 

O hızlıdır: için

df = pd.DataFrame({'a':[8,7], 'c':[2,4]}, index=[7,8]) 
df = pd.concat([df]*10000) 
print (df.head()) 

In [298]: %timeit df1 = df.reset_index(drop=True) 
The slowest run took 7.26 times longer than the fastest. This could mean that an intermediate result is being cached. 
10000 loops, best of 3: 105 µs per loop 

In [299]: %timeit df.index = pd.RangeIndex(len(df.index)) 
The slowest run took 15.05 times longer than the fastest. This could mean that an intermediate result is being cached. 
100000 loops, best of 3: 7.84 µs per loop 

In [300]: %timeit df.index = range(len(df.index)) 
The slowest run took 7.10 times longer than the fastest. This could mean that an intermediate result is being cached. 
100000 loops, best of 3: 14.2 µs per loop 
+0

@ Postasını döndürdüğünü unutmayın. Kaynak - En hızlı "len (df.index)", 381ns vs "df.shape" 1.17us. Oyr bir şey eksik mi? – jezrael

İlgili konular