Create a Pandas Column using For Loop
In Pandas you can create a new column by iterating over an existing column (a Series) with a for loop, collecting computed values into a Python list and assigning that list back to the DataFrame as a new column.
For Example: This example creates a new column that doubles the numbers in another column.
import pandas as pd
data = {'Number': [1, 2, 3]}
df = pd.DataFrame(data)
doubles = []
for n in df['Number']:
    doubles.append(n * 2)
df['Double'] = doubles
print(df)
Output
Number Double 0 1 2 1 2 4 2 3 6
Explanation:
- labels is created to store results.
 - Each value in column "Number" is checked using %.
 - "Even" or "Odd" is appended to the list.
 - A new column "Label" is created from that list.
 
Let's see more examples to understand it better.
More Examples
Example 1: This example checks each voter’s age and creates a new column "Voter" showing whether the person is eligible to vote.
import pandas as pd
import numpy as np
data = {'Voter_name': ['Geek1', 'Geek2', 'Geek3', 'Geek4', 'Geek5', 'Geek6', 'Geek7', 'Geek8'], 
        'Voter_age': [15, 23, 25, 9, 67, 54, 42, np.nan]}
df = pd.DataFrame(data)
status = []
for age in df['Voter_age']:
    if age >= 18:
        status.append("Yes")
    elif age < 18:
        status.append("No")
    else:
        status.append("Not Sure")
df['Voter'] = status
print(df)
Output
Voter_name Voter_age Voter
0 Geek1 15.0 No
1 Geek2 23.0 Yes
2 Geek3 25.0 Yes
3 Geek4 9.0 No
4 Geek5 67.0 Yes
5 Geek6 54.0 Yes
6 Geek7 42.0 Yes
7 Geek8 NaN Not Sure
Explanation:
- If age ≥ 18 -> "Yes".
 - If age < 18 -> "No".
 - If age is NaN -> "Not Sure".
 - A new "Voter" column is created with results.
 
Example 2: In this example, we classify salaries into "High" or "Low" categories and store them in a new column.
import pandas as pd
data = {'Employee': ['A', 'B', 'C', 'D'], 'Salary': [25000, 60000, 40000, 80000]}
df = pd.DataFrame(data)
category = []
for s in df['Salary']:
    if s >= 50000:
        category.append("High")
    else:
        category.append("Low")
df['Category'] = category
print(df)
Output
Employee Salary Category 0 A 25000 Low 1 B 60000 High 2 C 40000 Low 3 D 80000 High
Explanation:
- Salaries ≥ 50,000 are labeled "High".
 - Others are labeled "Low".
 - New column "Category" stores these labels.