2014-09-10 37 views
1

我正在研究d3.js图形。我的数据是一个巨大的多选项.xls。我必须从每个标签中获取数据,因此我决定将所有数据转储到熊猫并导出一些.json文件。pandas groupby嵌套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 

现在,摆在熊猫,合并和清理:

 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”对于每个值,lol:

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

dang我几乎在那里,我如何导出它,使每个国家是父母?

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

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

回答

4

计数方法计算非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}]' 
+3

喔!这就像Excel一样,只是很酷。一个增加 - 无论出于什么原因,它看到“速度”作为类型对象,而不是浮动。它给了我错误“没有数字类型来聚合”。所以我hadda转换它为浮动:df.convert_objects('rate',convert_numeric = True) – Maggie 2014-09-10 20:18:02

+3

“这就像Excel,只有很酷。”辉煌的报价! – 2014-09-10 20:37:31