2017-07-31 135 views
0

我有數據幀熊貓:寫作系列JSON

 product_type bank   target val event_time 
0    1 24 target_offline 1.0 2017-04 
1    1 10  non_target 1.0 2017-04 
10    1  6  non_target 1.0 2017-04 
19    1 97  non_target 1.0 2017-05 
64    1 10  non_target 1.0 2017-06 
106    2 24 target_offline 1.0 2017-04 
107    2 10  non_target 1.0 2017-04 
116    2  6  non_target 1.0 2017-04 
125    2 97  non_target 1.0 2017-05 
170    2 10  non_target 1.0 2017-06 
212    3 24 target_offline 1.0 2017-04 

我用

d = df.groupby(['product_type', 'bank', 'target'])['event_time', 'val'].apply(
    lambda x: pd.Series(x.set_index('event_time')['val'].to_dict())).to_json(nielson_telecom, orient='index') 

但它返回

TypeError: Series.name must be a hashable type 

我也嘗試使用DataFrame,但它返回

ValueError: If using all scalar values, you must pass an index 

慾望輸出看起來像

{'product_type':{ 
      '6':{ 
      'target_offline':{ 
        '2017-04': 1, 
        '2017-05': 0, ...}}} 

}

我用

with open('name', 'w') as f: 
     json.dump(json.loads(nielson_telecom.getvalue()), f, indent=4, sort_keys=True) 
+0

@JohnGalt加入問題 –

回答

1

看起來過於複雜。當然,這不是你需要的東西?

import json 

dict_ = {"product_type":{}} 
for key,value in df.groupby(['product_type', 'bank', 'target']): 
    dict_["product_type"][str(key[1])] = {key[2]:value.set_index("event_time")["val"].to_dict()} 

with open("output.json", "w") as f: 
    f.write(json.dumps(dict_, indent=4)) 
    print(json.dumps(dict_, indent=4)) 

打印和輸出 「output.json」:

{ 
    "product_type": { 
     "97": { 
      "non_target": { 
       "2017-05": 1.0 
      } 
     }, 
     "6": { 
      "non_target": { 
       "2017-04": 1.0 
      } 
     }, 
     "24": { 
      "target_offline": { 
       "2017-04": 1.0 
      } 
     }, 
     "10": { 
      "non_target": { 
       "2017-04": 1.0, 
       "2017-06": 1.0 
      } 
     } 
    } 
} 

更新:如果要包括不同的產品類型: 不是最好的解決方案,但它的工作原理

import json 
from collections import defaultdict 

dict_ = defaultdict(dict) 

for key,value in df.groupby(['product_type', 'bank', 'target']): 
    dict_["product_type{}".format(key[0])][str(key[1])] = {key[2]:value.set_index("event_time")["val"].to_dict()}  

with open("output.json", "w") as f: 
    f.write(json.dumps(dict_, indent=4)) 
    print(json.dumps(dict_, indent=4)) 
+0

如何寫入json文件? –

+0

@PetrPetrov更新到包括文件輸出,但是我仍然不確定這是100%正確的。但希望如果某些東西缺少其他人可以填寫。 –