Contents

How to Add New Column with Incremental Number in pandas DataFrame

You can add incremental numbers to a new column in a pandas DataFrame by using various functions such as range(), insert(), and arange() functions.

Method 1: range() function

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

Method 2: insert() function

df.insert(0, 'new_col', range(1, 1 + len(df)))

Method 3: arange() function

df['new_col'] = np.arange(1, len(df) + 1)

The following examples demonstrate how to use range(), insert(), and arange() functions to add incremental numbers to a new column in a Pandas DataFrame

Example 1: Add incremental numbers using range() function

Create a sample pandas DataFrame function,

# import package
import pandas as pd

df =  pd.DataFrame({'Name': ['A', 'B', 'C', 'D', 'E']})

df

  Name
0    A
1    B
2    C
3    D
4    E

Now, add new column (new_col) with incremental numbers to df using range() function,

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

df

  Name  new_col
0    A        1
1    B        2
2    C        3
3    D        4
4    E        5

Example 2: Add incremental numbers using insert() function

Create a sample pandas DataFrame function,

# import package
import pandas as pd

df =  pd.DataFrame({'Name': ['A', 'B', 'C', 'D', 'E']})

df

  Name
0    A
1    B
2    C
3    D
4    E

Now, add new column (new_col) with incremental numbers to df using insert() function,

df.insert(1, 'new_col', range(1, 1 + len(df)))

df

  Name  new_col
0    A        1
1    B        2
2    C        3
3    D        4
4    E        5

In the above example, the number 1 at the first argument indicates the position of the column in the pandas DataFrame.

Example 3: Add incremental numbers using NumPy arange() function

Create a sample pandas DataFrame function,

# import package
import pandas as pd

df =  pd.DataFrame({'Name': ['A', 'B', 'C', 'D', 'E']})

df

  Name
0    A
1    B
2    C
3    D
4    E

Now, add new column (new_col) with incremental numbers to df using NumPy arange() function,

# import package
import numpy as np

df['new_col'] = np.arange(1, len(df) + 1)

df

  Name  new_col
0    A        1
1    B        2
2    C        3
3    D        4
4    E        5

Example 4: Add incremental numbers starting from a specific value

Alternatively, you can also use NumPy arange() function to add incremental numbers starting from a a specific number.

Create a sample pandas DataFrame function,

# import package
import pandas as pd

df =  pd.DataFrame({'Name': ['A', 'B', 'C', 'D', 'E']})

df

  Name
0    A
1    B
2    C
3    D
4    E

Now, add new column (new_col) with incremental numbers starting from 10 to df using NumPy arange() function,

# import package
import numpy as np

df['new_col'] = np.arange(10, len(df) + 10)

df

  Name  new_col
0    A       10
1    B       11
2    C       12
3    D       13
4    E       14