2017-04-16 209 views
1

我有一個PandasDataframe或兩行數據,我想作爲JSON陣列通過。熊貓數據幀轉換爲JSON

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

我試着用df.to_json(orient='index'),但輸出是不完全正確,因爲它似乎是使用indexkeys

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

回答

2

JSON需要格式化如下如果您需要一系列字典,可以使用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"}]'