简体   繁体   English

在所有 Dataframe 行中应用函数的返回值

[英]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.

相关问题 将函数应用于pandas Dataframe,其返回值基于其他行 - apply a function to a pandas Dataframe whose returned value is based on other rows 如何在 DataFrame 的所有行上应用函数 - How to apply a function on all rows of a DataFrame 将 function 应用于 pandas dataframe (lambda) 中的所有行 - Apply function to all rows in pandas dataframe (lambda) 将用户定义的 function 应用于 python dataframe 中特定列的所有行 - Apply a user defined function to all rows of a specific column in python dataframe 根据其他列中的值,在列中 dataframe 行的子集上应用 function - apply function on subset of dataframe rows in column based on value in other column 根据值从 dataframe 中删除所有行 - Drop all rows from a dataframe based on value 是否可以在 pyspark dataframe 的每 60 行上应用 function? 就像找到每 60 行的最大值和最小值 - Is it possible to apply a function on every 60 rows in a pyspark dataframe? Like finding the max and min value of every 60 rows 当Apply方法返回多行时,Pandas Store DataFrame - Pandas Store DataFrame when multiple rows are returned by Apply method 将 function 应用于每一行,其中 function 使用 DataFrame 的所有先前行 - Apply a function to each row, where the function uses all previous rows of the DataFrame Using a column from a dataframe in a new function, and then attaching the returned value from that function to the dataframe - Using a column from a dataframe in a new function, and then attaching the returned value from that function to the dataframe
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM