
    .ig                       U d dl mZ d dlZd dlZd dlZd dlmZmZmZm	Z	m
Z
mZ d dlZd dlZd dlmZ d dlmZmZmZmZmZmZ d dlmZ d dlmZmZmZmZm Z m!Z!m"Z" d dl#m$Z$ erd d	l%m&Z&m'Z'm(Z( d d
l)m*Z* d dl+Z,d dl-m.Z/ d dl0m1Z1 d dl2m3Z3m4Z4 d dl5m6Z6 d dl7m8Z8 d dl9m:Z: d dl;m<Z<m=Z=m>Z> d dl?m@Z@ d dlAmBZBmCZCmDZDmEZE  e
de8      ZFeDZGdeHd<   eDZIdeHd<   eeeJgef   ZKdeHd<   eJZLdeHd<   ej                  ej                  ej                  hZPdZQ ej                  eQej                        ZTdZU ej                  eUej                        ZVe	d   ZWdeHd<   dd d!ZXd"d#d$d%d&d'd(d)d*d+d,
ZYd-eHd.<   ej                  j                         Z[	  e!e      Z\	 dd0Z]	 	 	 	 	 	 dd2Z^	 	 	 	 	 	 	 	 dd3Z_	 	 	 	 	 	 	 	 	 	 dd4Z` ej                  d56      dd7       Zb ej                  d56      dd8       Zc	 	 	 	 	 	 	 	 dd9Zd	 	 	 	 	 	 	 	 dd:Ze	 	 	 	 dd;Zfd<Zgd=d>	 	 	 	 	 	 	 	 	 dd?Zhej                  j                         d@k\  rddAZinddBZiddCZj	 	 	 	 	 	 ddDZk ej                  d56      ddE       Zlej                  j                  Znenj                  dFenj                  dGiZqdHeHdI<   enj                  dJdKdLdMenj                  dNdOdPdMenj                  dQdRdSdMenj                  dTdUdVdMenj                  dWdXdYdMenj                  dZd[d\dMenj                  d]d^d_dMenj                  d`dadbdMenj                  dcdddedMenj                  dfdgdhdMenj                  didjd/dMiZ}dkeHdl<   	 	 	 	 	 	 	 	 	 	 ddmZ~	 	 	 	 	 	 	 	 ddnZddoZej                  dpfej                  dqfej                  efej                  dpfej                  efej                  dpfej                  efej                  efej                  efdr	ZdseHdt<   	 	 	 	 	 	 	 	 dduZeeedvdwZdxeHdy<   ddzZ	 	 	 	 	 	 	 	 dd{Zdd|Zdd}Z G d~ ded1ef         ZddZ	 	 	 	 	 	 	 	 	 	 ddZy)    )annotationsN)TYPE_CHECKINGAnyCallableLiteralTypeVarcast)EagerSeriesNamespace)MS_PER_SECONDNS_PER_MICROSECONDNS_PER_MILLISECONDNS_PER_SECONDSECONDS_PER_DAYUS_PER_SECOND)issue_warning)ImplementationVersion_DeferredIterablecheck_columns_existisinstance_or_issubclassparse_versionrequires)
ShapeError)IterableIteratorMapping)
ModuleType)DtypeBaseMaskedDtype)	TypeAliasTypeIs)IntervalUnit)PandasLikeExprPandasLikeSeries)NativeDataFrameTNativeNDFrameTNativeSeriesT)DType)DTypeBackend	IntoDTypeTimeUnit_1DArrayExprT)boundr!   UnitCurrent
UnitTargetBinOpBroadcastIntoRhsa  ^
    datetime64\[
        (?P<time_unit>s|ms|us|ns)                 # Match time unit: s, ms, us, or ns
        (?:,                                      # Begin non-capturing group for optional timezone
            \s*                                   # Optional whitespace after comma
            (?P<time_zone>                        # Start named group for timezone
                [a-zA-Z\/]+                       # Match timezone name, e.g., UTC, America/New_York
                (?:[+-]\d{2}:\d{2})?              # Optional offset in format +HH:MM or -HH:MM
                |                                 # OR
                pytz\.FixedOffset\(\d+\)          # Match pytz.FixedOffset with integer offset in parentheses
            )                                     # End time_zone group
        )?                                        # End optional timezone group
    \]                                            # Closing bracket for datetime64
