Jak zresetować indeks w ramce danych pandy? [duplikat]

to pytanie ma już odpowiedzi tutaj : Jak przekonwertować indeks ramki danych pandy na kolumnę? (7 odpowiedzi) Zamknięty 1 rok temu .

Mam ramkę danych, z której usuwam kilka wierszy. W rezultacie otrzymuję dataframe, w którym indeks jest coś takiego: [1,5,6,10,11] i chciałbym go zresetować do [0,1,2,3,4]. Jak mogę to zrobić?


Wygląda na to, że działa:

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

Nie działa:

df = df.reindex()
Author: Scott Boston, 2013-12-10

3 answers

DataFrame.reset_index tego szukasz. Jeśli nie chcesz, aby została zapisana jako kolumna, wykonaj:

df = df.reset_index(drop=True)

If you don ' t want to reign:

df.reset_index(drop=True, inplace=True)
 800
Author: mkln,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-06-28 05:50:04

Inne rozwiązania to RangeIndex lub range:

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

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

Jest szybszy:

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
 56
Author: jezrael,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-15 11:40:58
data1.reset_index(inplace=True)
 14
Author: user10692571,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-01-31 19:47:12