I'd like to know how to change the column name in Pandas.

Asked 2 years ago, Updated 2 years ago, 157 views

I'm working on a diagram in the Pandas module, and the column name comes with $ in front of it.

['$a', '$b', '$c', '$d', '$e', ...] -> ['a', 'b', 'c', 'd', 'e', ..]. I want to remove all the $ before the column name.

I removed the $ by calling the column names into the list I don't know how to apply this to the table.

python replace rename pandas

2022-09-22 22:28

1 Answers

df = pd.DataFrame({'$a':[1,2], '$b': [10,20]})
df.columns = ['a', 'b'] #Columns can be renamed even if frames are already created
print(df)

Result: a b 0 1 10 1 2 20

import pandas
pd = pandas
df = pd.DataFrame({'$a':[1,2], '$b': [10,20]})

print("df.columns:", df.columns)
df.rename(columns = lambda x : x[1:], inplace = True)
#or df = df.rename (columns = {'$a': 'a', '$b': 'b'})

print("-----change------")
print("df.columns:", df.columns)

Results:

('df.columns:', Index([u'$a', u'$b'], dtype='object'))
-----change------
('df.columns:', Index([u'a', u'b'], dtype='object'))


2022-09-22 22:28

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.