

#Rename a column in pandas how to#
You learned how to be specific about which columns to rename, how to apply transformations to all columns, and how to rename only columns in a specific level of a MultiIndex dataframe. One way of renaming the columns in a Pandas Dataframe is by using the rename() function. In line 6, we specify new column names and assign them to the columns property of the DataFrame. How to rename columns in Pandas DataFrame Method 1: Using rename() function. In line 4, we print the new DataFrame with a new column name. I have 2 merged csv datasets and I need to rename the rows putting only the abbreviation, like " new york" becomes " NY". In this post, you learned about the different ways to rename columns in a Pandas dataframe. In line 1, we use the rename () function and pass in the old column name and the new column name. This returns the following dataframe: gender_of_person Female male Renaming a single column by nameįor example, if we wanted to rename the Age Group column to age_group, we could write: df = df.rename(columns=, level=0) df df.rename(columnsstr.lower) df. Alternatively, you can use inplaceTrue and skip the df bit at the beginning. To do this we reassign df.rename (columnsstr.lower) back to df. The easiest way would be to pass in a dictionary with just a single key:value pair. The cleanest way to rename column names is to combine the rename () function with str.lower (). To rename a single column, we can approach this in multiple ways.

If you do use a mapper, values must be unique (i.e., a 1-to-1 match) and ignores missing values (leaving them as-is).Ĭheck out some other Python tutorials on datagy, including our complete guide to styling Pandas and our comprehensive overview of Pivot Tables in Pandas! How to rename a single Pandas column You can pass in mappers (either functions or dictionaries) or lists to change them entirely. We’ll focus on the columns item for this tutorial. rename() method alters axes labels – either for rows or columns. We can see that there are a number of quirks with the column names (such as leading and additional spaces). This returns the following: Index(, dtype='object') columns attribute.īy printing out the df.columns attribute, all the columns are returned: print(df.columns) Let’s see how we can explore the columns of the dataframe using the. This returns the following dataframe: Name Age Age Group Birth City Gender of person We’ll use pandas to create the dataframe that we’ll use throughout the tutorial.

