a
    é´«j -  ã                   @  s^  d Z ddlmZ ddlmZmZmZ ddlZddlm	Z	 ddl
mZ ddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZmZmZmZ ddlmZmZmZmZ ddlm Z  ddl!m"  m#Z$ ddl%m&Z& erúddl'm(Z(m)Z) ddlm*Z* ddl+m,Z, dZ-dddœdd„Z.dd„ Z/ddœdd„Z0ddœdd „Z1d,d"d#d$d#dd%œd&d'„Z2d#d(d)œd*d+„Z3dS )-zH
Table Schema builders

https://specs.frictionlessdata.io/table-schema/
é    )Úannotations)ÚTYPE_CHECKINGÚAnyÚcastN)Úlib)Úujson_loads)Ú	timezones)Úfreq_to_period_freqstr)Úfind_stack_level)Ú	_registry)Úis_bool_dtypeÚis_integer_dtypeÚis_numeric_dtypeÚis_string_dtype)ÚCategoricalDtypeÚDatetimeTZDtypeÚExtensionDtypeÚPeriodDtype)Ú	DataFrame)Ú	to_offset)ÚDtypeObjÚJSONSerializable)ÚSeries)Ú
MultiIndexz1.4.0r   Ústr)ÚxÚreturnc                 C  sf   t | ƒrdS t| ƒrdS t| ƒr$dS t | d¡s>t| ttfƒrBdS t | d¡rRdS t| ƒr^dS d	S d
S )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ÚMÚdatetimeÚmÚdurationÚstringÚanyN)	r   r   r   r   Zis_np_dtypeÚ
isinstancer   r   r   )r   © r'   ú[/var/www/html/laksyashrimp/venv/lib/python3.9/site-packages/pandas/io/json/_table_schema.pyÚas_json_table_type5   s    r)   c                 C  s®   t j| jjŽ rr| jj}t|ƒdkr@| jjdkr@tjdtƒ d� n.t|ƒdkrnt	dd„ |D ƒƒrntjdtƒ d� | S |  
¡ } | jjdkršt  | jj¡| j_n| jjp¤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.)Ú
stacklevelc                 s  s   | ]}|  d ¡V  qdS ©Zlevel_N©Ú
startswith©Ú.0r   r'   r'   r(   Ú	<genexpr>l   ó    z$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ÚnlevelsZfill_missing_names)ÚdataZnmsr'   r'   r(   Úset_default_namesc   s$    þþr=   zdict[str, JSONSerializable])r   c                 C  s¸   | j }| jd u rd}n| j}|t|ƒdœ}t|tƒrZ|j}|j}dt|ƒi|d< ||d< nZt|tƒrr|j	j
|d< nBt|tƒr t |j¡r’d|d< q´|jj|d< nt|tƒr´|j|d	< |S )
NÚvalues)r7   ÚtypeÚenumÚconstraintsÚorderedÚfreqÚUTCÚtzÚextDtype)Údtyper7   r)   r&   r   Ú
categoriesrB   Úlistr   rC   Zfreqstrr   r   Zis_utcrE   Úzoner   )ZarrrG   r7   ÚfieldZcatsrB   r'   r'   r(   Ú!convert_pandas_type_to_json_field{   s*    
þ






rL   zstr | CategoricalDtypec                 C  s*  | d }|dkr|   dd¡S |dkr0|   dd¡S |dkrD|   dd¡S |d	krX|   dd
¡S |dkrddS |dkrÆ|   d¡r†d| d › d�S |   d¡rÀt| d ƒ}|j|j }}t||ƒ}d|› d�S dS nR|dk�rd| v � rüd| v � rüt| d d | d d�S d| v �rt | d ¡S dS td|› �ƒ‚dS )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, categories_dtype=object)

    >>> 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$   rF   Nr   Zint64r   Zfloat64r   Úboolr#   Útimedelta64r!   rE   zdatetime64[ns, ú]rC   zperiod[zdatetime64[ns]r%   rA   rB   r@   )rH   rB   Úobjectz#Unsupported or invalid field type: )	Úgetr   Únr7   r	   r   ÚregistryÚfindÚ
ValueError)rK   ÚtypÚoffsetZfreq_nZ	freq_namerC   r'   r'   r(   Ú!convert_json_field_to_pandas_type›   s:    )



ÿ
rX   TzDataFrame | SeriesrM   zbool | None)r<   r+   Úprimary_keyÚversionr   c                 C  s"  |du rt | ƒ} i }g }|r~| jjdkrntd| jƒ| _t| jj| jjƒD ]"\}}t|ƒ}||d< | |¡ qHn| t| jƒ¡ | j	dkrª|  
¡ D ]\}	}
| t|
ƒ¡ q�n| t| ƒ¡ ||d< |rþ| jjrþ|du rþ| jjdkrð| jjg|d< n| jj|d< n|du�r||d< |�rt|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*   r   r7   ÚfieldsNÚ
primaryKeyZpandas_version)r=   r+   r;   r   ÚzipZlevelsr5   rL   ÚappendÚndimÚitemsZ	is_uniquer7   ÚTABLE_SCHEMA_VERSION)r<   r+   rY   rZ   Úschemar[   Úlevelr7   Z	new_fieldÚcolumnÚsr'   r'   r(   Úbuild_table_schemaè   s4    8

rf   r   )Úprecise_floatr   c                 C  sÈ   t | |d�}dd„ |d d D ƒ}t|d |d�| }dd	„ |d d D ƒ}d
| ¡ v r`tdƒ‚| |¡}d|d v rÄ| |d d ¡}t|jjƒdkr®|jj	dkrÄd|j_	ndd„ |jjD ƒ|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
    )rg   c                 S  s   g | ]}|d  ‘qS ©r7   r'   ©r1   rK   r'   r'   r(   Ú
<listcomp>i  r3   z&parse_table_schema.<locals>.<listcomp>rb   r[   r<   )Úcolumnsc                 S  s   i | ]}|d  t |ƒ“qS rh   )rX   ri   r'   r'   r(   Ú
<dictcomp>l  s   ÿz&parse_table_schema.<locals>.<dictcomp>rN   z<table="orient" can not yet read ISO-formatted Timedelta datar\   r*   r+   Nc                 S  s   g | ]}|  d ¡rdn|‘qS r-   r.   r0   r'   r'   r(   rj     s   )
r   r   r>   ÚNotImplementedErrorZastypeZ	set_indexr6   r+   r5   r7   )Újsonrg   ÚtableZ	col_orderZdfZdtypesr'   r'   r(   Úparse_table_schemaD  s(    $
þÿ

ÿ
rp   )TNT)4Ú__doc__Ú
__future__r   Útypingr   r   r   r8   Zpandas._libsr   Zpandas._libs.jsonr   Zpandas._libs.tslibsr   Zpandas._libs.tslibs.dtypesr	   Zpandas.util._exceptionsr
   Zpandas.core.dtypes.baser   rS   Zpandas.core.dtypes.commonr   r   r   r   Zpandas.core.dtypes.dtypesr   r   r   r   Zpandasr   Zpandas.core.commonÚcoreÚcommonr4   Zpandas.tseries.frequenciesr   Zpandas._typingr   r   r   Zpandas.core.indexes.multir   ra   r)   r=   rL   rX   rf   rp   r'   r'   r'   r(   Ú<module>   s8   . O   ü\