
    Q/Ph                      Z   d Z ddlZddlZddlZddlZddlmZ ddlmZm	Z	 ddl
ZddlmZ deddfdZd	edefd
ZdededefdZdedefdZdedej        fdZdej        dej        fdZddej        dedej        fdZdZdej        defdZddededefdZdede	e         defdZdS ) zUtils for pandas DataFrames.    N)Path)AnyOptional)hash_pandas_object	extensionreturnc                 6    t          j        d|  d           dS )zyWarn the user when an extension is not supported.

    Args:
        extension: The extension that is not supported.
    z3There was an attempt to read a file with extension a[  , we assume it to be in CSV format.
To prevent this warning from showing up, please rename the file to any of the extensions supported by pandas
(docs: https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html)
If you think this extension should be supported, please report this as an issue:
https://github.com/ydataai/ydata-profiling/issuesN)warningswarn)r   s    _/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/ydata_profiling/utils/dataframe.py	warn_readr      s8     M	5	 	5 	5 	5        file_extensionc                 .    |                                  dv S )uB  Determine if the given file extension indicates a compression format that pandas can handle automatically.

    Args:
        file_extension (str): the file extension to test

    Returns:
        bool: True if the extension indicates a compression format that pandas handles automatically and False otherwise

    Notes:
        Pandas can handle on the fly decompression from the following extensions: ‘.bz2’, ‘.gz’, ‘.zip’, or ‘.xz’
        (otherwise no decompression). If using ‘.zip’, the ZIP file must contain exactly one data file to be read in.
    )z.bz2z.gzz.xzz.zip)lower)r   s    r   is_supported_compressionr      s     !!%CCCr   textsuffixc                 d    |r-|                      |          r| dt          |                    n| S )a  Removes the given suffix from the given string.

    Args:
        text (str): the string to remove the suffix from
        suffix (str): the suffix to remove from the string

    Returns:
        str: the string with the suffix removed, if the string ends with the suffix, otherwise the unmodified string

    Notes:
        In python 3.9+, there is a built-in string method called removesuffix() that can serve this purpose.
    N)endswithlen)r   r   s     r   remove_suffixr   ,   s6     $*MdmmF.C.CM43v;;,Mr   	file_namec                     | j                                         }t          |          rAt          t	          t          |                                           |                    j         n|S )a  Returns the uncompressed extension of the given file name.

    Args:
        file_name (Path): the file name to get the uncompressed extension of

    Returns:
        str: the uncompressed extension, or the original extension if pandas doesn't handle it automatically
    )r   r   r   r   r   str)r   r   s     r   uncompressed_extensionr   <   s^      &&((I $I..	]3y>>//119==>>EEr   c                    t          |           }|dk    r#t          j        t          |                     }n|dk    r%t          j        t          |           d          }n_|dk    r#t          j        t          |                     }n6|dk    r%t          j        t          |           d          }n|d	v r"t          j        t          |                     }n|d
v r"t          j        t          |                     }n|dv r"t          j        t          |                     }n|dk    r"t          j	        t          |                     }nq|dv r"t          j
        t          |                     }nK|dk    rt          d          |dk    rt          |           t          j        t          |                     }|S )a  Read DataFrame based on the file extension. This function is used when the file is in a standard format.
    Various file types are supported (.csv, .json, .jsonl, .data, .tsv, .xls, .xlsx, .xpt, .sas7bdat, .parquet)

    Args:
        file_name: the file to read

    Returns:
        DataFrame

    Notes:
        This function is based on pandas IO tools:
        https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html
        https://pandas.pydata.org/pandas-docs/stable/reference/io.html

        This function is not intended to be flexible or complete. The main use case is to be able to read files without
        user input, which is currently used in the editor integration. For more advanced use cases, the user should load
        the DataFrame in code.
    z.jsonz.jsonlT)linesz.dtaz.tsv	)sep)z.xlsz.xlsx)z.hdfz.h5)z	.sas7bdatz.xptz.parquet)z.pklz.picklez.tarzTtar compression is not supported directly by pandas, please use the 'tarfile' modulez.csv)r   pd	read_jsonr   
