Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I assign a reset index a name?

Tags:

python

pandas

Normally when a dataframe undergoes a reset_index() the new column is assigned the name index or level_i depending on the level.

Is it possible to assign the new column a name?

like image 964
Demetri Pananos Avatar asked Dec 01 '16 15:12

Demetri Pananos


People also ask

How do I reset index without creating new column?

Reset index without new column By default, DataFrame. reset_index() adds the current row index as a new 'index' column in DataFrame. If we do not want to add the new column, we can use the drop parameter. If drop=True then it does not add the new column of the current row index in the DataFrame.

Why do we use reset index?

The reset_index() function is used to generate a new DataFrame or Series with the index reset. For a Series with a MultiIndex, only remove the specified levels from the index. Removes all levels by default. Just reset the index, without inserting it as a column in the new DataFrame.

What does it mean to reset the index?

Definition and Usage The reset_index() method allows you reset the index back to the default 0, 1, 2 etc indexes. By default this method will keep the "old" idexes in a column named "index", to avoid this, use the drop parameter.


1 Answers

You can call rename on the returned df from reset_index:

In [145]: # create a df df = pd.DataFrame(np.random.randn(5,3)) df  Out[145]:           0         1         2 0 -2.845811 -0.182439 -0.526785 1 -0.112547  0.661461  0.558452 2  0.587060 -1.232262 -0.997973 3 -1.009378 -0.062442  0.125875 4 -1.129376  3.282447 -0.403731 

Set the index name

In [146]:     df.index = df.index.set_names(['foo']) df  Out[146]:             0         1         2 foo                               0   -2.845811 -0.182439 -0.526785 1   -0.112547  0.661461  0.558452 2    0.587060 -1.232262 -0.997973 3   -1.009378 -0.062442  0.125875 4   -1.129376  3.282447 -0.403731 

call reset_index and chain with rename:

In [147]: df.reset_index().rename(columns={df.index.name:'bar'})  Out[147]:    bar         0         1         2 0    0 -2.845811 -0.182439 -0.526785 1    1 -0.112547  0.661461  0.558452 2    2  0.587060 -1.232262 -0.997973 3    3 -1.009378 -0.062442  0.125875 4    4 -1.129376  3.282447 -0.403731 

Thanks to @ayhan

alternatively you can use rename_axis to rename the index prior to reset_index:

In [149]: df.rename_axis('bar').reset_index()  Out[149]:    bar         0         1         2 0    0 -2.845811 -0.182439 -0.526785 1    1 -0.112547  0.661461  0.558452 2    2  0.587060 -1.232262 -0.997973 3    3 -1.009378 -0.062442  0.125875 4    4 -1.129376  3.282447 -0.403731 

or just overwrite the index name directly first:

df.index.name = 'bar' 

and then call reset_index

like image 146
EdChum Avatar answered Oct 05 '22 13:10

EdChum