简体   繁体   English

熊猫数据框转换为JSON

[英]Pandas Dataframe conversion to JSON

I have a Pandas Dataframe or two rows with data that I'd like to pass as a JSON array. 我有一个Pandas Dataframe或两行包含我想作为JSON数组传递的数据。

The JSON needs to be formatted as follow: JSON格式如下:

[{
    "Date": "2017-02-03",
    "Text": "Sample Text1"
},
{
    "Date": "2015-02-04",
    "Text": "Sample Text2"
}]

I tried using df.to_json(orient='index') , but the output is not quite right as it seems to be using the index values as keys 我尝试使用df.to_json(orient='index') ,但是输出似乎不太正确,因为它似乎正在使用index值作为keys

{"0":{"Date":"2017-02-03","Text""Sample Text1"},"1":{"Date":"2017-02-04","Text""Sample Text2"}}

If you want an array of dictionaries, you can use orient='records' : 如果需要字典数组,可以使用orient='records'

>>> import pandas as pd
>>> df = pd.DataFrame({
...     'Date': ['2017-02-03', '2015-02-04'],
...     'Text': ['Sample Text 1', 'Sample Text 2']
... })
>>> df.to_json(orient='records')
'[{"Date":"2017-02-03","Text":"Sample Text 1"},{"Date":"2015-02-04","Text":"Sample Text 2"}]'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM