Skip to content
Related Articles

Related Articles

Improve Article

Create a column using for loop in Pandas Dataframe

  • Last Updated : 08 Jan, 2019
Geek Week

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.




# 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)
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

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course

My Personal Notes arrow_drop_up
Recommended Articles
Page :