简体   繁体   English

将其他参数传递给python pandas DataFrame适用

[英]Passing additional arguments to python pandas DataFrame apply

I have a DataFrame df and I tried to iterate each row to map values of two columns to new values, but I have problems passing in the dictionary containing the map to df.apply 我有一个DataFrame df,我尝试遍历每一行以将两列的值映射到新值,但是在将包含映射的字典传递给df.apply时遇到了问题

df.apply(lambda row: (map_dict[row['colA']], map_dict[row['colB']]), axis=1, args=(map_dict,), map_dict=map_dict)

I got the error message 我收到错误消息

File "<console>", line 1
SyntaxError: Generator expression must be parenthesized if not sole argument

I tried to read the official doc , but I struggle to understand its explanation on args parameter http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html 我试图阅读官方文档,但是我很难理解它对args参数的解释http://pandas.pydata.org/pandas-docs/stable/genic/pandas.DataFrame.apply.html

I have also tried passing in map_dict as either keyword or positional argument, but I still get the same error 我也尝试过将map_dict作为关键字或位置参数传递,但是我仍然遇到相同的错误

The args argument given to apply function is passed func argument (lambda function given). 赋予apply函数的args参数传递了func参数(给定的lambda函数)。 You are getting this error since two arguments are given but lambda function only accepts one argument. 由于给出了两个参数,但lambda函数仅接受一个参数,因此您会收到此错误。

Hope this example helps 希望这个例子有帮助

import pandas as pd
df = pd.DataFrame({'a':range(100,110), 'b':range(200, 210)})

def modulo(x, n=5):
    return x%n

some_dict = {0: 'a', 1:'b', 2:'c', 3:'d', 4:'e'}
print(df.apply(lambda row,n, map_dict: (map_dict[modulo(row['a'],n)], map_dict[modulo(row['b'],n)]), axis=1, args=(5, some_dict)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM