Friday, December 27, 2024
Google search engine
HomeLanguagesCreate a pandas column using for loop

Create a pandas column using for loop

Let’s see how to create a column in pandas dataframe using for loop. Such operation is needed sometimes when we need to process the data of dataframe created earlier for that purpose, we need this type of computation so we can process the existing data and make a separate column to store the data.

It can be easily done by for-loop. The data of column can be taken from the existing Dataframe or any of the array.




# importing libraries
import pandas as pd
import numpy as np
  
raw_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(raw_Data, columns = ['Voter_name', 'Voter_age'])
#       //DataFrame will look like
#
# Voter_name          Voter_age
# Geek1                15
# Geek2                23
# Geek3                25
# Geek4                09
# Geek5                67
# Geek6                54
# Geek7                42
# Geek8           not a number
  
eligible = []
  
# For each row in the column
for age in df['Voter_age']:       
    if age >= 18:                   # if Voter eligible
        eligible.append('Yes')
    elif age < 18:                  # if voter is not eligible
        eligible.append("No")
    else:
        eligible.append("Not Sure")
  
# Create a column from the list
df['Voter'] = eligible  
            
print(df)


Output:

    Voter_name  Voter_age     Voter
0      Geek1         15        No
1      Geek2         23       Yes
2      Geek3         25       Yes
3      Geek4          9        No
4      Geek5         67       Yes
5      Geek6         54       Yes
6      Geek7         42       Yes
7      Geek8        NaN  Not Sure
RELATED ARTICLES

Most Popular

Recent Comments