Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fill a new pandas column with row numbers

Tags:

python

pandas

I have the following DataFrame data with random index values:

      A   B 100   0   7 203   5   4 5992  0  10 2003  9   8 20   10   5 12    6   2 

I would like to add a new column 'C' with row numbers. For example:

      A   B   C 100   0   7   0 203   5   4   1 5992  0  10   2 2003  9   8   3 20   10   5   4 12    6   2   5 
like image 951
michael0196 Avatar asked Mar 30 '18 12:03

michael0196


People also ask

How create new column in Pandas fill with value?

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, ...])

How do I add row numbers in Pandas?

Generate row number in pandas using index() function In order to generate the row number in pandas we can also use index() function. dataframe. index() function generates the row number.

How do I fill empty columns in Pandas?

Fill Data in an Empty Pandas DataFrame by Appending Rows First, create an empty DataFrame with column names and then append rows one by one. The append() method can also append rows. When creating an empty DataFrame with column names and row indices, we can fill data in rows using the loc() method.


2 Answers

Use numpy.arange by length of DataFrame:

df['C'] = np.arange(len(df)) 

Or you can use DataFrame.shape, thank you @Mehmet Burak Sayıcı:

df['C'] = np.arange(df.shape[0]) 

print (df)        A   B  C 100    0   7  0 203    5   4  1 5992   0  10  2 2003   9   8  3 20    10   5  4 12     6   2  5 
like image 199
jezrael Avatar answered Oct 21 '22 16:10

jezrael


By using reset_index

df['C'] = df.reset_index().index df         A   B  C 100    0   7  0 203    5   4  1 5992   0  10  2 2003   9   8  3 20    10   5  4 12     6   2  5 

To generalise:

df['C'] = df.index if df.index.is_monotonic_increasing else range(len(df)) df         A   B  C 100    0   7  0 203    5   4  1 5992   0  10  2 2003   9   8  3 20    10   5  4 12     6   2  5 
like image 37
BENY Avatar answered Oct 21 '22 16:10

BENY