gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 18:08:28 24 4
gpt4 key购买 nike

我正在尝试在 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()。关于为什么一种方法有效而另一种方法无效的任何见解?

最佳答案

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

当您在 set_index 中使用 inplace = True 时,它就地修改了数据框。它不返回任何内容(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

关于Python pandas dataframe pivot 仅适用于 pivot_table() 但不适用于 set_index() 和 unstack(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52230219/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com