小能豆

Renaming column names in Pandas

python

I want to change the column labels of a Pandas DataFrame from

['$a', '$b', '$c', '$d', '$e']

to

['a', 'b', 'c', 'd', 'e']

阅读 117

收藏
2023-12-25

共1个答案

小能豆

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:

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.

The inplace=True argument modifies the DataFrame in place, so you don’t need to assign the result back to a new variable.

After running this code, your DataFrame will have column labels without the leading dollar sign.

2023-12-25