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

标签 python pandas

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

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/

相关文章:

Python读取csv文件,并跳过非固定长度的 header 部分

python - 从 python 2.7.3 升级到 2.7.9 后,停止 ConfigParser 向 delims 添加空格

python - 每次pandas数据框中出现NaN时如何重置累积和?

python - 如何通过python在选定的Gmail邮箱中存档电子邮件

python - 如何在通用级别 l 上对 pandas.MultiIndex 进行切片?

python - 如何使 pandas dataframe str.contains 搜索更快

python - 使用 Oracle 的 AWS Python Lambda - OID 生成失败

python - Python:file.readline在行尾添加一个空格

python - Pandas DataFrame 在列中每次出现后计算每个元素的出现次数

python - Pandas/Python - 使用 stack() groupby() 和 apply() 的性能非常慢