在 for 循环中,replace() 不接受关键字参数

Map*_*ofu 5 python replace for-loop typeerror keyword-argument

我正在尝试将多列美元金额转换为浮点数,并编写了以下代码

    for column in wo.columns[14:21]:
        column = (column.replace( '[\$,)]','', regex=True )
                   .replace( '[(]','-',   regex=True ).replace('#NAME?','NaN', regex=True).astype(float))
    return column


And this is the error i get:
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-276-f7c13cb3d0af> in <module>
      1 for column in wo.columns[14:19]:
----> 2     column = (column.replace( '[\$,)]','', regex=True )
      3                .replace( '[(]','-',   regex=True ).replace('#NAME?','NaN', regex=True).astype(float))
      4 return column
      5 

TypeError: replace() takes no keyword arguments
Run Code Online (Sandbox Code Playgroud)

可能出了什么问题?wo 是数据帧的名称,我用来加载数据帧的库是 Pandas,当我在其他单独的列上使用代码时,它工作得很好,只是当我使用 for 循环时,它返回一个错误。

zig*_*zag 7

它给出一个错误,因为它不接受关键字参数;在这种情况下regex=True。根据文档,它不存在。另外,.replace仅适用于字符串,因此这里的数据类型应该是str. 另一方面,如果您想使用正则表达式,我建议re.sub


小智 1

柱是什么类型? print(type(column)) 如果它是一个 str,它将使用 str.replace,它不需要 kwargs。尝试删除regex=True.