Python pandas dataframe pivot 仅适用于 pivot_table() 但不适用于 set_index() 和 unstack()

Python pandas dataframe pivot only works with pivot_table() but not with set_index() and unstack()

我正在尝试在 Python 中的 Pandas 数据框中转换以下类型的示例数据。我遇到了其他几个讨论如何进行数据透视的 Whosebug 答案:

但是,当我使用 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()。 关于为什么一种方法有效而另一种方法无效的任何见解?

AttributeError: 'NoneType' object has no attribute 'unstack'

当您在 set_index 中使用 inplace = True 时,它就地修改了数据框。它 return 什么都没有 (None)。所以你不能在 None 对象上使用 unstack

inplace : boolean, default False

Modify the DataFrame in place (do not create a new object)

使用:

df1 = pdDF.set_index(['items_id','responseTime','label']).unstack('label')    
print(df1)

# Output:

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