44import operator
55import weakref
66import gc
7+ import json
78
89import numpy as np
910import pandas .lib as lib
@@ -129,6 +130,37 @@ def __init__(self, data, axes=None, copy=False, dtype=None,
129130 object .__setattr__ (self , '_data' , data )
130131 object .__setattr__ (self , '_item_cache' , {})
131132
133+ def _ipython_display_ (self ):
134+ try :
135+ from IPython .display import display
136+ except ImportError :
137+ return None
138+
139+ # Series doesn't define _repr_html_ or _repr_latex_
140+ latex = self ._repr_latex_ () if hasattr (self , '_repr_latex_' ) else None
141+ html = self ._repr_html_ () if hasattr (self , '_repr_html_' ) else None
142+ table_schema = self ._repr_table_schema_ ()
143+ # We need the inital newline since we aren't going through the
144+ # usual __repr__. See
145+ # https://github.com/pandas-dev/pandas/pull/14904#issuecomment-277829277
146+ text = "\n " + repr (self )
147+
148+ reprs = {"text/plain" : text , "text/html" : html , "text/latex" : latex ,
149+ "application/vnd.dataresource+json" : table_schema }
150+ reprs = {k : v for k , v in reprs .items () if v }
151+ display (reprs , raw = True )
152+
153+ def _repr_table_schema_ (self ):
154+ """
155+ Not a real Jupyter special repr method, but we use the same
156+ naming convention.
157+ """
158+ if config .get_option ("display.html.table_schema" ):
159+ data = self .head (config .get_option ('display.max_rows' ))
160+ payload = json .loads (data .to_json (orient = 'table' ),
161+ object_pairs_hook = collections .OrderedDict )
162+ return payload
163+
132164 def _validate_dtype (self , dtype ):
133165 """ validate the passed dtype """
134166
@@ -1094,7 +1126,7 @@ def __setstate__(self, state):
10941126 strings before writing.
10951127 """
10961128
1097- def to_json (self , path_or_buf = None , orient = None , date_format = 'epoch' ,
1129+ def to_json (self , path_or_buf = None , orient = None , date_format = None ,
10981130 double_precision = 10 , force_ascii = True , date_unit = 'ms' ,
10991131 default_handler = None , lines = False ):
11001132 """
@@ -1129,10 +1161,17 @@ def to_json(self, path_or_buf=None, orient=None, date_format='epoch',
11291161 - index : dict like {index -> {column -> value}}
11301162 - columns : dict like {column -> {index -> value}}
11311163 - values : just the values array
1164+ - table : dict like {'schema': {schema}, 'data': {data}}
1165+ describing the data, and the data component is
1166+ like ``orient='records'``.
11321167
1133- date_format : {'epoch', 'iso'}
1168+ .. versionchanged:: 0.20.0
1169+
1170+ date_format : {None, 'epoch', 'iso'}
11341171 Type of date conversion. `epoch` = epoch milliseconds,
1135- `iso`` = ISO8601, default is epoch.
1172+ `iso` = ISO8601. The default depends on the `orient`. For
1173+ `orient='table'`, the default is `'iso'`. For all other orients,
1174+ the default is `'epoch'`.
11361175 double_precision : The number of decimal places to use when encoding
11371176 floating point values, default 10.
11381177 force_ascii : force encoded string to be ASCII, default True.
@@ -1151,14 +1190,53 @@ def to_json(self, path_or_buf=None, orient=None, date_format='epoch',
11511190
11521191 .. versionadded:: 0.19.0
11531192
1154-
11551193 Returns
11561194 -------
11571195 same type as input object with filtered info axis
11581196
1197+ See Also
1198+ --------
1199+ pd.read_json
1200+
1201+ Examples
1202+ --------
1203+
1204+ >>> df = pd.DataFrame([['a', 'b'], ['c', 'd']],
1205+ ... index=['row 1', 'row 2'],
1206+ ... columns=['col 1', 'col 2'])
1207+ >>> df.to_json(orient='split')
1208+ '{"columns":["col 1","col 2"],
1209+ "index":["row 1","row 2"],
1210+ "data":[["a","b"],["c","d"]]}'
1211+
1212+ Encoding/decoding a Dataframe using ``'index'`` formatted JSON:
1213+
1214+ >>> df.to_json(orient='index')
1215+ '{"row 1":{"col 1":"a","col 2":"b"},"row 2":{"col 1":"c","col 2":"d"}}'
1216+
1217+ Encoding/decoding a Dataframe using ``'records'`` formatted JSON.
1218+ Note that index labels are not preserved with this encoding.
1219+
1220+ >>> df.to_json(orient='records')
1221+ '[{"col 1":"a","col 2":"b"},{"col 1":"c","col 2":"d"}]'
1222+
1223+ Encoding with Table Schema
1224+
1225+ >>> df.to_json(orient='table')
1226+ '{"schema": {"fields": [{"name": "index", "type": "string"},
1227+ {"name": "col 1", "type": "string"},
1228+ {"name": "col 2", "type": "string"}],
1229+ "primaryKey": "index",
1230+ "pandas_version": "0.20.0"},
1231+ "data": [{"index": "row 1", "col 1": "a", "col 2": "b"},
1232+ {"index": "row 2", "col 1": "c", "col 2": "d"}]}'
11591233 """
11601234
11611235 from pandas .io import json
1236+ if date_format is None and orient == 'table' :
1237+ date_format = 'iso'
1238+ elif date_format is None :
1239+ date_format = 'epoch'
11621240 return json .to_json (path_or_buf = path_or_buf , obj = self , orient = orient ,
11631241 date_format = date_format ,
11641242 double_precision = double_precision ,
0 commit comments