Pandas DataFrame Add column to index without resetting
Question:
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
Answers:
Your code is not valid, reset_index has no inplace argument in my version of pandas (0.8.1).
The following achieves what you want but there’s probably a more elegant way, but you’ve not provided enough information as to why you are avoiding the reset_index.
df2.index = MultiIndex.from_tuples([(x,y,df2['d'].values[i]) for i,(x,y) in enumerate(df2.index.values)])
HTH
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)
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
Your code is not valid, reset_index has no inplace argument in my version of pandas (0.8.1).
The following achieves what you want but there’s probably a more elegant way, but you’ve not provided enough information as to why you are avoiding the reset_index.
df2.index = MultiIndex.from_tuples([(x,y,df2['d'].values[i]) for i,(x,y) in enumerate(df2.index.values)])
HTH
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)