繁体   English   中英

How do I *avoid* passing arguments to function in Python pandas.apply function?

[英]How do I *avoid* passing arguments to function in Python pandas .apply function?

我想试验 pandas apply function 中的raw=True选项,根据 p. 155高性能 Python,作者 Gorelick 和 Ozsvald。 但是,Python 显然将raw=True作为我正在申请的 function 的参数,而不是.apply ZC1C425268E68385D1AB5074C17A94F14 本身的参数:

import pandas as pd

df = pd.DataFrame(columns=('a', 'b'))
df.loc[0] = (1, 2)
df.loc[1] = (3, 4)

df['a'] = df['a'].apply(str, raw=True)

当我尝试执行此操作时,出现以下错误:

TypeError: 'raw' is an invalid keyword argument for str()

即使我使用lambda表达式,问题仍然存在:

df['a'] = df['a'].apply(lambda x: str(x), raw=True)

如果我调用自定义的 function 而不是str ,问题仍然存在。

如何让 Pandas 认识到raw=True.apply而不是str的参数?

参考评论,我不认为这些是副作用。 如文档所述,将raw=True作为参数传递,“函数接收 ndarray 对象”,因此您传递一个数组并将其转换为字符串。 结果是一个类似[1 3]的字符串。 因此,您不要将每个值转换为字符串,而是将整个 Series 转换为字符串

如果你写一个小助手 function 你可以看到。

def conv(col):
    print(f"input values: {col}")
    print(f"type input: {type(col)}\n")
    return str(col)

t = df[['a']].apply(conv, raw=True)
print(f"{type(t)}:\n{t}\n")
print(f"first value: {type(t[0])}:\n{t[0]}\n")
print(f"{t[0][0]}")

Output:

input values: [1 3]
type input: <class 'numpy.ndarray'>

<class 'pandas.core.series.Series'>:
a    [1 3]
dtype: object

first value: <class 'str'>:
[1 3]

[

暂无
暂无

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

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