【问题标题】:replace() takes no keyword arguments, in for loopreplace() 在 for 循环中不接受关键字参数
【发布时间】:2020-02-04 01:20:49
【问题描述】:

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

    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

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

【问题讨论】:

  • 如果您使用外部库,请将其添加到问题的标签中。并显示“wo”的定义。
  • 如果您使用 pandas,则需要将替换应用到 DataFrame 或 Series 的 str,如下所示:column.str.replace。每次都必须在replace 函数之前添加str 部分。
  • 另外,pandas regex=True 是默认值,不需要指定。

标签: python for-loop replace typeerror keyword-argument


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    因为它不接受关键字参数而报错;在这种情况下regex=True。根据documentation,它不存在。另外,.replace 只针对字符串,所以这里的数据类型应该是str。另一方面,如果你想使用正则表达式,我推荐re.sub

    【讨论】:

      【解决方案3】:

      尝试删除 'regex = True' 将对我的情况有所帮助。

      # df_num_key_split[name][var].replace(to_replace="[\[|\]|']|\s+|\.|\-", value='', regex=True)
      
      

      在我这样做之后,它起作用了。

      df_num_key_split[name][var].replace("[\[|\]|']|\s+|\.|\-", '')
      
      

      【讨论】:

        猜你喜欢
        • 2015-08-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-09-01
        • 2021-09-24
        • 2018-11-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多