Skip to content

reset_index + set_index with drop=False #6181

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
cancan101 opened this issue Jan 30, 2014 · 6 comments
Closed

reset_index + set_index with drop=False #6181

cancan101 opened this issue Jan 30, 2014 · 6 comments

Comments

@cancan101
Copy link
Contributor

Is there a simple way to make the Index in a DataFrame into columns in a while still keeping the index?

Currently I do the following and am wondering if this is the best I can do:

df.reset_index().set_index(df.index.names, drop=False)
@jreback
Copy link
Contributor

jreback commented Jan 30, 2014

In [16]: df = DataFrame(np.random.randn(5,2),columns=['A','B'],index=date_range('20130101',periods=5))

In [17]: df
Out[17]: 
                   A         B
2013-01-01 -0.075832 -0.571500
2013-01-02 -0.484581 -0.208359
2013-01-03 -0.579949  2.218587
2013-01-04 -0.636561 -0.741129
2013-01-05  0.629130  0.693871

[5 rows x 2 columns]

In [18]: df['the_index'] = df.index

In [19]: df
Out[19]: 
                   A         B  the_index
2013-01-01 -0.075832 -0.571500 2013-01-01
2013-01-02 -0.484581 -0.208359 2013-01-02
2013-01-03 -0.579949  2.218587 2013-01-03
2013-01-04 -0.636561 -0.741129 2013-01-04
2013-01-05  0.629130  0.693871 2013-01-05

[5 rows x 3 columns]

@jreback jreback closed this as completed Jan 30, 2014
@cancan101
Copy link
Contributor Author

@jreback What about multi indexes?

@cancan101
Copy link
Contributor Author

Also strictly speaking the answer you proposed would be:

df2=df.copy()
df2['the_index'] = df2.index

@jreback
Copy link
Contributor

jreback commented Jan 30, 2014

@cancan101 you said Index. !

@cancan101
Copy link
Contributor Author

That is true. The reason I used names was for a general purpose solution.

All that being said, what is the best bet for a multi index?

Also df.reset_index().set_index(df.index.names, drop=False) isn't quite right if the name if the Index is None

@jreback
Copy link
Contributor

jreback commented Jan 30, 2014

In [55]: df2 = df.reset_index()

In [56]: df2.index = df.index

In [57]: df2
Out[57]: 
             level_0    level_1         A         B
a 2013-01-01       a 2013-01-01 -0.592502  0.851388
  2013-01-02       a 2013-01-02 -1.358005  0.118389
  2013-01-03       a 2013-01-03 -1.835907  0.284208
b 2013-01-01       b 2013-01-01 -0.009812  0.421922
  2013-01-02       b 2013-01-02  0.662348  0.312630
  2013-01-03       b 2013-01-03  1.368136  0.859343

[6 rows x 4 columns]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants