I want to change the column labels of a Pandas DataFrame from
['$a', '$b', '$c', '$d', '$e']
to
['a', 'b', 'c', 'd', 'e']
You can use the rename method of a Pandas DataFrame to change the column labels. In your case, you want to remove the leading dollar sign (‘$’) from each column label. Here’s an example:
rename
import pandas as pd # Sample DataFrame data = {'$a': [1, 2, 3], '$b': [4, 5, 6], '$c': [7, 8, 9], '$d': [10, 11, 12], '$e': [13, 14, 15]} df = pd.DataFrame(data) # Display the original DataFrame print("Original DataFrame:") print(df) # Rename columns by removing the leading dollar sign df.rename(columns=lambda x: x.lstrip('$'), inplace=True) # Display the DataFrame with updated column labels print("\nDataFrame with Updated Column Labels:") print(df)
In this example, df.rename(columns=lambda x: x.lstrip('$'), inplace=True) is used to remove the leading dollar sign from each column label. The lambda x: x.lstrip('$') function is applied to each column label.
df.rename(columns=lambda x: x.lstrip('$'), inplace=True)
lambda x: x.lstrip('$')
The inplace=True argument modifies the DataFrame in place, so you don’t need to assign the result back to a new variable.
inplace=True
After running this code, your DataFrame will have column labels without the leading dollar sign.