gpt4 book ai didi

Python - 如何将结果从 group by 传递到 Pivot?

转载 作者:太空宇宙 更新时间:2023-11-04 04:28:42 25 4
gpt4 key购买 nike

我的目标是将数据透视表函数应用于包含重复记录的数据框。我通过向数据框添加一个唯一列解决了这个问题:

my_df['id_column'] = range(1, len(my_df.index)+1)

df_pivot = my_df.pivot(index ='id_column', columns = 'type', values = 'age_16_18').fillna(0).astype(int)

我想弄清楚如何在不删除重复项或不使用数据透视表的情况下将 pivot 应用于数据框?通过按多列进行拳头分组,然后将结果传递给数据透视函数。我不确定分组后如何传递结果。

    year  category  state_name  type    is_state gender age_16_18 age_18_30
0 2001 Foreigners CA Convicts 0 M 8 5
1 2001 Indians NY Convicts 0 F 5 2
2 2005 Foreigners NY Others 1 M 0 9
3 2009 Indians NJ Detenus 0 F 7 0

最佳答案

目前还不完全清楚您在尝试什么,但看看您是否可以从以下方法中获得一些灵感。您希望按哪些列进行分组?

import pandas
my_df = pandas.DataFrame( { 'year' : [2001, 2001, 2005, 2009] ,
'category' : ['Foreigners','Indians','Foreigners','Indians'] ,
'state_name': ['CA','NY','NY','NJ' ],
'type': ['Convicts', 'Convicts','Others','Detenus'],
'is_state' : [0,0,1,0] ,
'gender' : ['M','F','M','F'],
'age_16_18':[8,5,0,7],
'age_18_30' : [5,2,9,0] }, columns=[ 'year','category','state_name','type','is_state','gender','age_16_18','age_18_30'])

>>> my_df.pivot( columns = 'type', values = 'age_16_18' )
type Convicts Detenus Others
0 8.0 NaN NaN
1 5.0 NaN NaN
2 NaN NaN 0.0
3 NaN 7.0 NaN

>>> my_df['key'] = my_df.category.str.cat(my_df.gender)

>>> my_df.pivot( index='key', columns = 'type', values = 'age_16_18' )
type Convicts Detenus Others
key
ForeignersM 8.0 NaN 0.0
IndiansF 5.0 7.0 NaN

关于Python - 如何将结果从 group by 传递到 Pivot?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53054149/

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