【发布时间】: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 谢谢人,但我正在尝试编写通用代码,因为我的数据文件头通常有特殊字符,如 %、?、/ 等等。最终,我试图找到一种从标题名称中删除这些字符的方法。我认为这可能是一个好的开始。