【发布时间】:2019-02-13 06:15:25
【问题描述】:
我正在尝试在 Python 的 Pandas 数据框中转换以下类型的示例数据。我遇到了其他几个讨论如何进行数据透视的 stackoverflow 答案:pivot_table No numeric types to aggregate
但是,当我使用pivot_table() 时,我能够对数据进行透视。但是当我使用set_index() 和unstack() 时,出现以下错误:
AttributeError: 'NoneType' 对象没有属性 'unstack'
样本数据:
id responseTime label answers
ABC 2018-06-24 Category_1 [3]
ABC 2018-06-24 Category_2 [10]
ABC 2018-06-24 Category_3 [10]
DEF 2018-06-25 Category_1 [7]
DEF 2018-06-25 Category_8 [10]
GHI 2018-06-28 Category_3 [7]
期望的输出:
id responseTime category_1 category_2 category_3 category_8
ABC 2018-06-24 [3] [10] [10] NULL
DEF 2018-06-25 [7] NULL NULL [10]
GHI 2018-06-28 NULL NULL [7] NULL
这行得通:
df=pdDF.pivot_table(index=['items_id','responseTime'], columns='label', values='answers', aggfunc='first')
这不起作用:
pdDF.set_index(['items_id','responseTime','label'], append=True, inplace=True).unstack('label')
我还使用了pdDF[pdDF.isnull().any(axis=1)] 来确保答案列中没有任何 NULL 数据。我也使用了append=False,但发生了同样的错误。
从其他线程来看,set_index() 和unstack() 似乎比pivot_table() 更有效。我也不想使用pivot_table(),因为它需要聚合函数,而且我的答案列不包含数字数据。我不想使用默认值 (mean()),所以我最终使用了 first()。
关于为什么一种方法有效而另一种方法无效的任何见解?
【问题讨论】:
标签: python pandas pivot-table attributeerror