$z^
    timedelta64\[
        (?P<time_unit>s|ms|us|ns)                 # Match time unit: s, ms, us, or ns
    \]                                            # Closing bracket for timedelta64
$)yearquartermonthweekdayhourminutesecondmillisecondmicrosecond
nanosecondNativeIntervalUnitDmin)dmr5   r6   r7   r9   r:   r;   r<   r=   r>   r?   )
yqmorC   hrD   smsusnsz)Mapping[IntervalUnit, NativeIntervalUnit]
UNITS_DICTboolc                F    | t         j                  t         j                  hv S N)r   PANDASMODINimplementations    X/opt/house_gps_flutter/.venv/lib/python3.12/site-packages/narwhals/_pandas_like/utils.pyis_pandas_or_modinrV      s    n33^5I5IJJJ    r&   c                X   ddl m} | j                  j                  }| j                  r=t        ||      r1|j                  s%| j                  j                  d   |j                  fS t        ||      r|j                  r%| j                  |j                  j                  d   fS |j                  j                  |ur.| j                  t        |j                  ||j                        fS | j                  |j                  fS t        |t              rd}t        |      | j                  |fS )zValidate RHS of binary operation.

    If the comparison isn't supported, return `NotImplemented` so that the
    "right-hand-side" operation (e.g. `__radd__`) can be tried.
    r   r%   rS   z$Expected Series or scalar, got list.)narwhals._pandas_like.seriesr&   nativeindex
_broadcast
isinstanceiloc	set_index_implementationlist	TypeError)lhsrhsr&   	lhs_indexmsgs        rU   align_and_extract_nativerg      s     >

  I
~~*S*:;CNNzzq!3::--#'(>>JJ

 233::9,

#**i@S@ST  

CJJ''#t4n ::s?rW   c                  t        ||j                         j                        r.t        |      x}t        |       x}k7  rd| d| }t	        |      |t
        j                  u r| j                  d      } || _        | S |t
        j                  u r0d|j                         cxk  rdk  rn n| j                  |dd      S | j                  |d	      S )
z}Wrapper around pandas' set_axis to set object index.

    We can set `copy` / `inplace` based on implementation/version.
    zExpected object of length z, got length: F)deep         r   )axiscopy)ro   )r]   to_native_namespaceIndexlenr   r   CUDFrp   r[   rQ   _backend_versionset_axis)objr[   rT   expected_len
actual_lenrf   s         rU   r_   r_      s     %;;=CCDE
"C
 *J" +<.zlSo,,,hhEh"	
....113:d:||E|66<<A<&&rW   c                   |t         j                  u r*|j                         dk\  r | j                  |i |ddi}n | j                  |i |ddd}t	        d|      S )zXWrapper around pandas' rename so that we can set `copy` based on implementation/version.rm   inplaceF)rp   r{   r(   )r   rQ   ru   renamer	   )rw   rT   argskwargsresults        rU   r|   r|      sg     ...'')T1T;V;U;TGVG%G &))rW      )maxsizec                T    t        | t        j                        xs t        |       dv S )zR*There is no problem which can't be solved by adding an extra string type* pandas.>   string[python]string[pyarrow_numpy]<StringDtype(na_value=nan)>strstring)r]   pdStringDtyper   native_dtypes    rU   is_dtype_non_pyarrow_stringr      s.    
 lBNN3 s<7H M 8 rW   c                F   t        |       }|j                  }|dv r|j                         S |dv r|j                         S |dv r|j	                         S |dv r|j                         S |dv r|j                         S |dv r|j                         S |dv r|j                         S |dv r|j                         S |d	v r|j                         S |d
