我有數據幀熊貓:寫作系列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)
@JohnGalt加入問題 –