我想在交叉列表中插入列吗?

时间:2019-12-06 10:00:25

标签: python python-3.x pandas python-2.7

我有熊猫交叉制表对象。

| 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 |

如果我在做age.dtypes,这会给我输出

Age Category
A int64
B int64
C int64
D int64 
dtype: object

但是我希望年龄类别也应该是object。如果需要为此再插入一列,那就没问题了。这样age.dtypes应该显示类似这样的内容

Age Category
Age Category  object
A             int64
B             int64
C             int64
D             int64 
dtype: object

感谢您的时间和考虑

1 个答案:

答案 0 :(得分:1)

我认为您需要DataFrame.reset_index才能将索引转换为列,然后在必要时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

编辑:

如果列名是分类的,请在前面使用CategoricalIndex.add_categories

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