read_stataread_csv
read_excelread_hdfread_sasread_parquetread_pickle
ValueErrorr   )r   r   dfs      r   read_pandasr,   M   s   & 'y11IG\#i..))	h		\#i..555	f		]3y>>**	f		[YT222	'	'	']3y>>**	o	%	%[Y((	+	+	+[Y((	j	 	 _S^^,,	)	)	)^C	NN++	f		b
 
 	
 i   [Y((Ir   r+   c                     |                      ddid           d| j        j        v r d | j        j        D             | j        _        | S )aL  If the DataFrame contains a column or index named `index`, this will produce errors. We rename the {index,column}
    to be `df_index`.

    Args:
        df: DataFrame to process.

    Returns:
        The DataFrame with {index,column} `index` replaced by `df_index`, unchanged if the DataFrame does not contain such a string.
    indexdf_indexTcolumnsinplacec                 "    g | ]}|d k    r|ndS )r.   r/    ).0xs     r   
<listcomp>z rename_index.<locals>.<listcomp>   s$    TTTqG||!!TTTr   )renamer.   names)r+   s    r   rename_indexr:      sN     IIw
+TI:::"(.  TTRX^TTTIr   typesc                    t           t          t          g| j        D ]}| |                                                             fd          }|                                rt          j        | |                                         	                                          }|
                    |dz             }t          |          }|                     |gd           t          j        | |gd          } | S )a  Expand non-nested lists, dicts and tuples in a DataFrame into columns with a prefix.

    Args:
        types: list of types to expand (Default: list, dict, tuple)
        df: DataFrame

    Returns:
        DataFrame with the dict values as series, identifier by the combination of the series and dict keys.

    Notes:
        TODO: allow for list expansion by duplicating rows.
        TODO: allow for expansion of nested data structures.
    Nc                 ^    t          |           v ot          fd| D                        S )Nc              3   :   K   | ]}t          |          v V  d S N)type)r5   yr;   s     r   	<genexpr>z1expand_mixed.<locals>.<lambda>.<locals>.<genexpr>   s.      7T7TQQ58H7T7T7T7T7T7Tr   )r@   any)r6   r;   s    r   <lambda>zexpand_mixed.<locals>.<lambda>   s8    477e+TC7T7T7T7TRS7T7T7T4T4T0T r   _Tr0      )axis)listdicttupler1   dropnamapallr!   	DataFrametolist
add_prefixexpand_mixeddropconcat)r+   r;   column_namenon_nested_enumerationexpandeds    `   r   rQ   rQ      s     }tU#z 3 3 {OVXXSTTTTUU 	 "%%'' 	3|B{O$:$:$<$<$C$C$E$EFFH**;+<==H $H--H GG[M4G888B>222BIr   z2@c                    d                     t          |           j                            t                              }t          j        |                    d                                                    }t           | S )zHash a DataFrame (implementation might change in the future)

    Args:
        df: the DataFrame

    Returns:
        The DataFrame's hash
    
zutf-8)
joinr   valuesastyper   hashlibsha256encode	hexdigestHASH_PREFIX)r+   hash_valuesdigests      r   hash_dataframerc      si     )).r229@@EEFFK^K..w7788BBDDF#6###r   Fvalueallow_unicodec                 j   t          |           } |rt          j        d|           } n<t          j        d|                               dd                              d          } t          j        dd|                                           } t          j        dd|                               d	          S )
ai  
    Taken from https://github.com/django/django/blob/master/django/utils/text.py
    Convert to ASCII if 'allow_unicode' is False. Convert spaces or repeated
    dashes to single dashes. Remove characters that aren't alphanumerics,
    underscores, or hyphens. Convert to lowercase. Also strip leading and
    trailing whitespace, dashes, and underscores.
    NFKCNFKDasciiignorez[^\w\s-] z[-\s]+-z-_)	r   unicodedata	normalizer^   decoderesubr   strip)rd   re   s     r   slugifyrs      s     JJE 
%fe44 !&%00VGX&&VG__ 	
 F;EKKMM22E6)S%((..t444r   dctsortc                 r   || S |                                 }|                    d          r2t          t          |                                 d                     } nW|                    d          r3t          t          |                                 d d                    } nt          d          | S )	Nascc                 6    | d                                          S Nr   casefoldr6   s    r   rD   z#sort_column_names.<locals>.<lambda>       QqT]]__ r   )keydescc                 6    | d                                          S ry   rz   r|   s    r   rD   z#sort_column_names.<locals>.<lambda>   r}   r   T)r~   reversez3"sort" should be "ascending", "descending" or None.)r   
startswithrI   sorteditemsr*   )rt   ru   s     r   sort_column_namesr      s    |
::<<Du P6#))+++D+DEEEFF		 	  P6#))+++D+DdSSSTTNOOOJr   r?   )F)__doc__r\   rp   rm   r
   pathlibr   typingr   r   pandasr!   pandas.core.util.hashingr   r   r   boolr   r   r   rN   r,   r:   rQ   r`   rc   rs   rI   r   r4   r   r   <module>r      s$   " "  				                                7 7 7 7 7 7     DS DT D D D D N NS NS N N N N d s    "/4 /BL / / / /dR\ bl    "% %R\ %# % % % % %R $r| $ $ $ $ $$5 53 5t 5 5 5 5 5*4 x}       r   