Now to change the column names all we have to do is assign the new column names in a list to df.columns. df.columns returns the names of the columns df.columns # rename column names with lambda functionĭf.rename(columns = lambda x : x.replace(' ', '_').lower())Īnother way to rename column names is using df.columns attribute.
We can also do method chaining to lowercase all the column names along with replacing whitespace with underscore in one call. # rename column names with lambda functionĭf.rename(columns = lambda x : x.replace(' ', '_')) To change the column names we can use the lambda function with the rename function. The column names contains white spaces between words which means you can not use the dot notation for column selection. Here, we have some data for clothing store sales.
This is useful when you want to rename all of the columns in a particular way like replacing spaces with underscore. You can also pass a lambda function to the columns and index parameters of the rename function. (2) Using df.rename() with lambda function – # import pandasĬorporations = ĭf = pd.DataFrame(ĭf.rename(cols, axis='columns', inplace=True) Let’s create a pandas dataframe to work with. There could be multiple reasons why do you want to do that, so let’s take a look. You have a dataframe and you want to rename the column names because either the names have extra useless characters or you want to change the names to all lowercase or you want to replace the spaces with underscores so that you can use the dot notation for column selection.