gpt4 book ai didi

python - 当只有一些变量需要多个值时,如何将多个值传递给函数 - python 3

转载 作者:太空宇宙 更新时间:2023-11-04 00:22:04 24 4
gpt4 key购买 nike

我正在尝试创建一个函数,该函数将根据其他列的条件创建一个新列。当我只传递一个变量时,该函数工作正常,但当需要两个时,它就不起作用了。我正在尝试做的一个示例是:

### create a function called name

def name(ID, NAME):
if (ID == 1 ):
return "First"
elif (ID == 2):
return "Second"
elif (ID == 3):
return "Third"
elif (ID == 4 and NAME = “Four” ):
return "Fourth"

### apply function to dataset and view results

dataset["NAME"].apply(name).head(100)

我的大多数新列值都可以通过只查看一个变量来获得,但少数需要两个。任何人都可以提供有关如何在 python 中完成此操作的指导吗?在 R 中,我在 dplyr 中使用了 case_when 函数,但我似乎没有发现 python 支持 case 语句

最佳答案

您可以将数据帧的整行传递给 apply 中带有 axis=1 参数的函数,然后您可以像这样访问函数中的部分行:

import pandas as pd
import numpy as np

def nameme(row):
if (row.ID == 1 ):
return "First"
elif (row.ID == 2):
return "Second"
elif (row.ID == 3):
return "Third"
elif (row.ID == 4 and row.Name == 'Four' ):
return "Fourth"


dataset = pd.DataFrame({'ID':[0,1,2,3,4,5],'Name':['Four']*6})

dataset.apply(nameme, axis=1)

输出:

0      None
1 First
2 Second
3 Third
4 Fourth
5 None
dtype: object

关于python - 当只有一些变量需要多个值时,如何将多个值传递给函数 - python 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48773437/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com