重命名dataframe的列并更改其类型

2024-10-05 14:23:02 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有办法将R中变量的名称更改为标签值

例如,当变量表示“年龄段”时,我试图将其更改为“三向分带年龄组”:

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

我试过这个,但似乎不起作用:

import pandas as pd

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

Tags: tonameimport名称datavalue标签out
1条回答
网友
1楼 · 发布于 2024-10-05 14:23:02

注意:将列名重命名为包含空格的名称被认为是一种不好的做法,应该使用下划线来避免

要重命名pandas中的列,只需使用^{}方法

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}')

相关问题 更多 >