johnny_birkenhead
johnny_birkenhead

Reputation: 39

Rename a column of Pandas data-frame and change it's type

Is there a way to change the name of a variable in R to a label value?

For example, where the variable says 'ageband' I'm trying to change it to "Three way banded age group":

Data_2017_18.ageband.value_counts()
Out[118]: 
51 to 99    13320
30 to 40    10985
1 to 29      5002
Name: ageband, dtype: int64

I've tried this but it doesn't seem to be working:

import pandas as pd

Data_2017_18['Three-way banded age group'] = Data_2017_18['ageband'].astype("category")

Upvotes: 0

Views: 1990

Answers (1)

Aviv Yaniv
Aviv Yaniv

Reputation: 6298

NOTE: Renaming a column name to a name that includes spaces, is considered a bad-practice, and should be avoided by using underscores instead.

To rename a column in pandas just use the rename method.

import pandas as pd

d = {'ageband': [1, 2], 'col2': [3, 4]}
df = pd.DataFrame(data=d)

# Before :    ageband  col2
# 0        1     3
# 1        2     4
print(f'Before : {df}')

# Rename column name
df=df.rename(columns={'ageband' : "Three-way banded age group"})

# Convert type name to `category`
df[['Three-way banded age group']] = df[['Three-way banded age group']].astype('category')

# After :    Three-way banded age group  col2
# 0                           1     3
# 1                           2     4
print(f'After : {df}')

Upvotes: 1

Related Questions