4
4
import operator
5
5
import weakref
6
6
import gc
7
+ import json
7
8
8
9
import numpy as np
9
10
import pandas .lib as lib
@@ -129,6 +130,37 @@ def __init__(self, data, axes=None, copy=False, dtype=None,
129
130
object .__setattr__ (self , '_data' , data )
130
131
object .__setattr__ (self , '_item_cache' , {})
131
132
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
+
132
164
def _validate_dtype (self , dtype ):
133
165
""" validate the passed dtype """
134
166
@@ -1094,7 +1126,7 @@ def __setstate__(self, state):
1094
1126
strings before writing.
1095
1127
"""
1096
1128
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 ,
1098
1130
double_precision = 10 , force_ascii = True , date_unit = 'ms' ,
1099
1131
default_handler = None , lines = False ):
1100
1132
"""
@@ -1129,10 +1161,17 @@ def to_json(self, path_or_buf=None, orient=None, date_format='epoch',
1129
1161
- index : dict like {index -> {column -> value}}
1130
1162
- columns : dict like {column -> {index -> value}}
1131
1163
- 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'``.
1132
1167
1133
- date_format : {'epoch', 'iso'}
1168
+ .. versionchanged:: 0.20.0
1169
+
1170
+ date_format : {None, 'epoch', 'iso'}
1134
1171
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'`.
1136
1175
double_precision : The number of decimal places to use when encoding
1137
1176
floating point values, default 10.
1138
1177
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',
1151
1190
1152
1191
.. versionadded:: 0.19.0
1153
1192
1154
-
1155
1193
Returns
1156
1194
-------
1157
1195
same type as input object with filtered info axis
1158
1196
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"}]}'
1159
1233
"""
1160
1234
1161
1235
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'
1162
1240
return json .to_json (path_or_buf = path_or_buf , obj = self , orient = orient ,
1163
1241
date_format = date_format ,
1164
1242
double_precision = double_precision ,
0 commit comments