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
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.
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With