1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
U
¬ý°d@-ã@s>dZddlmZddlmZmZmZddlZddlm    Z    ddl
m Z ddl m Z mZddlmZdd    lmZdd
lmZmZmZmZmZmZmZmZmZmZdd lm Z dd l!m"Z"ddl#m$m%Z&erâdd l!m'Z'ddl(m)Z)dZ*dddœdd„Z+dd„Z,ddœdd„Z-ddœdd„Z.d'dd d!d dd"œd#d$„Z/d%d&„Z0dS)(zH
Table Schema builders
 
https://specs.frictionlessdata.io/table-schema/
é)Ú annotations)Ú TYPE_CHECKINGÚAnyÚcastN)Úloads)Ú    timezones)ÚDtypeObjÚJSONSerializable)Úfind_stack_level)Ú    _registry)
Ú is_bool_dtypeÚis_categorical_dtypeÚis_datetime64_dtypeÚis_datetime64tz_dtypeÚis_extension_array_dtypeÚis_integer_dtypeÚis_numeric_dtypeÚis_period_dtypeÚis_string_dtypeÚis_timedelta64_dtype)ÚCategoricalDtype)Ú    DataFrame)ÚSeries)Ú
MultiIndexz1.4.0rÚstr)ÚxÚreturncCsxt|ƒr dSt|ƒrdSt|ƒr$dSt|ƒs<t|ƒs<t|ƒr@dSt|ƒrLdSt|ƒrXdSt|ƒrddSt    |ƒrpdSdSdS)    aœ
    Convert a NumPy / pandas type to its corresponding json_table.
 
    Parameters
    ----------
    x : np.dtype or ExtensionDtype
 
    Returns
    -------
    str
        the Table Schema data types
 
    Notes
    -----
    This table shows the relationship between NumPy / pandas dtypes,
    and Table Schema dtypes.
 
    ==============  =================
    Pandas type     Table Schema type
    ==============  =================
    int64           integer
    float64         number
    bool            boolean
    datetime64[ns]  datetime
    timedelta64[ns] duration
    object          str
    categorical     any
    =============== =================
    ÚintegerÚbooleanÚnumberÚdatetimeÚdurationÚanyÚstringN)
rr rrrrrr rr)r©r$úSd:\z\workplace\vscode\pyvenv\venv\Lib\site-packages\pandas/io/json/_table_schema.pyÚas_json_table_type1s"r&cCs®tj|jjŽrr|jj}t|ƒdkr@|jjdkr@tjdtƒdn.t|ƒdkrnt    dd„|Dƒƒrntjdtƒd|S| 
¡}|jj dkršt  |jj¡|j_n|jjp¤d|j_|S)z?Sets index names to 'index' for regular, or 'level_x' for MultiéÚindexz-Index name of 'index' is not round-trippable.)Ú
stacklevelcss|]}| d¡VqdS©Zlevel_N©Ú
startswith©Ú.0rr$r$r%Ú    <genexpr>lsz$set_default_names.<locals>.<genexpr>z<Index names beginning with 'level_' are not round-trippable.) ÚcomZ all_not_noner(ÚnamesÚlenÚnameÚwarningsÚwarnr
r"ÚcopyÚnlevelsZfill_missing_names)ÚdataZnmsr$r$r%Úset_default_namescs$þþ r9zdict[str, JSONSerializable])rcCs°|j}|jdkrd}n|j}|t|ƒdœ}t|ƒrX|j}|j}dt|ƒi|d<||d<nTt|ƒrn|jj    |d<n>t
|ƒršt   |j ¡rŒd|d<q¬|j j|d<nt|ƒr¬|j|d    <|S)
NÚvalues)r3ÚtypeÚenumÚ constraintsÚorderedÚfreqÚUTCÚtzÚextDtype)Údtyper3r&r Ú
categoriesr>Úlistrr?ZfreqstrrrZis_utcrAÚzoner)ZarrrCr3ÚfieldZcatsr>r$r$r%Ú!convert_pandas_type_to_json_field{s*
þ
 
 
rHzstr | CategoricalDtypecCsú|d}|dkrdS|dkr(| dd¡S|dkr<| dd¡S|d    krP| dd
¡S|d kr\d S|d krž| d¡r~d|d›dS| d¡r˜d|d›dSdSnJ|dkrèd|krÎd|krÎt|dd|ddSd|krät |d¡SdStd|›ƒ‚dS)a÷
    Converts a JSON field descriptor into its corresponding NumPy / pandas type
 
    Parameters
    ----------
    field
        A JSON field descriptor
 
    Returns
    -------
    dtype
 
    Raises
    ------
    ValueError
        If the type of the provided field is unknown or currently unsupported
 
    Examples
    --------
    >>> convert_json_field_to_pandas_type({"name": "an_int", "type": "integer"})
    'int64'
 
    >>> convert_json_field_to_pandas_type(
    ...     {
    ...         "name": "a_categorical",
    ...         "type": "any",
    ...         "constraints": {"enum": ["a", "b", "c"]},
    ...         "ordered": True,
    ...     }
    ... )
    CategoricalDtype(categories=['a', 'b', 'c'], ordered=True)
 
    >>> convert_json_field_to_pandas_type({"name": "a_datetime", "type": "datetime"})
    'datetime64[ns]'
 
    >>> convert_json_field_to_pandas_type(
    ...     {"name": "a_datetime_with_tz", "type": "datetime", "tz": "US/Central"}
    ... )
    'datetime64[ns, US/Central]'
    r;r#ÚobjectrrBÚint64rÚfloat64rÚboolr!Ú timedelta64r rAzdatetime64[ns, ú]r?zperiod[zdatetime64[ns]r"r=r>r<)rDr>z#Unsupported or invalid field type: N)ÚgetrÚregistryÚfindÚ
