To rename a column in a pandas dataframe in Python, you can use the rename()
function. Here's the syntax:
main.py71 chars2 lines
Here, df
refers to the dataframe object, old_column_name
is the current name of the column that you want to rename, and new_column_name
is the new name that you want to give to the column.
By setting inplace=True
, the dataframe will be modified in place, without creating a new dataframe object. If you omit this parameter or set it to False
, a new dataframe with the renamed column will be returned.
Here's an example:
main.py352 chars15 lines
Output:
main.py132 chars5 lines
In the above example, we renamed the 'Name' column to 'First Name' using the rename()
function.
Remember to assign the updated dataframe back to df
(or a different variable) if you want to keep the changes.
gistlibby LogSnag