v r|j                         S t        |       r|j                         S |dv r|j                         S t        j!                  |      x}r4|j#                  d      }|j#                  d      }|j%                  ||      S t&        j!                  |      x}r"|j#                  d      }|j)                  |      S |j+                         S )N>   Int64int64>   Int32int32>   Int16int16>   Int8int8>   UInt64uint64>   UInt32uint32>   UInt16uint16>   UInt8uint8>   Float64float64>   Float32float32>   rN   boolean	time_unit	time_zone)r   dtypesr   r   r   r   r   r   r   r   r   r   r   StringBooleanPATTERN_PD_DATETIMEmatchgroupDatetimePATTERN_PD_DURATIONDurationUnknown)r   versiondtyper   match_dt_time_unitdt_time_zonedu_time_units           rU   #non_object_native_to_narwhals_dtyper      s   E^^F""||~""||~""||~  {{}$$}}$$}}$$}}""||~&&~~&&~~"<0}}##~~$**511v1!'k!:#)<<#<|\::$**511v1!'k!:|,,>>rW   c                   |j                   }|t        j                  u r|j                         S t        j
                  j                  j                  }| dn || j                  d      d      }|dk(  r|j                         S |dk(  r"|t        j                  ur|j                         S |dk(  r|j                         S |j                         S )Nemptyd   T)skipnar   )r   r   rt   r   r   apitypesinfer_dtypeheadr   V1Object)seriesr   rT   r   inferinferred_dtypes         rU   object_native_to_narwhals_dtyper      s     ^^F,,, }}FFLL$$E &WE&++c:JSW4XN!}} WGJJ%>}} }}==?rW   c                0   |j                   }|t        j                  u r|j                         S | j                  rM|t
        j                  u rt        |       n| j                  j                  }|j                  t        |            S |j                         S rP   )r   r   r   Categoricalorderedr   rt   _cudf_categorical_to_list
categoriesto_listEnumr   )r   r   rT   r   	into_iters        rU   $native_categorical_to_narwhals_dtyper     s     ^^F'**!!## !4!44 &l3((00 	
 {{,Y788rW   c                     d fd}|S )Nc                 T     j                   j                         j                         S rP   )r   to_arrow	to_pylistr   s   rU   fnz%_cudf_categorical_to_list.<locals>.fn*  s!    &&//1;;==rW   )returnz	list[Any] )r   r   s   ` rU   r   r   $  s    > IrW   )ra   structdecimalF)allow_objectc                  t        |       }t        |       s|j                  t              r8ddlm} t        | d      r| j                         }n| j                  } |||      S |dk(  rt        | ||      S |dk7  rt        | |      S |t        j                  u r|j                  j                         S |rt        d ||      S d}t!        |      )Nr   )native_to_narwhals_dtyper   categoryobjectz;Unreachable code, object dtype should be handled separately)r   is_dtype_pyarrow
startswithCUDF_BASE_DTYPE_PREFIXnarwhals._arrow.utilsr   hasattrr   pyarrow_dtyper   r   r   DASKr   r   r   AssertionError)r   r   rT   r   	str_dtypearrow_native_to_narwhals_dtypepa_dtyperf   s           rU   r   r   3  s     L!I%)=)=>T)U	
 <,$0$9$9$;H#11H-h@@J3L'>ZZH2<II,,, ~~$$&&.tWnMME  
rW   )rk      c                    t               }t        | t        j                  j                  j
                        xr t        | d|      du S )z/Return `True` if `dtype` is `"numpy_nullable"`.baseN)r   r]   r   r   
extensionsExtensionDtypegetattr)r   sentinels     rU   is_dtype_numpy_nullabler   X  s@     8ubff//>>? 9vx0D8	
rW   c                    t        | t        j                  j                  j                        rddlm} t        | |      S y)Nr   r   F)r]   r   r   r   r   pandas.core.arrays.maskedr    )r   OldBaseMaskedDtypes     rU   r   r   c  s6     eRVV..==> e%788rW   c                ^    |t         j                  u ryt        |       ryt        |       rdS dS )zjGet dtype backend for pandas type.

    Matches pandas' `dtype_backend` argument in `convert_dtypes`.
    Npyarrownumpy_nullable)r   rt   r   r   )r   rT   s     rU   get_dtype_backendr   r  s3    
 ,,,6u=G4GrW   c                    fd| D        S )ziYield a `DTypeBackend` per-dtype.

    Matches pandas' `dtype_backend` argument in `convert_dtypes`.
    c              3  6   K   | ]  }t        |        y wrP   )r   ).0r   rT   s     rU   	<genexpr>z&iter_dtype_backends.<locals>.<genexpr>  s     Ie^4Is   r   )r   rT   s    `rU   iter_dtype_backendsr     s     J&IIrW   c                Z    t        t        d      xr t        | t        j                        S )N
ArrowDtype)r   r   r]   r   r   s    rU   r   r     s    2|$IE2==)IIrW   r   r   zMapping[type[DType], str]NW_TO_PD_DTYPES_INVARIANTzFloat64[pyarrow]r   r   )r   r   NzFloat32[pyarrow]r   r   Int64[pyarrow]r   r   zInt32[pyarrow]r   r   zInt16[pyarrow]r   r   zInt8[pyarrow]r   r   zUInt64[pyarrow]r   r   zUInt32[pyarrow]r   r   zUInt16[pyarrow]r   r   zUInt8[pyarrow]r   r   zboolean[pyarrow]r   z<Mapping[type[DType], Mapping[DTypeBackend, str | type[Any]]]NW_TO_PD_DTYPES_BACKENDc           	        |dvrd| d}t        |      |j                  }| j                         }t        j	                  |      x}r|S t
        j	                  |      x}r||   S t        ||j                        r9|dk(  r(dd l}	t        j                   |	j                               S |dk(  ryt        S t        | |j                        rt        |      rxt         dk  rot#        | |j                        rV| j$                  d	k7  rGt'        j(                  t               }
d
|
d}d}d| j$                  d| d| d}t+        |t,               d	}n| j$                  }|dk(  r| j.                  x}rd| nd}d| | dS | j.                  x}rd| nd}d| | dS t        | |j0                        r4t        |      rt         dk  rd	}n| j$                  }|dk(  rd| dS d| dS t        | |j2                        r	 dd l}	yt        | |j6                        ro|t8        j:                  u rd}t=        |      t#        | |j6                        r-|j?                         }|jA                  | jB                  d      S d}t        |      t        ||jD                  |jF                  |jH                  |jJ                  |jL                  |jN                  f      rtQ        | ||      S d |  }tS        |      # t4        $ r}d}t5        |      |d }~ww xY w)!N>   Nr   r   z;Expected one of {None, 'pyarrow', 'numpy_nullable'}, got: ''r   r   r   r   )r   rL   z*available in 'pandas>=2.0', found version .zhttps://pandas.pydata.org/docs/dev/whatsnew/v2.0.0.html#construction-with-datetime64-or-timedelta64-dtype-with-unsupported-resolutionz`nw.Datetime(time_unit=z)` is only z
Narwhals has fallen back to using `time_unit='ns'` to avoid an error.

Hint: to avoid this warning, consider either:
- Upgrading pandas: zA
- Using a bare `nw.Datetime`, if this precision is not importantz, tz= z
timestamp[z
][pyarrow]z, zdatetime64[]z	duration[ztimedelta64[z/'pyarrow>=13.0.0' is required for `Date` dtype.zdate32[pyarrow]z9Converting to Enum is not supported in narwhals.stable.v1T)r   z9Can not cast / initialize Enum without categories presentzUnknown dtype: )*
ValueErrorr   	base_typer   getr   
issubclassr   r   r   r   r   r   r   r   rV   PANDAS_VERSIONr]   r   r   _unparse_versionr   UserWarningr   r   DateModuleNotFoundErrorr   r   r   NotImplementedErrorrq   CategoricalDtyper   StructArrayListTimeBinaryDecimalnarwhals_to_native_arrow_dtyper   )r   dtype_backendrT   r   rf   r   r  pd_typeinto_pd_typepafound	availablechangelog_urlr   tztz_partr   excrL   s                      rU   narwhals_to_native_dtyper!    sD    ??Mm_\]^o^^F!I+//	::w:.229==|=M**)V]]+I%  ==--,,
v7n-. D
 3
 %1eoo6M 11.AH	QRS	 !h-eoo-@I; W+ ,9/ :WX  c;/L ??LI%-2__'<r'<bTl2G~gYjAA&+oo 5 5Brd)B\N7)155v7n-. D
 3
  L ??L 	) ~Z0	
  ~Q/	

  v{{3	4 
 !v{{3gjj MC%c**eV[[)335B&&u'7'7&FFIoMMLLKKKKMMNN	

 .e^WMME7
#C

7 # 	4CC%c*3	4s   ;K0 0	L9LLc                   t        |      r0t        dk\  r'	 dd l}ddlm} t        j                   || |            S d|  d| d| d	}t        |      # t        $ r#}d|  d|j                   }t        |      |d }~ww xY w)
N)r   r   r   zUnable to convert to z! due to the following exception: )r!  zConverting to z+ dtype is not supported for implementation z and version r  )
rV   r	  r   ImportErrorrf   r   r!  r   r   r  )r   rT   r   r  r   rf   _to_arrow_dtypes          rU   r  r  %  s     .)n.F	,  	V}}_UG<==
J
-y	3  c
""  	,'w.OPSPWPWyY  c"+		,s   A 	A?A::A?c                l    dt        |       v ryt        |       j                         t        |       k7  ryy)Nr   r   r   r   )r   lowerr   s    rU   int_dtype_mapperr'  :  s0    CJ
5zSZ'rW   i  i@B )	)rL   rK   )rL   rJ   )rK   rL   )rK   rJ   )rJ   rL   )rJ   rK   )rI   rL   )rI   rK   )rI   rJ   zGMapping[tuple[UnitCurrent, UnitTarget], tuple[BinOpBroadcast, IntoRhs]]_TIMESTAMP_DATETIME_OP_FACTORc                    ||k(  r| S t         j                  ||f      x}r|\  }} || |      S d| d}t        |      )Nzunexpected time unit zD, please report an issue at https://github.com/narwhals-dev/narwhals)r(  r  r   )rI   currentr   itemr   factorrf   s          rU   calculate_timestamp_datetimer-  Q  sd     ),00'91EFFtF
F!V}
y )3 	3  
rW   rk   )rL   rK   rJ   rI   zMapping[TimeUnit, int]_TIMESTAMP_DATE_FACTORc                (    | t         z  t        |   z  S rP   )r   r.  )rI   r   s     rU   calculate_timestamp_dater0  h  s    !7	!BBBrW   c                   t        |      | j                  d   k(  r| j                  |k(  j                         r| S | j                  j                  j
                  dk(  s%|t        j                  u rO|j                         dk  r<t        || j                  j                               x}r|| j                  dd|f   S 	 | |   S # t        $ r0}t        || j                  j                               x}r|| d}~ww xY w)zsSelect columns by name.

    Prefer this over `df.loc[:, column_names]` as it's
    generally more performant.
    rk   brj   )r  N)rs   shapecolumnsallr   kindr   rQ   ru   r   tolistlocKeyError)dfcolumn_namesrT   errores        rU   select_columns_by_namer>  l  s     <BHHQK'RZZ<-G,L,L,N	


$.///++-6 (

@Q@Q@STT5TKvvao&&, '

@Q@Q@STT5TQs    C 	C>+C99C>c                    | j                   t        j                  t        j                  t        j                  hv xr | j
                  j                  dk(  S )NrN   )r`   r   rQ   rR   r   rZ   r   )rI   s    rU   is_non_nullable_booleanr@    sI     	
!!>#7#79L9LM	N 	%HHNNf$rW   c                   | t         j                  t         j                  hv rddl}|S | t         j                  u rddl}|S d|  }t        |      )zCReturns numpy or cupy module depending on the given implementation.r   Nz!Expected pandas/modin/cudf, got: )r   rQ   rR   numpyrt   cupyr   )rT   npcprf   s       rU   import_array_modulerF    sQ    .//1E1EFF	,,,	-n-=
>C

rW   c                      e Zd Zy)PandasLikeSeriesNamespaceN)__name__
__module____qualname__r   rW   rU   rH  rH    s    rW   rH  c                    dd| ddS )NFT)sortas_indexdropnaobservedr   )drop_null_keyss    rU   make_group_by_kwargsrR    s    t~SWXXrW   c                   | j                   d   }|rLddlm} t        j                   ||t        |            | j                        } |||| j                        S  |||| j                  | j                        S )a`  Broadcast a scalar value from a (one element) Series to match a target index.

    For nested (arrow-backed) types, we rely on
    [`pandas.array`](https://pandas.pydata.org/docs/reference/api/pandas.array.html).

    Arguments:
        native: The native pandas-like Series containing the scalar value to broadcast.
        index: The target index to broadcast to.
        is_nested: Whether the Series has a nested (arrow-backed) dtype.
        series_class: Series class to use for constructing the result.

    Returns:
        A new Series with the scalar value broadcast to match the target index.
    r   )repeatr   )r[   name)r[   r   rU  )r^   r   rT  r   arrayrs   r   rU  )rZ   r[   	is_nestedseries_classvaluerT  pa_arrays          rU   broadcast_series_to_indexr[    sd    * KKNE0 88F5#e*5V\\JHEDDU&,,V[[QQrW   )rT   r   r   rN   )rc   r&   rd   zPandasLikeSeries | objectr   z.tuple[pd.Series[Any], pd.Series[Any] | object])rw   r(   r[   r   rT   r   r   r(   )
rw   r(   r}   r   rT   r   r~   r   r   r(   )r   r   r   rN   )r   r   r   r   r   r*   )r   zPandasLikeSeries | Noner   r   rT   r   r   r*   )r   zpd.CategoricalDtyper   r   rT   r   r   r*   )r   r   r   zCallable[[], list[Any]])
r   r   r   r   rT   r   r   rN   r   r*   )r   r   r   zTypeIs[BaseMaskedDtype])r   r   rT   r   r   r+   )r   zIterable[Any]rT   r   r   zIterator[DTypeBackend])r   r   r   zTypeIs[pd.ArrowDtype])
r   r,   r  r+   rT   r   r   r   r   zstr | PandasDtype)r   r,   rT   r   r   r   r   zpd.ArrowDtype)r   r   r   r   )rI   r)   r*  r-   r   r-   r   r)   )rI   r)   r   r-   r   r)   )r:  r'   r;  zlist[str] | _1DArrayrT   r   r   zNativeDataFrameT | Any)rI   r&   r   rN   )rT   r   r   r   )rQ  rN   r   zdict[str, bool])
rZ   pd.Series[Any]r[   r   rW  rN   rX  ztype[pd.Series[Any]]r   r\  )
__future__r   	functoolsoperatorretypingr   r   r   r   r   r	   rB  rD  pandasr   narwhals._compliantr
   narwhals._constantsr   r   r   r   r   r   narwhals._exceptionsr   narwhals._utilsr   r   r   r   r   r   r   narwhals.exceptionsr   collections.abcr   r   r   r   r   r   r  pandas._typingr   PandasDtypepandas.core.dtypes.dtypesr    typing_extensionsr!   r"   narwhals._durationr#   narwhals._pandas_like.exprr$   rY   r&   narwhals._pandas_like.typingr'   r(   r)   narwhals.dtypesr*   narwhals.typingr+   r,   r-   r.   r/   r1   __annotations__r2   intr3   r4   rQ   rt   rR   PANDAS_LIKE_IMPLEMENTATIONPD_DATETIME_RGXcompileVERBOSEr   PD_DURATION_RGXr   r@   
ALIAS_DICTrM   ru   r	  NUMPY_VERSIONrV   rg   r_   r|   	lru_cacher   r   r   r   r   r   r   r   r   r   r   MAINr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r!  r  r'  floordivmulr(  r-  r.  r0  r>  r@  rF  rH  rR  r[  r   rW   rU   <module>r     sL   "   	 G G   4  /   +;; 393/9= 
 &KKG>2E%K%$J	$ (#sS 9NI9GY  
 !bjj"**= 
 !bjj"**=  '
! I  U#
		
				


9
5   &&779
 b!K	 93B'	' #'8F''.
*	
* #
*5C
*OR
*
* R 
 !
 R # !#L#.5GU
. % 07 IW 
  			 7      # 
    F ))+v5
	HJJ+9JJ R J !J 
		
 

MM88 4  NN%#
 NN%#
 LL.'QXY
LL.'QXY
LL.'QXY
KK_fU
MM$"
 MM$"
 MM$"
 LL.'QXY
NN%#?$Y U $Neee #e 	e
 eP##&4#?F##* $$e,$$i0<<!34$$e,<<!34<<',,.,,.,,.
    '4<  

	
	2 . C& # 	: T 45G5L M SYRRR 	R
 'R RrW   