Jak przekonwertować indeks ramki danych pandy na kolumnę?

Wydaje się to dość oczywiste, ale nie mogę wymyślić, jak przekonwertować indeks ramki danych na kolumnę?

Na przykład:

df=
        gi       ptt_loc
 0  384444683      593  
 1  384444684      594 
 2  384444686      596  

Do,

df=
    index1    gi       ptt_loc
 0  0     384444683      593  
 1  1     384444684      594 
 2  2     384444686      596  
Author: jpp, 2013-12-09

7 answers

Albo:

df['index1'] = df.index

Lub, .reset_index:

df.reset_index(level=0, inplace=True)

Więc, jeśli masz ramkę multi-index z 3 poziomami indeksu, jak:

>>> df
                       val
tick       tag obs        
2016-02-26 C   2    0.0139
2016-02-27 A   2    0.5577
2016-02-28 C   6    0.0303

I chcesz przekonwertować poziomy 1st (tick) I 3rd (obs) w indeksie na kolumny, wykonaj:

>>> df.reset_index(level=['tick', 'obs'])
          tick  obs     val
tag                        
C   2016-02-26    2  0.0139
A   2016-02-27    2  0.5577
C   2016-02-28    6  0.0303
 930
Author: behzad.nouri,
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
2018-03-23 02:20:50

Dla MultiIndex można wyodrębnić jego subindex za pomocą

df['si_name'] = R.index.get_level_values('si_name') 

Gdzie si_name jest nazwą subindeksu.

 41
Author: Apogentus,
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
2015-06-26 14:13:58

Aby zapewnić nieco większą jasność, przyjrzyjmy się ramce danych z dwoma poziomami w indeksie (MultiIndex).

index = pd.MultiIndex.from_product([['TX', 'FL', 'CA'], 
                                    ['North', 'South']], 
                                   names=['State', 'Direction'])

df = pd.DataFrame(index=index, 
                  data=np.random.randint(0, 10, (6,4)), 
                  columns=list('abcd'))

Tutaj wpisz opis obrazka

Metoda reset_index, wywołana z domyślnymi parametrami, konwertuje wszystkie poziomy indeksów na kolumny i używa prostego RangeIndex jako nowego indeksu.

df.reset_index()

Tutaj wpisz opis obrazka

Użyj parametru level, aby kontrolować, które poziomy indeksów są konwertowane na kolumny. Jeśli to możliwe, użyj nazwy poziomu, która jest bardziej jednoznaczna. Jeśli nie ma poziomu nazwy, można odnosić się do każdego poziomu przez jego całkowitą lokalizację, która zaczyna się od 0 z zewnątrz. Możesz użyć tutaj wartości skalarnej lub listy wszystkich indeksów, które chcesz zresetować.

df.reset_index(level='State') # same as df.reset_index(level=0)

Tutaj wpisz opis obrazka

W rzadkich przypadkach, gdy chcesz zachować indeks i przekształcić indeks w kolumnę, możesz wykonać następujące czynności:

# for a single level
df.assign(State=df.index.get_level_values('State'))

# for all levels
df.assign(**df.index.to_frame())
 33
Author: Ted Petrou,
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-10-24 22:04:27

rename_axis + reset_index

Możesz najpierw zmienić nazwę indeksu na żądaną etykietę, następnie podnieść do szeregu:

df = df.rename_axis('index1').reset_index()

print(df)

   index1         gi  ptt_loc
0       0  384444683      593
1       1  384444684      594
2       2  384444686      596

To działa również dla MultiIndex ramek danych:

print(df)
#                        val
# tick       tag obs        
# 2016-02-26 C   2    0.0139
# 2016-02-27 A   2    0.5577
# 2016-02-28 C   6    0.0303

df = df.rename_axis(['index1', 'index2', 'index3']).reset_index()

print(df)

       index1 index2  index3     val
0  2016-02-26      C       2  0.0139
1  2016-02-27      A       2  0.5577
2  2016-02-28      C       6  0.0303
 24
Author: jpp,
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-20 12:13:16

Jeśli chcesz użyć metody reset_index i zachować istniejący indeks powinieneś użyć:

df.reset_index().set_index('index', drop=False)

Lub zmienić go na miejsce:

df.reset_index(inplace=True)
df.set_index('index', drop=False, inplace=True)

Na przykład:

print(df)
          gi  ptt_loc
0  384444683      593
4  384444684      594
9  384444686      596

print(df.reset_index())
   index         gi  ptt_loc
0      0  384444683      593
1      4  384444684      594
2      9  384444686      596

print(df.reset_index().set_index('index', drop=False))
       index         gi  ptt_loc
index
0          0  384444683      593
4          4  384444684      594
9          9  384444686      596

A jeśli chcesz pozbyć się etykiety indeksu możesz zrobić:

df2 = df.reset_index().set_index('index', drop=False)
df2.index.name = None
print(df2)
   index         gi  ptt_loc
0      0  384444683      593
4      4  384444684      594
9      9  384444686      596
 5
Author: bunji,
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
2018-11-03 21:33:11
df1 = pd.DataFrame({"gi":[232,66,34,43],"ptt":[342,56,662,123]})
p = df1.index.values
df1.insert( 0, column="new",value = p)
df1

    new     gi     ptt
0    0      232    342
1    1      66     56 
2    2      34     662
3    3      43     123
 3
Author: Avneesh Hota,
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-23 21:12:56

Bardzo prostym sposobem jest użycie metody reset_index ().Dla ramki danych df użyj poniższego kodu:

df.reset_index(inplace=True)

W ten sposób indeks stanie się kolumną, a używając inplace jako True, stanie się to stałą zmianą.

 -2
Author: maria_g,
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-05-15 12:06:35