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
1
  • @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 stackoverflow.com/q/20461165/5142797. Commented Oct 21, 2015 at 14:55

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

Comments

1

Just:

df['index'] = df.index

where df is your dataframe.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.