2013-12-10 13 views
143

मेरे पास एक डेटा फ्रेम है जिसमें से मैं कुछ पंक्तियों को हटा देता हूं। नतीजतन, मुझे डेटा फ्रेम मिलता है जिसमें इंडेक्स कुछ ऐसा होता है: [1,5,6,10,11] और मैं इसे [0,1,2,3,4] पर रीसेट करना चाहता हूं। मैं यह कैसे कर सकता हूं?एक पांडा डेटा फ्रेम में इंडेक्स को रीसेट कैसे करें?

जोड़ा

निम्नलिखित काम करने के लिए लगता है:

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

निम्नलिखित काम नहीं करता:

df = df.reindex() 

उत्तर

318

reset_index() आप जो खोज रहे हैं है। आप इसे एक स्तंभ के रूप में सहेजा नहीं करना चाहते हैं, तो कार्य करें:

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

के +1 'ड्रॉप = True' – Rhubarb

+53

उसी चर में डेटाफ्रेम को फिर से सौंपने के बजाय आप' inplace = True' तर्क सेट कर सकते हैं। – ahuelamo

+1

ध्यान दें कि 'इनस्थल = ट्रू' के मामले में विधि कोई नहीं लौटाती है – alyaxey

8

एक अन्य समाधान कर रहे हैं असाइन RangeIndex या range:

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

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

यह तेजी से होता है:

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

@ ऑटकास्ट स्रोत - सबसे तेज़ 'लेन (df.index) ', 381ns बनाम' df.shape' 1.17us है। ओरी कुछ याद आ रही है? – jezrael

संबंधित मुद्दे