Pandas: Create a DataFrame using a for loop

31 July 2020

Code

During DataFrame creation, a custom function is called within a for loop to generate values for the rows.

# Import library
import pandas as pd
import random 
import string

# Function - 1: Square a number
def sq(m):
    return m**2

# Function - 2: Create a random key
def rand(nkey):
    rl = string.ascii_letters # random alphabet
    rd = string.digits # random digit
    return ''.join(random.choices(rl + rd, k=nkey))

# List
x = [1,2,3,4,5]
nkey = 15 # key length

# Create DataFrame using for loop and functions
df = pd.DataFrame({
    'num': x,
    'num_sq': [i**2 for i in x],
    'num_sq_func': [sq(i) for i in x],
    'random_key': [rand(nkey) for _ in range(len(x))]
    
})

# Output
print(df)

Output

   num  num_sq  num_sq_func       random_key
0    1       1            1  c4eZo4euSCLZ0EM
1    2       4            4  YWV1jbHlDPeRvt1
2    3       9            9  wyrOIZK6wTYCZRQ
3    4      16           16  42UpW1b4GslxRFe
4    5      25           25  uVVNI87BS1ddzl9






Any errors in code above?
Please send a message.