[英]How do i convert this Series to a nested json string?
So i have this Series object called ss
:所以我有这个名为
ss
Series 对象:
In [137]: d
Out[137]: {'-1': 24.0, '-2': 0.0, '-3': 0.0}
In [138]: ss = pd.Series(d)
In [139]: ss
Out[139]:
-1 24.0
-2 0.0
-3 0.0
dtype: float64
How do i get a json string in the following shape?如何获得以下形状的 json 字符串?
[
{
"y": 24.0,
"x": -1
},
{
"y": 0.0,
"x": -2
},
{
"y": 0.0,
"x": -3
}
]
I've tried the following, but it's not what is expected.我尝试了以下方法,但这不是预期的。
In [142]: result = json.loads(ss.to_json())
In [143]: result
Out[143]: {u'-1': 24.0, u'-2': 0.0, u'-3': 0.0}
EDIT: per the comment from Anton vBR, i'm trying with a DataFrame:编辑:根据 Anton vBR 的评论,我正在尝试使用 DataFrame:
In [151]: dd = {'-1': [24.0], '-2': [0.0], '-3': [0.0]}
In [153]: df = pd.DataFrame(dd)
In [154]: df
Out[154]:
-1 -2 -3
0 24.0 0.0 0.0
In [156]: df.to_dict()
Out[156]: {'-1': {0: 24.0}, '-2': {0: 0.0}, '-3': {0: 0.0}}
In [157]: df.to_json()
Out[157]: '{"-1":{"0":24.0},"-2":{"0":0.0},"-3":{"0":0.0}}'
But it's still not close to what i need.但它仍然不接近我需要的。
You could do something like this:你可以这样做:
import json
import pandas as pd
d = {'-1': 24.0, '-2': 0.0, '-3': 0.0}
ss = pd.Series(d)
result = json.dumps([{"x": k, "y": v} for k, v in ss.items()])
print(result)
Output输出
[{"x": "-1", "y": 24.0}, {"x": "-2", "y": 0.0}, {"x": "-3", "y": 0.0}]
Ok the idea here is to go directly to a DataFrame by accessing your dictionaries keys and values through the items()
function.好的,这里的想法是通过
items()
函数访问字典键和值来直接进入 DataFrame。
Let us call the columns x
and y
to get desired output.让我们调用
x
和y
列来获得所需的输出。
updated for json output为 json 输出更新
import json
import pandas as pd
d = {'-1': 24.0, '-2': 0.0, '-3': 0.0}
df = pd.DataFrame(list(d.items()), columns=['x','y'])
df['x'] = pd.to_numeric(df['x'])
dout = json.dumps(df.to_dict(orient='records'), indent=2)
# "[{"y": 0.0, "x": -2.0}, {"y": 0.0, "x": -3.0}, {"y": 24.0, "x": -1.0}]" with indent None
print(dout)
Returns退货
[
{
"y": 0.0,
"x": -2.0
},
{
"y": 0.0,
"x": -3.0
},
{
"y": 24.0,
"x": -1.0
}
]
首先将您的系列转换为 Dataframe,然后在 Dataframes 上使用内置方法:
df = pd.DataFrame(list(d.items()), columns=['x','y']).to_json(orient='records')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.