The Wayback Machine - https://web.archive.org/web/20241126210837/https://www.geeksforgeeks.org/create-a-pandas-column-using-for-loop/
Open In App

Create a pandas column using for loop

Last Updated : 14 Jan, 2019
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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


Previous Article
Next Article

Similar Reads

Create a column using for loop in Pandas Dataframe
Adding a new column in an already created dataframe is quite easy. Adding a new column is actually required to process the data of dataframe created earlier. For that purpose, we can process the existing data and make a separate column to store the data. The simplest way to add a new column along with data is by creating a new column and assigning
3 min read
Create a Pandas DataFrame from a Numpy array and specify the index column and column headers
This article demonstrates multiple examples to convert the Numpy arrays into Pandas Dataframe and to specify the index column and column headers for the data frame. Example 1: In this example, the Pandas dataframe will be generated and proper names of index column and column headers are mentioned in the function. This approach can be used when ther
4 min read
Python - Scaling numbers column by column with Pandas
Scaling numbers in machine learning is a common pre-processing technique to standardize the independent features present in the data in a fixed range. When applied to a Python sequence, such as a Pandas Series, scaling results in a new sequence such that your entire values in a column comes under a range. For example if the range is ( 0 ,1 ) your e
3 min read
Get column index from column name of a given Pandas DataFrame
Let's learn how to get the index of a column based on its name using the DataFrame.columns attribute and Index.get_loc() method from the pandas library. Index.get_loc() Method Index.get_loc() function finds the index of a specified column name and returns an integer if the column name is unique. Syntax: Index.get_loc(key, method=None, tolerance=Non
2 min read
Create a DataFrame from a Numpy array and specify the index column and column headers
Let us see how to create a DataFrame from a Numpy array. We will also learn how to specify the index and the column headers of the DataFrame. Approach : Import the Pandas and Numpy modules. Create a Numpy array. Create list of index values and column values for the DataFrame. Create the DataFrame. Display the DataFrame. Example 1 : # importiong the
2 min read
Difference between for loop and while loop in Python
In this article, we will learn about the difference between for loop and a while loop in Python. In Python, there are two types of loops available which are 'for loop' and 'while loop'. The loop is a set of statements that are used to execute a set of statements more than one time. For example, if we want to print "Hello world" 100 times then we ha
4 min read
Create a new column in Pandas DataFrame based on the existing columns
While working with data in Pandas, we perform a vast array of operations on the data to get the data in the desired form. One of these operations could be that we want to create new columns in the DataFrame based on the result of some operations on the existing columns in the DataFrame. Let's discuss several ways in which we can do that. Given a Da
4 min read
Pandas DataFrame hist() Method | Create Histogram in Pandas
A histogram is a graphical representation of the numerical data. Sometimes you'll want to share data insights with someone, and using graphical representations has become the industry standard. Pandas.DataFrame.hist() function plots the histogram of a given Data frame. It is useful in understanding the distribution of numeric variables. This functi
4 min read
Add a new column in Pandas Data Frame Using a Dictionary
Pandas is basically the library in Python used for Data Analysis and Manipulation. To add a new Column in the data frame we have a variety of methods. But here in this post, we are discussing adding a new column by using the dictionary. Let's take Example! # Python program to illustrate # Add a new column in Pandas # Importing the pandas Library im
2 min read
How to extract Time data from an Excel file column using Pandas?
Prerequisite: Regular Expressions in Python In these articles, we will discuss how to extract Time data from an Excel file column using Pandas. Suppose our Excel file looks like below given image then we have to extract the Time from the Excel sheet column and store it into a new Dataframe column. For viewing the Excel file Click Here. Approach: Im
2 min read
Extract date from a specified column of a given Pandas DataFrame using Regex
In this article, we will discuss how to extract only valid date from a specified column of a given Data Frame. The extracted date from the specified column should be in the form of 'mm-dd-yyyy'. Approach: In this article, we have used a regular expression to extract valid date from the specified column of the data frame. Here we used \b(1[0-2]|0[1-
2 min read
How to extract Email column from Excel file and find out the type of mail using Pandas?
In this article, Let's see how to Extract Email column from an Excel file and find out the type of mail using Pandas. Suppose our Excel file looks like below given image, and then we have to store different type of emails in different columns of Dataframe. For viewing the Excel file Click Here Approach: Import required module.Import data from Excel
3 min read
Find the sum and maximum value of the two column in excel file using Pandas
In these articles, we will discuss how to read data from excel and perform some mathematical operation and store it into a new column in DataFrame. Suppose our excel file looks like this. Then we have to compute the sum of two-column and find out the maximum value and store into a new DataFrame column. Approach : Import Pandas module.Read data from
2 min read
How to merge two csv files by specific column using Pandas in Python?
In this article, we are going to discuss how to merge two CSV files there is a function in pandas library pandas.merge(). Merging means nothing but combining two datasets together into one based on common attributes or column. Syntax: pandas.merge() Parameters : data1, data2: Dataframes used for merging.how: {‘left’, ‘right’, ‘outer’, ‘inner’}, def
3 min read
How to do Fuzzy Matching on Pandas Dataframe Column Using Python?
Prerequisite: FuzzyWuzzy In this tutorial, we will learn how to do fuzzy matching on the pandas DataFrame column using Python. Fuzzy matching is a process that lets us identify the matches which are not exact but find a given pattern in our target item. Fuzzy matching is the basis of search engines. That is why we get many recommendations or sugges
9 min read
How to import excel file and find a specific column using Pandas?
To read specific columns from an Excel file in Pandas, you have the flexibility to use either column indices or letters. This is achieved by setting the usecols argument, which can take a comma-separated string or a list containing column identifying letters or indices. In this article, we will learn how to import an Excel file into a data frame an
5 min read
How to Name the Column When Using value_counts Function in Pandas?
In Pandas, when using the value_counts function, it's important to name the resulting column for clear data interpretation. This process involves using Pandas' functionality to assign meaningful names to the frequency count column, ensuring easier analysis and understanding of the data. In this article, we will explore three different methods/appro
6 min read
Python Program for Column to Row Transpose using Pandas
Given an Input File, having columns Dept and Name, perform an operation to convert the column values to rows. Name contains pipe separated values that belong to a particular department identified by the column Dept. Attached Dataset: emp_data Examples: Input: dept, name 10, Vivek|John 20, Ritika|Shubham|Nitin 30, Vishakha|Ankit Output: dept, name 1
2 min read
Loop or Iterate over all or certain columns of a dataframe in Python-Pandas
Pandas DataFrames facilitate column-wise iteration, allowing convenient access to elements in each column. In this article, we will discuss how to loop or Iterate overall or certain columns of a DataFrame. Creating Pandas DataframeIn this article, we will use this Dataframe that we have created by using the Pandas package. C/C++ Code # import panda
5 min read
How to add column sum as new column in PySpark dataframe ?
In this article, we are going to see how to perform the addition of New columns in Pyspark dataframe by various methods. It means that we want to create a new column that will contain the sum of all values present in the given row. Now let's discuss the various methods how we add sum as new columns But first, let's create Dataframe for Demonstratio
4 min read
Get Column name and Column type with Python psycopg2
When working with PostgreSQL databases in Python, one common task is to retrieve metadata about database tables, such as column names and their types. This information can be crucial for dynamically generating queries, validating data, or understanding the structure of our database. The psycopg2 library provides a powerful way to interact with Post
4 min read
Change column names and row indexes in Pandas DataFrame
Given a Pandas DataFrame, let's see how to change its column names and row indexes. About Pandas DataFramePandas DataFrame are rectangular grids which are used to store data. It is easy to visualize and work with data when stored in dataFrame. It consists of rows and columns.Each row is a measurement of some instance while column is a vector which
4 min read
Apply uppercase to a column in Pandas dataframe
Analyzing a real world data is some what difficult because we need to take various things into consideration. Apart from getting the useful data from large datasets, keeping data in required format is also very important. One might encounter a situation where we need to uppercase each letter in any specific column in given dataframe. Let's see how
2 min read
How to lowercase strings in a column in Pandas dataframe
Analyzing real-world data is somewhat difficult because we need to take various things into consideration. Apart from getting the useful data from large datasets, keeping data in required format is also very important. One might encounter a situation where we need to lowercase each letter in any specific column in given dataframe. Let's see how to
2 min read
Convert a column to row name/index in Pandas
Pandas provide a convenient way to handle data and its transformation. Let's see how can we convert a column to row name/index in Pandas. Create a dataframe first with dict of lists. C/C++ Code # importing pandas as pd import pandas as pd # Creating a dict of lists data = {'Name':["Akash", "Geeku", "Pankaj", "Sumi
2 min read
Get n-smallest values from a particular column in Pandas DataFrame
Pandas DataFrame is two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). Let's see how can we can get n-smallest values from a particular column in Pandas DataFrame. Observe this dataset first. We'll use 'Age', 'Weight' and 'Salary' columns of this data in order to get n-smallest value
1 min read
Get n-largest values from a particular column in Pandas DataFrame
Pandas DataFrame is two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). Let's see how can we can get n-largest values from a particular column in Pandas DataFrame. Observe this dataset first. We’ll use ‘Age’, ‘Weight’ and ‘Salary’ columns of this data in order to get n-largest values
1 min read
Split a text column into two columns in Pandas DataFrame
Let's see how to split a text column into two columns in Pandas DataFrame. Method #1 : Using Series.str.split() functions. Split Name column into two different columns. By default splitting is done on the basis of single space by str.split() function. # import Pandas as pd import pandas as pd # create a new data frame df = pd.DataFrame({'Name': ['J
3 min read
Join two text columns into a single column in Pandas
Let's see the different methods to join two text columns into a single column. Method #1: Using cat() function We can also use different separators during join. e.g. -, _, " " etc. # importing pandas import pandas as pd df = pd.DataFrame({'Last': ['Gaitonde', 'Singh', 'Mathur'], 'First': ['Ganesh', 'Sartaj', 'Anjali']}) print('Before Join') print(d
1 min read
Getting Unique values from a column in Pandas dataframe
Let's see how can we retrieve the unique values from pandas dataframe. Let's create a dataframe from CSV file. We are using the past data of GDP from different countries. You can get the dataset from here. # import pandas as pd import pandas as pd gapminder_csv_url ='http://bit.ly/2cLzoxH' # load the data with pd.read_csv record = pd.read_csv(gapmi
2 min read
three90RightbarBannerImg