[英]Replace function not accepting list as argument - pandas. Getting error TypeError: replace() argument 1 must be str, not list
I have searched many past questions but could not find answer to my problem! 我已经搜索了许多过去的问题,但找不到我的问题的答案!
I am trying to replace the column names of a data frame by passing two lists. 我试图通过传递两个列表来替换数据框的列名。 First list (current column names) as to_replace argument and second list as value (new column names).
第一个列表(当前列名称)作为to_replace参数,第二个列表作为值(新列名称)。 According to the df.replace documentation, one can pass lists:
根据df.replace文档,可以传递列表:
list of str, regex, or numeric: str,regex或数字列表:
- 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.
My code is: 我的代码是:
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)
I am geeting error: 我正在检查错误:
TypeError: replace() argument 1 must be str, not list
TypeError:replace()参数1必须是str,而不是list
But documentation said, one can pass lists! 但是文档说,一个可以通过列表! Am i missing something?
我想念什么吗? Any help?!
有帮助吗?
.replace
is used for replacing a DataFrame's values , which are distinct from the DataFrame's column names. .replace
用于替换DataFrame的值 ,该值不同于DataFrame的列名。 @sacul is right - the easiest way to do what you want to do, is to simply replace the .columns
attribute with a new list: @sacul是正确的-做您想做的最简单的方法是简单地用一个新列表替换
.columns
属性:
df.columns = NewColNames
If you have a dictionary mapping current names to new names (let's call it current_to_new
, you could also use .rename
: 如果您有一个将当前名称映射为新名称的字典(我们将其命名为
current_to_new
,则也可以使用.rename
:
df = df.rename(columns=current_to_new)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.