Home >Backend Development >Python Tutorial >How to Rename Pandas DataFrame Column Names Efficiently?
Renaming Pandas DataFrame Column Names
Often, when working with Pandas DataFrames, it becomes necessary to modify column labels. Let's consider changing the column labels from ['$a', '$b', '$c', '$d', '$e'] to ['a', 'b', 'c', 'd', 'e'].
Renaming Specific Columns
To selectively modify specific columns, utilize the df.rename() method. This method accepts a dictionary as an argument, where keys represent old column labels and values represent new labels. For instance:
df = df.rename(columns={'$a': 'a', '$b': 'b'})
You can also modify the DataFrame in-place without creating a copy by setting inplace=True:
df.rename(columns={'$a': 'a', '$b': 'b'}, inplace=True)
Reassigning Column Headers
Alternatively, you can reassign the entire set of column headers using df.set_axis() with axis=1:
df2 = df.set_axis(['a', 'b', 'c', 'd', 'e'], axis=1)
Or, you can assign values directly to df.columns:
df.columns = ['a', 'b', 'c', 'd', 'e']
By implementing these techniques, you can effectively modify column names in Pandas DataFrames, ensuring that the data aligns with your desired labels.
The above is the detailed content of How to Rename Pandas DataFrame Column Names Efficiently?. For more information, please follow other related articles on the PHP Chinese website!