Have you ever wondered how to change the column labels of a Pandas DataFrame? In this article, we'll dive into various methods for renaming these labels, giving you the flexibility to customize your data structures.
To rename specific columns, utilize the df.rename() function. This method allows you to map old column names to new ones, targeting only the columns you want to modify.
Alternatively, you can rename columns in place (without creating a copy) by setting inplace=True within the function.
Example:
df = df.rename(columns={'oldName1': 'newName1', 'oldName2': 'newName2'}) # Or rename the DataFrame (rather than creating a copy): df.rename(columns={'oldName1': 'newName1', 'oldName2': 'newName2'}, inplace=True)
If you want to completely reassign the column headers, use the df.set_axis() method with axis=1. This allows you to specify a list of new header labels.
Example:
df2 = df.set_axis(['V', 'W', 'X', 'Y', 'Z'], axis=1)
To assign headers directly, simply set the df.columns attribute to the desired list of labels.
Example:
df.columns = ['V', 'W', 'X', 'Y', 'Z']
The above is the detailed content of How Can I Rename Column Labels in a Pandas DataFrame?. For more information, please follow other related articles on the PHP Chinese website!