I have a DataFrame using pandas and column labels that I need to edit to replace the original column labels.
I'd like to change the column names in a DataFrame A
where the original column names are:
['$a', '$b', '$c', '$d', '$e']
to
['a', 'b', 'c', 'd', 'e'].
I have the edited column names stored it in a list, but I don't know how to replace the column names.
If your new list of columns is in the same order as the existing columns, the assignment is simple:
If you had a dictionary keyed on old column names to new column names, you could do the following:
If you don't have a list or dictionary mapping, you could strip the leading
$
symbol via a list comprehension:Real simple just use
and it will assign the column names by the order you put them
Use the
df.rename()
function and refer the columns to be renamed. Not all the columns have to be renamed:Another way we could replace the original column labels is by stripping the unwanted characters (here '$') from the original column labels.
This could have been done by running a for loop over df.columns and appending the stripped columns to df.columns.
Instead , we can do this neatly in a single statement by using list comprehension like below:
(
strip
method in Python strips the given character from beginning and end of the string.)