I have Pandas cross-tabulation object.
| Age Category | A | B | C | D |
|--------------|---|----|----|---|
| 21-26 | 2 | 2 | 4 | 1 |
| 26-31 | 7 | 11 | 12 | 5 |
| 31-36 | 3 | 5 | 5 | 2 |
| 36-41 | 2 | 4 | 1 | 7 |
| 41-46 | 0 | 1 | 3 | 2 |
| 46-51 | 0 | 0 | 2 | 3 |
| Above 51 | 0 | 3 | 0 | 6 |
If I am doing age.dtypes
this is giving me output
Age Category
A int64
B int64
C int64
D int64
dtype: object
But I want Age Category should also be object
. If it need to insert one more column for that that would be fine. So that the age.dtypes
should show something like this
Age Category
Age Category object
A int64
B int64
C int64
D int64
dtype: object
Thank you for your time and consideration
I think you need DataFrame.reset_index
for convert index to column and then if necessary rename_axis
:
age = age.reset_index().rename_axis(columns='Age Category')
print (age.dtypes)
Age Category
Age Category object
A int64
B int64
C int64
D int64
dtype: object
EDIT:
If columns names are categoricals use CategoricalIndex.add_categories
before:
age.columns = age.columns.add_categories(['Age Category'])
age = age.reset_index().rename_axis(columns='Age Category')
print (age.dtypes)
Age Category
Age Category object
A int64
B int64
C int64
D int64
dtype: object
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.