Apply returned value from function in all Dataframe rows

Viewed 42

I am trying to assign a value from a function in all rows of a Dataframe in a new column. i.e. the df below should contain new column called random number with the random number generated in the get_random() function.

import pandas as pd
from random import random

def get_random():
    return random()

d = {'col1': [1, 2], 'col2': [3, 4]}
df = pd.DataFrame(data=d)

I tried the below, but I get the error get_random takes 0 positional arguments

df['random number'] = df.apply(get_random)
3 Answers

You can either do

df['random number'] = df.apply(lambda x: random())

or change get_random to

def get_random(x):
    return random()

Just change the function random:

def get_random(x):
    return random()

as apply expects the function to take an input.

You can use list-comprehension

df['random number'] = [get_random() for i in range(len(df))]
Related