我的第一个数据帧df_gammask
如下所示:
distance breakEvenDistance min max
0 2.1178 2.0934 NaN 0.000955
1 2.0309 2.1473 0.000955 0.001041
2 1.9801 1.7794 0.001041 0.001124
3 1.9282 2.1473 0.001124 0.001199
4 1.8518 1.5885 0.001199 0.001259
5 1.8518 1.5151 0.001259 0.001319
第二个df_gammabid
:
distance breakEvenDistance min max
0 1.9999 1.9329 NaN 0.001034
1 1.9251 2.0670 0.001034 0.001118
2 1.8802 1.6758 0.001118 0.001193
3 1.8802 1.5956 0.001193 0.001252
4 1.7542 1.5181 0.001252 0.001317
5 1.7542 1.4541 0.001317 0.001374
我需要的是一个像这样的json文件:
{
"buy": [
{
"distance": 0.6278,
"breakEvenDistance": 0.6261,
"max": 0.0031920626236615754
},
{
"distance": 0.6224,
"breakEvenDistance": 0.6199,
"min": 0.0031920626236615754,
"max": 0.003223405873670448
},
{
"distance": 0.6202,
"breakEvenDistance": 0.6142,
"min": 0.003223405873670448,
"max": 0.003253791039488344
},
{
"distance": 0.6174,
"breakEvenDistance": 0.6081,
"min": 0.003253791039488344,
"max": 0.003285709011703031}],
"sell": [
{
"distance": 0.8012,
"breakEvenDistance": 0.8005,
"max": 0.0024962095663052064
},
{
"distance": 0.7996,
"breakEvenDistance": 0.7939,
"min": 0.0024962095663052064,
"max": 0.002516799325547373
},
{
"distance": 0.794,
"breakEvenDistance": 0.7877,
"min": 0.002516799325547373,
"max": 0.0025370182220432014
},
{
"distance": 0.7927,
"breakEvenDistance": 0.7807,
"min": 0.0025370182220432014,
"max": 0.0025605480833123294
}]
我知道有一个功能pd.DataFrame.to_json
,但是它适用于一个数据帧,关于如何使用上述格式的2个数据帧有任何线索吗?我必须合并它们吗? buy
面是df_gammask
,而sell
面是dg_gammabid
!谢谢
答案 0 :(得分:2)
在嵌套字典理解中使用DataFrame.to_dict
来删除丢失的值,然后创建a, b, c
并转换为dictionary
:
json
import json
L1 = [{k: v for k, v in x.items() if pd.notnull(v)} for x in df_gammask.to_dict('r')]
L2 = [{k: v for k, v in x.items() if pd.notnull(v)} for x in df_gammabid.to_dict('r')]
答案 1 :(得分:1)
Firs将您的数据框转换为字典:
dict_gammask = df_gammask.to_dict()
dict_gammabid = df_gammabid.to_dict()
然后将它们放在所需结构的另一本词典中:
result_dict = {'buy': dict_gammabid, 'sell': dict_gammask}
然后您可以将其转换为json:
import json
json_result = json.dumps(result_dict)
或将其保存到文件中
with open('data.json', 'w') as outfile:
json.dump(result_dict, outfile)