gpt4 book ai didi

python - pandas groupby 到嵌套的 json——不需要计算字段

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

我正在处理 d3.js 图形。我的数据在一个巨大的多标签 .xls 中。我必须从每个选项卡中获取数据,所以我决定将其全部转储到 pandas 中并导出一些 .json。

原始数据,分布在许多标签中:

demography, area, state, month, rate
over 65, region2, GA, May, 23
over 65, region2, AL, May, 25
NaN, random_odd_data, mistake, error
18-65, region2, GA, 77
18-65, region2, AL, 75

现在,放入 pandas,合并并清理:

     demography area     state  month rate
0 over 65 region2 GA May 23
1 over 65 region2 AL May 25
2 18-65 region2 GA May 50
3 18-65 region2 AL May 55

现在,把它分组

group = df.groupby(['state', 'demography'])

产量

<pandas.core.groupby.DataFrameGroupBy object at 0x106939610>

试试这个:

group = df.groupby(['state', 'demography']).count()

产生的结果几乎是正确的,除了我不想计算任何东西,我只想“评分”

state    demography  area   month  rate
AL over 65 1 1 1
18-65 1 1 1
GA over 65 1 1 1
18-65 1 1 1

果然,这只为每个值导出“1”,哈哈:

group.reset_index().to_json("myjson2.json", orient="index")

当我快到了,我如何导出它以便每个状态都是父级?

[
{
"state": "Alabama",
"over 65": 25,
"18-65": 50

},
{
"state": "Georgia",
"over 65": 23,
"18-65": 55
}
]

最佳答案

count 方法计算每列中每个组的非 NaN 条目的数量,因此它们在这里都是 1(每个组的大小为 1,没有 NaN)。
(我找不到具体链接,但在 the groupby docs 中提到了。)


我想你真正想要的是 pivot_table :

In [11]: res = df.pivot_table('rate', 'state', 'demography')

In [12]: res
Out[12]:
demography 18-65 over65
state
AL 55 25
GA 50 23

我认为您正在寻找 orient='records'(不过您需要先reset_index):

In [13]: res.reset_index().to_json(orient='records')
Out[13]: '[{"state":"AL","18-65":55,"over65":25},{"state":"GA","18-65":50,"over65":23}]'

关于python - pandas groupby 到嵌套的 json——不需要计算字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25770885/

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