Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

The index that I have in the dataframe (with 30 rows) is of the form:

Int64Index([171, 174,173, 172, 199..............         ....175, 200]) 

The index is not strictly increasing because the data frame is the output of a sort(). I want to have add a column which is the series:

[1, 2, 3, 4, 5......................., 30] 

How should I go about doing that?

like image 234
Navneet Avatar asked Aug 28 '12 22:08

Navneet


People also ask

How do I add a column to a DataFrame matching index?

Using the pandas. DataFrame. assign() method, you can insert multiple columns in a DataFrame, ignoring the index of a column to be added, or modify the values of existing columns. The method returns a new DataFrame object with all of the original columns as well as the additional(newly added) ones.

How do I add an index to a DataFrame?

DataFrame - set_index() function The set_index() function is used to set the DataFrame index using existing columns. Set the DataFrame index (row labels) using one or more existing columns or arrays of the correct length. The index can replace the existing index or expand on it.

How do I add a column to a DataFrame in Python?

You can use the assign() function to add a new column to the end of a pandas DataFrame: df = df. assign(col_name=[value1, value2, value3, ...])


1 Answers

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() 
like image 127
Chang She Avatar answered Sep 22 '22 02:09

Chang She