可以使用cat.rename_categories()
方法重命名的類別。如果您想要使用原始級別,則可以使用cat.codes
來獲取基礎整數。這裏有一個重複的例子:
df = pd.DataFrame({'age_group':["1","2","3","4","5","6","7"]},
dtype="category")
# Rename categories
df.age_group = df.age_group.cat.rename_categories([ '0-23','24-27','48-59',
'60-71','72-79','80-87','88-99'])
# Test
> df
age_group
0 0-23
1 24-27
2 48-59
3 60-71
4 72-79
5 80-87
6 88-99
# Underlying integers
> df.age_group.cat.codes
0 0
1 1
2 2
3 3
4 4
5 5
6 6
dtype: int8
另外,如果你的列並非是絕對的,你可以使用字典結合.replace()
打印的相關值。
# Create data and dictionary
df = pd.DataFrame({'age_group':[1,2,3,4,5,6,7,8]})
d = {1:'0-23',2:'24-27',3:'48-59',4:'60-71',5:'72-79',6:'80-87',7:'88-99'}
# Print matching values
df.replace({"age_group": d})
age_group
0 0-23
1 24-27
2 48-59
3 60-71
4 72-79
5 80-87
6 88-99
@mtoto ....如果他們不在類,我需要將其轉換並應用上面的程序?有沒有重命名類別,如適用格式欄只是爲了打印任何其他方法,因爲當我想看到df,它應該還有代碼,當我打印時,應該應用該格式。 – marupav
請參閱編輯,讓我知道這是否工作。 – mtoto