In this article, we will discuss different ways to add a new column in DataFrame with incremental values or numbers.
Table Of Contents
Preparing DataSet
First we will create a DataFrame from list of tuples i.e.
import pandas as pd # List of Tuples employees= [('Mark', 'US', 'Tech', 5), ('Riti', 'India', 'Tech' , 7), ('Shanky', 'India', 'PMO' , 2), ('Shreya', 'India', 'Design' , 2), ('Aadi', 'US', 'Tech', 11), ('Sim', 'US', 'Tech', 4)] # Create a DataFrame object from list of tuples df = pd.DataFrame(employees, columns=['Name', 'Location', 'Team', 'Experience']) print(df)
Output:
Name Location Team Experience 0 Mark US Tech 5 1 Riti India Tech 7 2 Shanky India PMO 2 3 Shreya India Design 2 4 Aadi US Tech 11 5 Sim US Tech 4
Now, suppose we want to add a new column in this DataFrame ‘Age’, and this column should contain incremental values like 31, 32, 33, 34, 35 etc. Let’s see how to do that.
Add new column with incremental values in Pandas DataFrame
We can call the range() function of Python, to give a range of numbers from start
till end
. Like, start will be 30 in our case, and end will be 30 + N. Where, N is the number of rows in the DataFrame. So, it will return a sequence of numbers from 31 till 31 + N. Then we can add this squence as a new column in the DataFrame. Let’s see an example,
start = 30 # Add column with incremental values from 30 onwards df['Age'] = range(start, start + df.shape[0]) print(df)
Output:
Frequently Asked:
Name Location Team Experience Age 0 Mark US Tech 5 30 1 Riti India Tech 7 31 2 Shanky India PMO 2 32 3 Shreya India Design 2 33 4 Aadi US Tech 11 34 5 Sim US Tech 4 35
Here, we added a new column ‘Age’ in the DataFrame with incremental values.
Add new DataFrame column with incremental values of equal interval
Suppose we want to a add a new column containing incremental values. But the adjacent values should separated by a given step size. We can do that using the range() function. Let’s see the example,
# Add column with incremental values from 30 onwards # with step size 5 df['Age'] = range(start, start + (5 * df.shape[0]), 5) print(df)
Output:
Name Location Team Experience Age 0 Mark US Tech 5 30 1 Riti India Tech 7 35 2 Shanky India PMO 2 40 3 Shreya India Design 2 45 4 Aadi US Tech 11 50 5 Sim US Tech 4 55
Here, we added a new column ‘Age’ in the DataFrame with incremental values, but each value in this column is greater than previous value by 5.
Summary
Today, we saw how to add a new column in DataFrame with incremental values. Thanks.