[英]Apply returned value from function in all Dataframe rows
I am trying to assign a value from a function in all rows of a Dataframe in a new column.我正在尝试从新列中 Dataframe 的所有行中的函数分配一个值。 ie the df below should contain new column called
random number
with the random number generated in the get_random()
function.即下面的 df 应包含称为
random number
新列,其中包含在get_random()
函数中生成的随机数。
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
我尝试了下面的方法,但出现错误
get_random takes 0 positional arguments
df['random number'] = df.apply(get_random)
You can either do你可以这样做
df['random number'] = df.apply(lambda x: random())
or change get_random to或将 get_random 更改为
def get_random(x):
return random()
Just change the function random
:只需更改函数
random
:
def get_random(x):
return random()
as apply expects the function to take an input.因为 apply 期望函数接受输入。
您可以使用列表理解
df['random number'] = [get_random() for i in range(len(df))]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.