簡體   English   中英

我想在交叉表中插入列?

[英]I want to insert column in cross-tabulation?

我有 Pandas 交叉表對象。

| 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

但我希望Age Category也應該是object 如果需要為此再插入一列就可以了。 所以age.dtypes應該顯示這樣的東西

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

感謝您的時間和考慮

我認為您需要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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM