Pandas 系列到 json 并返回

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22965985/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 21:54:39  来源:igfitidea点击:

Pandas Series to json and back

pythonjsonpandas

提问by tschm

I have some problems converting a simple Pandas Series into a json string and back. Here's my attempt

我在将简单的 Pandas 系列转换为 json 字符串并返回时遇到了一些问题。这是我的尝试

import pandas as pd
f = pd.Series(data=[1.0,2.0,3.0],index=[10,20,30])
x = f.to_json()
a = pd.read_json(x)

This results in ValueError: If using all scalar values, you must pass an Index.

这会导致 ValueError:如果使用所有标量值,则必须传递索引。

The json String x looks like {"10":1.0,"20":2.0,"30":3.0}

json 字符串 x 看起来像 {"10":1.0,"20":2.0,"30":3.0}

What's missing here. Please help

这里缺少什么。请帮忙

回答by dnll

You need to specify the type of object (default is DataFrame) and the format of the JSON string. More info here.

您需要指定对象的类型(默认为DataFrame)和 JSON 字符串的格式。更多信息在这里

This should work:

这应该有效:

a = pd.read_json(x, typ='series', orient='records')