I noticed that it’s possible to use df.rename(columns=str.lower)
, but not df.rename(columns=str.replace(" ", "_"))
.
-
Is this because it is allowed to use the variable which stores the method (
str.lower
), but it’s not allowed to actually call the method (str.lower()
)?
There is a similar question, why the error message of df.rename(columns=str.replace(” “, “_”)) is rather confusing – without an answer on that. -
Is it possible to use methods of the
.str
accessor (ofpd.DataFrame().columns
) inside ofdf.rename(columns=...)
?
The only solution I came up so far isdf = df.rename(columns=dict(zip(df.columns, df.columns.str.replace(" ", "_"))))
but maybe there is something more consistent and similar to style of
df.rename(columns=str.lower)
? I knowdf.rename(columns=lambda x: x.replace(" ", "_")
works, but it doesn’t use the.str
accessor of pandas columns, it uses thestr.replace()
of the standard library.
The purpose of the question is explore the possibilities to use pandas str methods when renaming columns in method chaining, that’s whydf.columns = df.columns.str.replace(' ', '_')
is not suitable to me.
As an df
example, assume:
df = pd.DataFrame([[0,1,2]], columns=["a pie", "an egg", "a nut"])