【问题标题】:I want to insert column in cross-tabulation?我想在交叉表中插入列?
【发布时间】:2019-12-06 10:00:25
【问题描述】:

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

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

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

感谢您的时间和考虑

【问题讨论】:

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


    【解决方案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
    

    【讨论】:

    • 我收到TypeError: cannot insert an item into a CategoricalIndex that is not already an existing category
    • 现在,我收到了ValueError: new categories must not include old categories: {'Age Category'}
    • @MaqsudInamdar - age.columns = age.columns.add_categories(['Age Category']) 两次没用?
    • @jezrael 我有一个问题。您可能使用pd.read_clipboard() 来复制OP 的表。您如何摆脱表格中的-| 等符号?您是手动删除它们还是使用pandas 有更好的方法?
    • @jezrael 谢谢。我将尝试就这个问题提出一个问题。 :)
    猜你喜欢
    • 2020-03-30
    • 1970-01-01
    • 2010-10-01
    • 1970-01-01
    • 2014-05-04
    • 1970-01-01
    • 1970-01-01
    • 2015-06-12
    • 1970-01-01
    相关资源
    最近更新 更多