gpt4 book ai didi

Python Pandas 应用,将字典作为参数传递

转载 作者:行者123 更新时间:2023-12-04 14:34:46 28 4
gpt4 key购买 nike

我想将字典作为附加参数传递给函数。该函数将应用于数据帧的每一行。所以我使用“申请”。下面我有一个我尝试的小例子:

import pandas as pd
import numpy as np

def fun(df_row, dict1):
return df_row['A']*2*max(dict1['x'])

df = pd.DataFrame(np.random.randn(6,2),columns=list('AB'))
dict_test = {'x': [1,2,3,4], 'y': [5,6,7,8]}
df['D'] = df.apply(fun, args = (dict_test), axis = 1)

我收到以下错误消息:
('fun() 只需要 1 个参数 (3 given)', u'occurred at index 0')
我使用 **dict1 来表示函数 'fun' 中的键值对

奇怪的是,如果我通过两次争论,事情就会很好
def fun(df_row, dict1, dict2):
return df_row['A']*2*max(dict1['x'])

df = pd.DataFrame(np.random.randn(6,2),columns=list('AB'))
dict_test = {'x': [1,2,3,4], 'y': [5,6,7,8]}
df['D'] = df.apply(fun, axis = 1, args = (dict_test, dict_test))

最佳答案

问题是你没有传递元组,(dict_test)不是元组,它和 dict_test 一样.你想要一个带有 dict_test 的元组作为唯一的元素,即 (dict_test,) .

df['D'] = df.apply(fun, args=(dict_test,), axis=1)

关于Python Pandas 应用,将字典作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36228977/

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