indexing – Pandas (python): How to add column to dataframe for index?

indexing – Pandas (python): How to add column to dataframe for index?

How about:

df[new_col] = range(1, len(df) + 1)

Alternatively if you want the index to be the ranks and store the original index as a column:

df = df.reset_index()

I stumbled on this question while trying to do the same thing (I think). Here is how I did it:

df[index_col] = df.index

You can then sort on the new index column, if you like.

indexing – Pandas (python): How to add column to dataframe for index?

How about this:

from pandas import *

idx = Int64Index([171, 174, 173])
df = DataFrame(index = idx, data =([1,2,3]))
print df

It gives me:

     0
171  1
174  2
173  3

Is this what you are looking for?

Leave a Reply

Your email address will not be published. Required fields are marked *