Create a column using for loop in Pandas Dataframe

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.

In this type of computation, we need to take care about the value that is in the existing dataframe. We only use those value to add new column in dataframe.

filter_none

edit
close

play_arrow

link
brightness_4
code

# importing pandas
import pandas as pd
  
# Creating new dataframe
initial_data = {'First_name': ['Ram', 'Mohan', 'Tina', 'Jeetu', 'Meera'], 
                'Last_name': ['Kumar', 'Sharma', 'Ali', 'Gandhi', 'Kumari'], 
                'Marks': [12, 52, 36, 85, 23] }
  
df = pd.DataFrame(initial_data, columns = ['First_name', 'Last_name', 'Marks'])
  
# Generate result using pandas
result = []
for value in df["Marks"]:
    if value >= 33:
        result.append("Pass")
    elif value < 0 and value > 100:
        result.append("Invalid")
    else:
        result.append("Fail")
       
df["Result"] = result   
print(df)

chevron_right


Output:

  First_name Last_name  Marks Result
0        Ram     Kumar     12   Fail
1      Mohan    Sharma     52   Pass
2       Tina       Ali     36   Pass
3      Jeetu    Gandhi     85   Pass
4      Meera    Kumari     23   Fail


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.