1

How do you write an index of a dataframe to itself?

For Example:

      50       51
   0  326.32   193.1
   1  324.2    192.1
   2  234.2    0
   3  302.1    23

I would like to write a column named index with the index values to the df:

      index     50       51
   0  0         326.32   193.1
   1  1         324.2    192.1
   2  2         234.2    0
   3  3         302.1    23
Techno04335
  • 1,365
  • 6
  • 22
  • 43
  • @Techno04335 You should clarify if you want to keep the original index or reset the index. In your example that would not make any difference. However, if the aim is to keep it than the question is not a duplicate of http://stackoverflow.com/q/20461165/5142797. – Fabian Rost Oct 21 '15 at 14:55

3 Answers3

1

using df.index

In [94]: df['index'] = df.index

In [95]: df
Out[95]:
       50     51  index
0  326.32  193.1      0
1  324.20  192.1      1
2  234.20    0.0      2
3  302.10   23.0      3
Zero
  • 74,117
  • 18
  • 147
  • 154
1

Just:

df['index'] = df.index

where df is your dataframe.

Fabio Lamanna
  • 20,504
  • 24
  • 90
  • 122
0

Another way is to use df.reset_index(). But this also resets your index (which is important if your original index was not just 0, 1, 2, 3...)

http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html

Fabian Rost
  • 2,284
  • 2
  • 15
  • 27