Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas DataFrame Add column to index without resetting

how do I add 'd' to the index below without having to reset it first?

from pandas import DataFrame df = DataFrame( {'a': range(6), 'b': range(6), 'c': range(6)} ) df.set_index(['a','b'], inplace=True) df['d'] = range(6)  # how do I set index to 'a b d' without having to reset it first? df.reset_index(['a','b','d'], inplace=True) df.set_index(['a','b','d'], inplace=True)  df 
like image 319
user1441053 Avatar asked Jun 14 '12 20:06

user1441053


People also ask

How do I add a column to an index in a DataFrame?

To create an index, from a column, in Pandas dataframe you use the set_index() method. For example, if you want the column “Year” to be index you type <code>df. set_index(“Year”)</code>. Now, the set_index() method will return the modified dataframe as a result.

Why do we need reset index pandas?

reset_index in pandas is used to reset index of the dataframe object to default indexing (0 to number of rows minus 1) or to reset multi level index. By doing so, the original index gets converted to a column.

What does reset_index drop true do?

If you set drop = True , reset_index will delete the index instead of inserting it back into the columns of the DataFrame. If you set drop = True , the current index will be deleted entirely and the numeric index will replace it.

How do you set an index on a existing data frame?

To set the DataFrame index using existing columns or arrays in Pandas, use the set_index() method. The set_index() function sets the DataFrame index using existing columns. The index can replace the existing index or expand on it. Pandas DataFrame is nothing but an in-memory representation of an excel sheet via Python.


1 Answers

We added an append option to set_index. Try that.

The command is:

df.set_index(['d'], append=True) 

(we don't need to specify ['a', 'b'], as they already are in the index and we're appending to them)

like image 170
Wes McKinney Avatar answered Oct 07 '22 08:10

Wes McKinney