【问题标题】:Replace function not accepting list as argument - pandas. Getting error TypeError: replace() argument 1 must be str, not list替换不接受列表作为参数的函数 - pandas。得到错误类型错误:replace() 参数 1 必须是 str,而不是列表
【发布时间】:2019-05-08 17:58:07
【问题描述】:

我搜索了许多过去的问题,但找不到我的问题的答案!

我试图通过传递两个列表来替换数据框的列名。第一个列表(当前列名)作为 to_replace 参数,第二个列表作为值(新列名)。根据 df.replace 文档,可以传递列表:

  • str、regex 或 numeric 的列表:

    - First, if `to_replace` and `value` are both lists, they
      **must** be the same length.
    - Second, if ``regex=True`` then all of the strings in **both**
      lists will be interpreted as regexs otherwise they will match
      directly. This doesn't matter much for `value` since there
      are only a few possible substitution regexes you can use.
    - str, regex and numeric rules apply as above.
    

我的代码是:

CurrentColNames=list(df.columns)

NewColNames=['Hello','Hi', ...'Bye'] #Just an example. Lists are of same size and type. 

df.rename(columns={c: c.replace(CurrentColNames,NewColNames) for c in df.columns},inplace=True)

我收到错误:

TypeError: replace() 参数 1 必须是 str,而不是 list

但是文档说,一个可以通过列表!我错过了什么吗?有什么帮助吗?!

【问题讨论】:

  • 您正在寻找一种复杂的方法来做一些简单的事情。只需:df.columns = NewColNames
  • @sacul 谢谢人,但我正在尝试编写通用代码,因为我的数据文件头通常有特殊字符,如 %、?、/ 等等。最终,我试图找到一种从标题名称中删除这些字符的方法。我认为这可能是一个好的开始。

标签: python pandas jupyter


【解决方案1】:

.replace 用于替换 DataFrame 的 ,它们与 DataFrame 的列名不同。 @sacul 是对的 - 做你想做的最简单的方法就是用一个新列表替换 .columns 属性:

df.columns = NewColNames

如果您有一个将当前名称映射到新名称的字典(我们称之为current_to_new,您也可以使用.rename

df = df.rename(columns=current_to_new)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-14
    • 1970-01-01
    • 1970-01-01
    • 2018-03-11
    • 2022-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多