ValueError)rGÚtypr$r$r%Ú!convert_json_field_to_pandas_typešs6)   
 
 
ÿrTTzDataFrame | SeriesrLz bool | None)r8r(Ú primary_keyÚversionrc Cs"|dkrt|ƒ}i}g}|r~|jjdkrntd|jƒ|_t|jj|jjƒD]"\}}t|ƒ}||d<| |¡qHn| t|jƒ¡|j    dkrª| 
¡D]\}    }
| t|
ƒ¡qn| t|ƒ¡||d<|rþ|jj rþ|dkrþ|jjdkrð|jj g|d<n |jj|d<n|dk    r||d<|rt |d<|S)    a‚
    Create a Table schema from ``data``.
 
    Parameters
    ----------
    data : Series, DataFrame
    index : bool, default True
        Whether to include ``data.index`` in the schema.
    primary_key : bool or None, default True
        Column names to designate as the primary key.
        The default `None` will set `'primaryKey'` to the index
        level or levels if the index is unique.
    version : bool, default True
        Whether to include a field `pandas_version` with the version
        of pandas that last revised the table schema. This version
        can be different from the installed pandas version.
 
    Returns
    -------
    dict
 
    Notes
    -----
    See `Table Schema
    <https://pandas.pydata.org/docs/user_guide/io.html#table-schema>`__ for
    conversion types.
    Timedeltas as converted to ISO8601 duration format with
    9 decimal places after the seconds field for nanosecond precision.
 
    Categoricals are converted to the `any` dtype, and use the `enum` field
    constraint to list the allowed values. The `ordered` attribute is included
    in an `ordered` field.
 
    Examples
    --------
    >>> from pandas.io.json._table_schema import build_table_schema
    >>> df = pd.DataFrame(
    ...     {'A': [1, 2, 3],
    ...      'B': ['a', 'b', 'c'],
    ...      'C': pd.date_range('2016-01-01', freq='d', periods=3),
    ...     }, index=pd.Index(range(3), name='idx'))
    >>> build_table_schema(df)
    {'fields': [{'name': 'idx', 'type': 'integer'}, {'name': 'A', 'type': 'integer'}, {'name': 'B', 'type': 'string'}, {'name': 'C', 'type': 'datetime'}], 'primaryKey': ['idx'], 'pandas_version': '1.4.0'}
    Tr'rr3ÚfieldsNÚ
primaryKeyZpandas_version)r9r(r7rÚzipÚlevelsr1rHÚappendÚndimÚitemsZ    is_uniquer3ÚTABLE_SCHEMA_VERSION) r8r(rUrVÚschemarWÚlevelr3Z    new_fieldÚcolumnÚsr$r$r%Úbuild_table_schemaãs48 
 
rccCsÈt||d}dd„|ddDƒ}t|d|d|}dd    „|ddDƒ}d
| ¡kr`td ƒ‚| |¡}d |dkrÄ| |dd ¡}t|jjƒd kr®|jj    dkrÄd|j_    ndd„|jjDƒ|j_|S)a 
    Builds a DataFrame from a given schema
 
    Parameters
    ----------
    json :
        A JSON table schema
    precise_float : bool
        Flag controlling precision when decoding string to double values, as
        dictated by ``read_json``
 
    Returns
    -------
    df : DataFrame
 
    Raises
    ------
    NotImplementedError
        If the JSON table schema contains either timezone or timedelta data
 
    Notes
    -----
        Because :func:`DataFrame.to_json` uses the string 'index' to denote a
        name-less :class:`Index`, this function sets the name of the returned
        :class:`DataFrame` to ``None`` when said string is encountered with a
        normal :class:`Index`. For a :class:`MultiIndex`, the same limitation
        applies to any strings beginning with 'level_'. Therefore, an
        :class:`Index` name of 'index'  and :class:`MultiIndex` names starting
        with 'level_' are not supported.
 
    See Also
    --------
    build_table_schema : Inverse function.
    pandas.read_json
    )Ú precise_floatcSsg|] }|d‘qS©r3r$©r.rGr$r$r%Ú
<listcomp>dsz&parse_table_schema.<locals>.<listcomp>r_rWr8)ÚcolumnscSsi|]}|dt|ƒ“qSre)rTrfr$r$r%Ú
<dictcomp>gsÿz&parse_table_schema.<locals>.<dictcomp>rMz<table="orient" can not yet read ISO-formatted Timedelta datarXr'r(NcSsg|]}| d¡rdn|‘qSr*r+r-r$r$r%rgzs)
rrr:ÚNotImplementedErrorZastypeZ    set_indexr2r(r1r3)ÚjsonrdÚtableZ    col_orderZdfZdtypesr$r$r%Úparse_table_schema?s($ 
þ ÿ
 
ÿ
rm)TNT)1Ú__doc__Ú
__future__rÚtypingrrrr4Zpandas._libs.jsonrZpandas._libs.tslibsrZpandas._typingrr    Zpandas.util._exceptionsr
Zpandas.core.dtypes.baser rPZpandas.core.dtypes.commonr r rrrrrrrrZpandas.core.dtypes.dtypesrZpandasrZpandas.core.commonÚcoreÚcommonr0rZpandas.core.indexes.multirr^r&r9rHrTrcrmr$r$r$r%Ú<module>s2     0    2Kü\