Change language

Create pandas column using for loop

This can be done easily with a for loop. Column data can be taken from an existing Dataframe or any 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 is not a number

 

eligible = []

 
# For each line in the column

for age in df [ ’Voter_age’ ]: 

if age" = 18 # if the voter has the right

eligible.append ( ’Yes’ )

elif age & lt;  18 # if the voter has no right

eligible.append ( "No" )

else :

  eligible.append ( " Not Sure " )

  
# Create column from list

df [ ’Voter’ ] = eligible 

 

print (df)

Exit:

 
 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 

Shop

Gifts for programmers

Learn programming in R: courses

$FREE
Gifts for programmers

Best Python online courses for 2022

$FREE
Gifts for programmers

Best laptop for Fortnite

$399+
Gifts for programmers

Best laptop for Excel

$
Gifts for programmers

Best laptop for Solidworks

$399+
Gifts for programmers

Best laptop for Roblox

$399+
Gifts for programmers

Best computer for crypto mining

$499+
Gifts for programmers

Best laptop for Sims 4

$

Latest questions

PythonStackOverflow

Common xlabel/ylabel for matplotlib subplots

1947 answers

PythonStackOverflow

Check if one list is a subset of another in Python

1173 answers

PythonStackOverflow

How to specify multiple return types using type-hints

1002 answers

PythonStackOverflow

Printing words vertically in Python

909 answers

PythonStackOverflow

Python Extract words from a given string

798 answers

PythonStackOverflow

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

606 answers

PythonStackOverflow

Python os.path.join () method

384 answers

PythonStackOverflow

Flake8: Ignore specific warning for entire file

360 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

How to specify multiple return types using type-hints

Printing words vertically in Python

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically