U Dx`Dy@s^ UddlZddlmZddlmZddlmZddlmZddlZddl Z ddl Z ddl m Z ddl Z ddlZddlmZddlZddlZddlmZmZmZmZmZmZmZmZmZddlZddlZddlZ dd l!m"Z"m#Z#dd l$m%Z%m&Z&m'Z'dd l(m)Z)ddl*m+m,Z-dd l.m/Z/m0Z0m1Z1dd l2m3Z3m4Z4ddl5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;mZ>m?Z?m@Z@mAZAddlBmCZCddlDZEddlDmFZFmGZGmHZHmIZImJZJmKZKmLZLmMZMmNZNmOZOddlPmQZQmRZRddlSmTZTmUZUmVZVmWZWmXZXmYZYddlZm[Z[ddl\m]Z]ddl^m_Z_e4Z`dZadZbdZcddddgZdee/eed<ddd d!gZfee/eed"<egd#d$d%d&gZhee/eed'<d(d)d*d+gZiee/eed,<edehZjefeiZkeld-d.gZmee/eed/<d0d1gZnee/eed2<eod3d4gZpee/eed5<eqd6d7gZree/eed8<d9d:gZsee/eed;<d<eud?gZvewd@gZxeydAgZzemejZ{e{eperesetevezexZ|de j}eEj~eldBeEjgZeefZdCdDZdEdFZedGdHZdUeee0e1dIdJdKZdVeeqdLdMdNZdWeeqdLdOdPZedQdRZdXdTdUZeeuegfeldVdWdXZdYe)dZd[feeueqfeeuegfeleld\d]d^Zd_d`ZdYeudbdcddZdZeldgdhdiZe jeejeje jdjfdkZe jedleeedmdneje jdjfdkZd[dpdqZd\drdsZdtduZd]dvdwZed^euedxdydzZed{d|Zed}d~ZeudddZdYdae)dadadadZd[df eJeJeeueqfeueeuegfeueueueleleqdd ddZd_eeueqfdddZd`eqeqdddZddZddZdaddZdbddZdcddZddddZdeddZdfddZdgddZdade)ddZd[feleldddZdadYdae)dadddadadadadZd[dfddZdadYdYdae)daddddaddadadZd[dfddZddZdhddZddZddZddZddZeudddZddZdiddZdjddÄZdkddƄZdlddȄZdmddʄZdndd̄Zdodd΄ZdpddЄZÐdqdd҄ZĐdrddՄZŐdsdd؄ZƐdtddڄZǐdudd܄ZddddddddddddddddddddddddddgZɐdvddZddZːdwddZ̐dxddZ͐dyddZΐdzddZϐddZАd{dd Zѐd|d d ZҐd}d d ZӐd~ddZԐdddZՐddZ֐ddZאddZؐdddZِdddZڐdddZېddd Zܐdd"d#Zݐd$d%Zސd&Zߐd'Zd(d)Zdd*d+Zeސd,ecddeefd-d.ZeZeed/dadadfeeeeeufeueueeqd0d1d2Zejdd3d4d5ZGd6d7d7Zed8d9Zedd:d;Zdd=d>ZGd?d@d@eNZGdAdBdBeHZGdCdDdDeFZeeqdEdFdGZddHdIZeeqdJdKdLZeeedMdNdOZeEjjjjZdPdQZeqedRdSdTZdS(N)Counter)contextmanager)datetimewraps)Path)rmtree) IOAnyCallableContextManagerListOptionalTypeUnioncast)randrandn)can_set_locale get_locales set_locale) no_default)DtypeFilePathOrBuffer FrameOrSeries) get_lzma_file import_lzma) is_boolis_categorical_dtypeis_datetime64_dtypeis_datetime64tz_dtypeis_extension_array_dtypeis_interval_dtype is_numberis_numeric_dtypeis_period_dtype is_sequenceis_timedelta64_dtypeneeds_i8_conversion)array_equivalent) CategoricalCategoricalIndex DataFrame DatetimeIndexIndex IntervalIndex MultiIndex RangeIndexSeries bdate_range) safe_sorttake_1d) DatetimeArrayExtensionArray IntervalArray PeriodArrayTimedeltaArray period_array)DatetimeLikeArrayMixin)urlopen) pprint_thingFZuint8Zuint16Zuint32Zuint64UNSIGNED_INT_DTYPESZUInt8ZUInt16ZUInt32ZUInt64UNSIGNED_EA_INT_DTYPESZint8int16int32int64SIGNED_INT_DTYPESZInt8ZInt16ZInt32ZInt64SIGNED_EA_INT_DTYPESfloat32float64 FLOAT_DTYPESZFloat32ZFloat64FLOAT_EA_DTYPESZ complex64Z complex128COMPLEX_DTYPESstrU STRING_DTYPESzdatetime64[ns]zM8[ns]DATETIME64_DTYPESztimedelta64[ns]zm8[ns]TIMEDELTA64_DTYPESboolbytesobjectnancCs&tjdd}d|kr"tdtdS)NPANDAS_TESTING_MODENone deprecatealwaysosenvirongetwarnings simplefilter_testing_mode_warningsZ testing_moderb6/tmp/pip-target-zr53vnty/lib/python/pandas/_testing.pyset_testing_modexs rdcCs&tjdd}d|kr"tdtdS)NrVrWrXignorerZrarbrbrcreset_testing_modes rfcCstjddddS)zJ Reset the display options for printing and representing objects. z ^display.T)ZsilentN)pdZ reset_optionrbrbrbrcreset_display_optionssrh)objpathreturnc CsR|}|dkrdtdd}t|$}t||t|W5QRSQRXdS)a Pickle an object and then read it again. Parameters ---------- obj : any object The object to pickle and then re-read. path : str, path object or file-like object, default None The path where the pickled object is written and then read. Returns ------- pandas object The original object that was pickled and then re-read. N__ z __.pickle)rands ensure_cleanrgZ to_pickleZ read_pickle)rirj_pathZ temp_pathrbrbrcround_trip_pickles   rq)rjc CsPddl}|dj}|dkr d}t|}||||||}W5QRX|S)a Write an object to file specified by a pathlib.Path and read it back Parameters ---------- writer : callable bound to pandas object IO writing function (e.g. DataFrame.to_csv ) reader : callable IO reading function (e.g. pd.read_csv ) path : str, default None The path where the object is written and then read. Returns ------- pandas object The original object that was serialized and then re-read. rNpathlibZ ___pathlib___)pytest importorskiprro)writerreaderrjrsrrirbrbrcround_trip_pathlibs   rwc CsPddl}|dj}|dkr d}t|}||||||}W5QRX|S)a Write an object to file specified by a py.path LocalPath and read it back. Parameters ---------- writer : callable bound to pandas object IO writing function (e.g. DataFrame.to_csv ) reader : callable IO reading function (e.g. pd.read_csv ) path : str, default None The path where the object is written and then read. Returns ------- pandas object The original object that was serialized and then re-read. rNzpy.pathZ___localpath___)rsrtlocalro)rurvrjrsZ LocalPathrirbrbrcround_trip_localpaths   ryccs|dkrt|d}n|dkr*t|d}n|dkr@t|d}nn|dkrXtt|d}nV|dkrt|}|}t |dkr|| }qt d|d nt d |z |VW5| |dkr| XdS) a Open a compressed file and return a file object. Parameters ---------- path : str The path where the file is read from. compression : {'gzip', 'bz2', 'zip', 'xz', None} Name of the decompression to use Returns ------- file object Nrbgzipbz2xzzipz ZIP file z error. Only one file per ZIP.Unrecognized compression type: ) openr{r|BZ2FilerlzmazipfileZipFilenamelistlenpop ValueErrorclose)rj compressionfzip_fileZ zip_namesrbrbrcdecompress_files(    rtestc Cs|dkrtj}n@|dkr tj}n0|dkr0tj}n |dkrBtt}ntd||dkrjd}||f}d}nd}|f}d }|||d }t |||W5QRXd S) a Write data to a compressed file. Parameters ---------- compression : {'gzip', 'bz2', 'zip', 'xz'} The compression type to use. path : str The file path to write the data. data : str The data to write. dest : str, default "test" The destination file (for ZIP only) Raises ------ ValueError : An invalid compression value was passed in. r~r{r|r}rwwritestrwbwrite)modeN) rrr{GzipFiler|rrrrgetattr) rrjdatadestZcompress_methodrargsmethodrrbrbrcwrite_to_compresseds$ r)check_less_preciserkcCs*t|tr|rdSdSndd| SdS)a| Return the tolerance equivalent to the deprecated `check_less_precise` parameter. Parameters ---------- check_less_precise : bool or int Returns ------- float Tolerance to be used as relative/absolute tolerance. Examples -------- >>> # Using check_less_precise as a bool: >>> _get_tol_from_less_precise(False) 0.5e-5 >>> _get_tol_from_less_precise(True) 0.5e-3 >>> # Using check_less_precise as an int representing the decimal >>> # tolerance intended: >>> _get_tol_from_less_precise(2) 0.5e-2 >>> _get_tol_from_less_precise(8) 0.5e-8 gMb@?gh㈵>?rmN) isinstancerR)rrbrbrc_get_tol_from_less_preciseSs  requivgh㈵>g:0yE>) check_dtyperrtolatolcKs|tk r$tjdtddt|}}t|tjrNt||fd|||d|nt|tj rxt ||fd|||d|nt|tj rt ||fd|||d|nt|rt |rt |rnBt|rt|rn0t|tjst|tjrd}nd}t|||d tj||f|||d |d S) a Check that the left and right objects are approximately equal. By approximately equal, we refer to objects that are numbers or that contain numbers which may be equivalent to specific levels of precision. Parameters ---------- left : object right : object check_dtype : bool or {'equiv'}, default 'equiv' Check dtype if both a and b are the same type. If 'equiv' is passed in, then `RangeIndex` and `Int64Index` are also considered equivalent when doing type checking. check_less_precise : bool or int, default False Specify comparison precision. 5 digits (False) or 3 digits (True) after decimal points are compared. If int, then specify the number of digits to compare. When comparing two numbers, if the first number has magnitude less than 1e-5, we compare the two numbers directly and check whether they are equivalent within the specified precision. Otherwise, we compare the **ratio** of the second number to the first number and check whether it is equivalent to 1 within the specified precision. .. deprecated:: 1.1.0 Use `rtol` and `atol` instead to define relative/absolute tolerance, respectively. Similar to :func:`math.isclose`. rtol : float, default 1e-5 Relative tolerance. .. versionadded:: 1.1.0 atol : float, default 1e-8 Absolute tolerance. .. versionadded:: 1.1.0 The 'check_less_precise' keyword in testing.assert_*_equal is deprecated and will be removed in a future version. You can stop passing 'check_less_precise' to silence this warning. stacklevelF) check_exactexactrr)rrrr numpy arrayInputri)rrrN)rr^warn FutureWarningrrrgr.assert_index_equalr2assert_series_equalr,assert_frame_equalr#rnpndarrayassert_class_equal_testingassert_almost_equal)leftrightrrrrkwargsrirbrbrcr|s|.     rcCsZ|j}t||s.t|d|dt|dt||sVt|d|dt|ddS)a Helper method for our assert_* methods that ensures that the two objects being compared have the right type before proceeding with the comparison. Parameters ---------- left : The first object being compared. right : The second object being compared. cls : The class type to check against. Raises ------ AssertionError : Either `left` or `right` is not an instance of `cls`. z Expected type z, found z insteadN)__name__rAssertionErrortype)rrclsZcls_namerbrbrc_check_isinstances  rT compare_keyscCs t||ttj|||ddS)Nr)rdictrassert_dict_equal)rrrrbrbrcrs rrbr)pcCs t||kSN)r)sizerrbrbrcrandbool srrdtypeiiOcCs6tjjt|t|dtj|f|}||S)z, Generate an array of byte strings. r) rrandomchoice RANDS_CHARSprodviewstr_reshapeastypencharsrrretvalrbrbrc rands_arraysrcCs6tjjt|t|dtj|f|}||S)z/ Generate an array of unicode strings. r) rrr RANDU_CHARSrrunicode_rrrrbrbrc randu_array"srcCsdtjt|S)zt Generate one random byte string. See `rands_array` if you want to create an array of random strings. r)joinrrrr)rrbrbrcrn.srncCs:ddlm}m}|dkr.|D] }||qn||dS)Nr)r get_fignums)matplotlib.pyplotrr)Zfignum_closerrbrbrcr8s   r)return_filelikerc kstt}|dkrd}dtjtjtjdd|}||}| t |}|rl| ddt |f|}z |VW5t |t s||r|XdS)az Gets a temporary path and agrees to remove on close. This implementation does not use tempfile.mkstemp to avoid having a file handle. If the code using the returned path wants to delete the file itself, windows requires that no program has a file handle to it. Parameters ---------- filename : str (optional) suffix of the created file. return_filelike : bool (default False) if True, returns a file-like which is *always* cleaned. Necessary for savefig and other functions which want to append extensions. **kwargs Additional keywords are passed to open(). Nrr?krzw+b)rtempfile gettempdirrrchoicesstring ascii_lettersdigitstouchrM setdefaultrrris_fileunlink)filenamerrfolderrjZ handle_or_strrbrbrcroFs"     roccs@tjdd}z |VW5z t|Wntk r8YnXXdS)z{ Get a temporary directory path and agrees to remove on close. Yields ------ Temporary directory path r)suffixN)rmkdtemprOSError)Zdirectory_namerbrbrcensure_clean_dirss   rc cs2ttj}z dVW5tjtj|XdS)z Get a context manager to safely set environment variables All changes will be undone on close, hence environment variables set within this contextmanager will neither persist nor change global state. N)rr[r\clearupdate)Z saved_environrbrbrc!ensure_safe_environment_variabless    r)rkcCst|t|kS)zO Checks if the set of unique elements of arr1 and arr2 are equivalent. ) frozenset)Zarr1Zarr2rbrbrc equalContentssrr.) rrr check_namesrrcheck_categorical check_orderrrrirkc  sd} dfdd } dd} |tk r@tjdtdd t|}} t||t| ||| d |j|jkr| d }|jd |}|jd |}t| |||t |t |kr| d }t |d |}t |d |}t| ||||stt |}tt |}|jdkrt t |}t t |}t |jD]X}| ||}| ||}d|d}t|||||| |d| |j||j|| d q2|rr||st|j|jktdt |}| dt|dd}t| |||ntj|j|j|| | ||d|r$td||| d t|tjs@t|tjrPtd||| d t|tjslt|tjrzt|j|jrt |j!st |j!rt"|j|j| dd dS)at Check that left and right Index are equal. Parameters ---------- left : Index right : Index exact : bool or {'equiv'}, default 'equiv' Whether to check the Index class, dtype and inferred_type are identical. If 'equiv', then RangeIndex can be substituted for Int64Index as well. check_names : bool, default True Whether to check the names attribute. check_less_precise : bool or int, default False Specify comparison precision. Only used when check_exact is False. 5 digits (False) or 3 digits (True) after decimal points are compared. If int, then specify the digits to compare. .. deprecated:: 1.1.0 Use `rtol` and `atol` instead to define relative/absolute tolerance, respectively. Similar to :func:`math.isclose`. check_exact : bool, default True Whether to compare number exactly. check_categorical : bool, default True Whether to compare internal Categorical exactly. check_order : bool, default True Whether to compare the order of index entries as well as their values. If True, both indexes must contain the same elements, in the same order. If False, both indexes must contain the same elements, but in any order. .. versionadded:: 1.2.0 rtol : float, default 1e-5 Relative tolerance. Only used when check_exact is False. .. versionadded:: 1.1.0 atol : float, default 1e-8 Absolute tolerance. Only used when check_exact is False. .. versionadded:: 1.1.0 obj : str, default 'Index' Specify object name being compared, internally used to show appropriate assertion message. Examples -------- >>> from pandas.testing import assert_index_equal >>> a = pd.Index([1, 2, 3]) >>> b = pd.Index([1, 2, 3]) >>> assert_index_equal(a, b) Tr.csVrRt|||dr(td|||d|jdkrB|jdksRtntd|||ddS)N)rrirrr inferred_type)rassert_attr_equalrrrrrirrrbrc _check_typess z(assert_index_equal.._check_typescSs:|j|}|j|}t|j||jd}|j||j|dS)N) fill_valuename)levelscodesr5_valuesZ _na_valueZ _shallow_copynames)indexleveluniqueZ level_codesZfilledrbrbrc_get_ilevel_valuess  z.assert_index_equal.._get_ilevel_valuesrrrrz levels are different, z length are differentrzMultiIndex level [])rrrrrriY@ values are different ( %))rrrrilobjZrobjrfreq categoryN)r.)#rr^rrrrr.nlevelsraise_assert_detailrr4rr0rangerrequalsrsumvaluesrintroundrrrrrgZ PeriodIndexr/assert_interval_array_equalrrrassert_categorical_equal)rrrrrrrrrrri__tracebackhide__rr msg1msg2Zmsg3rZllevelZrlevelrdiffmsgrbrrcrs?                $ rr)rcCsd}dd}|dkrjt|t|krt|jt|jh}t|ddhr|d}t||||||n4|rt|t|kr|d}t||||||d S) z# Checks classes are equal. TcSst|tr|St|jSr)rr.rrxrbrbrc repr_classWs z&assert_class_equal..repr_classrZ Int64Indexr1z classes are not equivalentz classes are differentN)rrrr)rrrrirr$typesr!rbrbrcrQs  r Attributes)attrric Csd}t||}t||}||kr$dSt|rLt|rLt|rLt|rLdSz ||k}Wntk rpd}YnXt|ts|}|rdSd|d}t||||dS)aO Check attributes are equal. Both objects must have attribute. Parameters ---------- attr : str Attribute name being compared. left : object right : object obj : str, default 'Attributes' Specify object name being compared, internally used to show appropriate assertion message TFz Attribute "z" are differentN) rr#risnan TypeErrorrrRallr) r'rrrirZ left_attrZ right_attrresultr!rbrbrcrks0      rcCsddlm}t|tjtjfrZ|D]0}dtt |j }t||j t fs&t |q&n.dtt |j }t||jtt fst |dS)NrzBone of 'objs' is not a matplotlib Axes instance, type encountered zoobjs is neither an ndarray of Artist instances nor a single ArtistArtist instance, tuple, or dict, 'objs' is a )rZpyplotrrgr2rrZravelreprrrZAxesrrZArtisttuple)objsZpltelr!rbrbrc"assert_is_valid_plot_return_objects  r0cCs.t|ttfr|j}t|tt|dS)z#Assert that the sequence is sorted.N)rr.r2rassert_numpy_array_equalrsortarray)seqrbrbrcassert_is_sortedsr5r*cCst||t|rDt|j|j|ddt|j|j||ddnxz|j}|j}Wn"tk r~|j|j}}YnXt|||ddt|j|j|j|j|ddt d|||ddS)a{ Test that Categoricals are equivalent. Parameters ---------- left : Categorical right : Categorical check_dtype : bool, default True Check that integer dtype of the codes are the same check_category_order : bool, default True Whether the order of the categories should be compared, which implies identical integer codes. If False, only the resulting values are compared. The ordered attribute is checked regardless. obj : str, default 'Categorical' Specify object name being compared, internally used to show appropriate assertion message z .categoriesrz.codesrriz.valuesorderedN) rr*r categoriesr1rZ sort_valuesr)Ztaker)rrrcheck_category_orderrilcrcrbrbrcrs*    rr8cCszt||ti}|jjjdkr&d|d<t|j|jfd|di|t|j|jfd|di|td|||ddS) a Test that two IntervalArrays are equivalent. Parameters ---------- left, right : IntervalArray The IntervalArrays to compare. exact : bool or {'equiv'}, default 'equiv' Whether to check the Index class, dtype and inferred_type are identical. If 'equiv', then RangeIndex can be substituted for Int64Index as well. obj : str, default 'IntervalArray' Specify object name being compared, internally used to show appropriate assertion message )mMF check_freqriz.leftclosedrN)rr8_leftrkind assert_equal_rightr)rrrrirrbrbrcrs   rr9cCs8t||tt|j|j|ddtd|||ddS)N._datarr)rr9r1_datarrrbrbrcassert_period_array_equals rFr6cCsPd}t||tt|j|j|dd|rrrbrbrcassert_datetime_array_equals  rIr:cCs@d}t||tt|j|j|dd|rrr,r)rimessagerrr  index_valuesrr!rbrbrcrs,     rrc sd}t||dt||tjdd} | |} | |} |dkrd| | k rtt| dt| n*|dkr| | krtt| dt| fd d } t||d s| ||||rt|tjrt|tjrtd ||dd S)a+ Check that 'np.ndarray' is equivalent. Parameters ---------- left, right : numpy.ndarray or iterable The two arrays to be compared. strict_nan : bool, default False If True, consider NaN and None to be different. check_dtype : bool, default True Check dtype if both a and b are np.ndarray. err_msg : str, default None If provided, used as assertion message. check_same : None|'copy'|'same', default None Ensure left and right refer/do not refer to the same memory area. obj : str, default 'numpy array' Specify object name being compared, internally used to show appropriate assertion message. index_values : numpy.ndarray, default None optional index (shared by both left and right), used in output. TrcSst|dddk r|jS|S)Nbase)rrMrrbrbrc _get_base[sz+assert_numpy_array_equal.._get_baseZsamez is not copyz is cs|dkr|j|jkr,td|j|jd}t||D]\}}t||ds:|d7}q:|d|j}dt|dd}t|||d t|dS) Nz shapes are differentr strict_nanrr r rrrL)shaperr~r)rrrr)rrerr_msgr Zleft_arrZ right_arrr!rLrirQrbrc_raisehs   z(assert_numpy_array_equal.._raiserPrN) rrrrrr,r)rr) rrrQrrTZ check_samerirLrrNZ left_baseZ right_baserVrbrUrcr14s$ r1)rrc Cs.|tk r$tjdtddt|}}t|ts6tdt|tsHtd|r\td||ddt|t rt|t rt |t |krt t |jt |j|d d St |}t |} t || d |d t ||t} t || t} |rt | | d|d ntj| | |||d|d d S)a- Check that left and right ExtensionArrays are equal. Parameters ---------- left, right : ExtensionArray The two arrays to compare. check_dtype : bool, default True Whether to check if the ExtensionArray dtypes are identical. index_values : numpy.ndarray, default None Optional index (shared by both left and right), used in output. check_less_precise : bool or int, default False Specify comparison precision. Only used when check_exact is False. 5 digits (False) or 3 digits (True) after decimal points are compared. If int, then specify the digits to compare. .. deprecated:: 1.1.0 Use `rtol` and `atol` instead to define relative/absolute tolerance, respectively. Similar to :func:`math.isclose`. check_exact : bool, default False Whether to compare number exactly. rtol : float, default 1e-5 Relative tolerance. Only used when check_exact is False. .. versionadded:: 1.1.0 atol : float, default 1e-8 Absolute tolerance. Only used when check_exact is False. .. versionadded:: 1.1.0 Notes ----- Missing values are checked separately from valid values. A mask of missing values is computed for each and checked to match. The remaining all-valid values are cast to object dtype and checked. Examples -------- >>> from pandas.testing import assert_extension_array_equal >>> a = pd.Series([1, 2, 3, 4]) >>> b, c = a.array, a.array >>> assert_extension_array_equal(b, c) rrrzleft is not an ExtensionArrayzright is not an ExtensionArrayrr7rrRNzExtensionArray NA mask)rirL)rrrrirL)rr^rrrrr7rrr<rr1rasarrayZasi8ZisnarrTrr) rrrrLrrrrZleft_naZright_naZ left_validZ right_validrbrbrcassert_extension_array_equalsb5  rXr2c Csd}|tk r(tjdtddt|} }t||t|rFt|||dt|t|krt|d|j }t|d|j }t |d||| r|j |j kst t |j dt |j t|j |j |||| | ||d d | r$t|j tjtjfr$|j }|j }|j|jks$t |j|jf|r`t|jrJt|jrJ| sJntd ||d |d|rt|jrt|jr|j}|j}t|rt|rt|||t|j d nt|||t|t|j dn|r2t|jst|jr2t |j!t |jspd|jd|jd}t |n>t"|jr\t"|jr\t#|j$|j$nt|jstt|jrt%j&|j|j| ||t|t|j dnt|jrt|jrt|j|j|t|j d nt'|j|jst'|j|jrt|j|j|t|j d n^t|jrHt|jrHt|j|j|t|j d n(t%j&|j|j| ||t|t|j d|rtd|||d| rt|jst|jrt(|j|j|d| ddS)ai Check that left and right Series are equal. Parameters ---------- left : Series right : Series check_dtype : bool, default True Whether to check the Series dtype is identical. check_index_type : bool or {'equiv'}, default 'equiv' Whether to check the Index class, dtype and inferred_type are identical. check_series_type : bool, default True Whether to check the Series class is identical. check_less_precise : bool or int, default False Specify comparison precision. Only used when check_exact is False. 5 digits (False) or 3 digits (True) after decimal points are compared. If int, then specify the digits to compare. When comparing two numbers, if the first number has magnitude less than 1e-5, we compare the two numbers directly and check whether they are equivalent within the specified precision. Otherwise, we compare the **ratio** of the second number to the first number and check whether it is equivalent to 1 within the specified precision. .. deprecated:: 1.1.0 Use `rtol` and `atol` instead to define relative/absolute tolerance, respectively. Similar to :func:`math.isclose`. check_names : bool, default True Whether to check the Series and Index names attribute. check_exact : bool, default False Whether to compare number exactly. check_datetimelike_compat : bool, default False Compare datetime-like which is comparable ignoring dtype. check_categorical : bool, default True Whether to compare internal Categorical exactly. check_category_order : bool, default True Whether to compare category order of internal Categoricals. .. versionadded:: 1.0.2 check_freq : bool, default True Whether to check the `freq` attribute on a DatetimeIndex or TimedeltaIndex. .. versionadded:: 1.1.0 check_flags : bool, default True Whether to check the `flags` attribute. .. versionadded:: 1.2.0 rtol : float, default 1e-5 Relative tolerance. Only used when check_exact is False. .. versionadded:: 1.1.0 atol : float, default 1e-8 Absolute tolerance. Only used when check_exact is False. .. versionadded:: 1.1.0 obj : str, default 'Series' Specify object name being compared, internally used to show appropriate assertion message. Examples -------- >>> from pandas.testing import assert_series_equal >>> a = pd.Series([1, 2, 3, 4]) >>> b = pd.Series([1, 2, 3, 4]) >>> assert_series_equal(a, b) Trrrrr zSeries length are different != .index)rrrrrrrirzAttributes of )rrL)rrirLzatetimelike_compat=True] z is not equal to .)rrrrirLrr)rir9N))rr^rrrrr2rrrrflagsrr,rrrgr-TimedeltaIndexrrrrr$rr!rXrrWr1rMr(r.rr"rr3rr0is_extension_array_dtype_and_needs_i8_conversionr)rrrcheck_index_typeZcheck_series_typerrrcheck_datetimelike_compatrr9r> check_flagsrrrirrrZlidxZridxZ left_valuesZ right_valuesr!rbrbrcrsV  *              rr,cCsd}|tk r(tjdtddt|}}t||t|rJt|t|sJt |j |j krzt ||dt |j t |j |r|j |j kst t |j dt |j t|j|j||| | | |||dd t|j|j||| | | |||d d | r|||}}|r|}|}ttt|t|D]:}||ksVt ||ksdt t||||||d qDnzt|jD]n\}}||kst |jd d |f}|jd d |f}t||||| || | | |d |d |d||d qd S)a Check that left and right DataFrame are equal. This function is intended to compare two DataFrames and output any differences. Is is mostly intended for use in unit tests. Additional parameters allow varying the strictness of the equality checks performed. Parameters ---------- left : DataFrame First DataFrame to compare. right : DataFrame Second DataFrame to compare. check_dtype : bool, default True Whether to check the DataFrame dtype is identical. check_index_type : bool or {'equiv'}, default 'equiv' Whether to check the Index class, dtype and inferred_type are identical. check_column_type : bool or {'equiv'}, default 'equiv' Whether to check the columns class, dtype and inferred_type are identical. Is passed as the ``exact`` argument of :func:`assert_index_equal`. check_frame_type : bool, default True Whether to check the DataFrame class is identical. check_less_precise : bool or int, default False Specify comparison precision. Only used when check_exact is False. 5 digits (False) or 3 digits (True) after decimal points are compared. If int, then specify the digits to compare. When comparing two numbers, if the first number has magnitude less than 1e-5, we compare the two numbers directly and check whether they are equivalent within the specified precision. Otherwise, we compare the **ratio** of the second number to the first number and check whether it is equivalent to 1 within the specified precision. .. deprecated:: 1.1.0 Use `rtol` and `atol` instead to define relative/absolute tolerance, respectively. Similar to :func:`math.isclose`. check_names : bool, default True Whether to check that the `names` attribute for both the `index` and `column` attributes of the DataFrame is identical. by_blocks : bool, default False Specify how to compare internal data. If False, compare by columns. If True, compare by blocks. check_exact : bool, default False Whether to compare number exactly. check_datetimelike_compat : bool, default False Compare datetime-like which is comparable ignoring dtype. check_categorical : bool, default True Whether to compare internal Categorical exactly. check_like : bool, default False If True, ignore the order of index & columns. Note: index labels must match their respective rows (same as in columns) - same labels must be with the same data. check_freq : bool, default True Whether to check the `freq` attribute on a DatetimeIndex or TimedeltaIndex. .. versionadded:: 1.1.0 check_flags : bool, default True Whether to check the `flags` attribute. rtol : float, default 1e-5 Relative tolerance. Only used when check_exact is False. .. versionadded:: 1.1.0 atol : float, default 1e-8 Absolute tolerance. Only used when check_exact is False. .. versionadded:: 1.1.0 obj : str, default 'DataFrame' Specify object name being compared, internally used to show appropriate assertion message. See Also -------- assert_series_equal : Equivalent method for asserting Series equality. DataFrame.equals : Check DataFrame equality. Examples -------- This example shows comparing two DataFrames that are equal but with columns of differing dtypes. >>> from pandas._testing import assert_frame_equal >>> df1 = pd.DataFrame({'a': [1, 2], 'b': [3, 4]}) >>> df2 = pd.DataFrame({'a': [1, 2], 'b': [3.0, 4.0]}) df1 equals itself. >>> assert_frame_equal(df1, df1) df1 differs from df2 as column 'b' is of a different type. >>> assert_frame_equal(df1, df2) Traceback (most recent call last): ... AssertionError: Attributes of DataFrame.iloc[:, 1] (column name="b") are different Attribute "dtype" are different [left]: int64 [right]: float64 Ignore differing dtypes in columns with check_dtype. >>> assert_frame_equal(df1, df2, check_dtype=False) Trrrz shape mismatchrYrZ)rrrrrrrriz.columnsr6Nz .iloc[:, z] (column name="z")) rr_rrr`rr>rirr)rr^rrrrr,rrrrSrr,r\rrcolumnsZ reindex_likeZ_to_dict_of_blockslistsetkeysr enumerateilocr)rrrr_Zcheck_column_typeZcheck_frame_typerrZ by_blocksrr`rZ check_liker>rarrrirZrblocksZlblocksricolZlcolZrcolrbrbrcrs~    * $ rcKsdd}t|tjrPt||f|t|tjtjfrL|j|jksLt|j|jfnt|tjrlt ||f|nt|tj rt ||f|nt|t rt ||f|nt|trt||f|nt|trt||f|nt|trt||f|npt|tr t||f|nTt|tjr*t||f|n6t|trT|iksDt||ks`tn tt|dS)aC Wrapper for tm.assert_*_equal to dispatch to the appropriate test function. Parameters ---------- left, right : Index, Series, DataFrame, ExtensionArray, or np.ndarray The two items to be compared. **kwargs All keyword arguments are passed through to the underlying assert method. TN)rrgr.rr-r]rrr2rr,rr8rr9rFr6rIr:rJr7rXrrr1rMNotImplementedErrorr)rrrrrbrbrcrBs2           rBcCs|tjkrt|}n|tjkr,t|}n|tjkrBt|}n|tjkrft|}|r|j}nf|tkrxt|}nT|t krt |}nB|t krt |}n0|t j krt |}n|t krt |}nt||S)z Helper function to wrap the expected output of a test in a given box_class. Parameters ---------- expected : np.ndarray, Index, Series box_cls : {Index, Series, DataFrame} Returns ------- subclass of box_cls )rgr3r.r2r,Zto_frameTr9r;r6r:rrto_arrayrj)expectedZbox_clsZ transposerbrbrc box_expecteds,             rncCsVt|dd}t|rt|St|s,t|r6t|St|rHt|St |SdS)Nr) rr%r;rr r6Z_from_sequencer'r:rr3)rirrbrbrcrl s   rlcCst||tjjt|j|jt|jtjj j s4t t|jtjj j sJt |j}|j}| |spt dd||ntd||td||t||dS)z Check that the left and right SparseArray are equal. Parameters ---------- left : SparseArray right : SparseArray zSparseArray.indexzindex are not equalrrN)rrgZarraysZ SparseArrayr1Z sp_valuesrZsp_index_libssparseZ SparseIndexrrrrZto_dense)rrZ left_indexZ right_indexrbrbrcassert_sp_array_equals    rqcCs(|D]}||kstdt|qdS)NzDid not contain item: )rr,)iterableZdicrrbrbrcassert_contains_allAsrscKsXt||D]H\}}t||f|dtt|dtt|d}||k s t|q dS)z iter1, iter2: iterables that produce elements comparable with assert_almost_equal Checks that the elements are equal, but not the same object. (Does not check that items in sequences are also not the same object) zExpected object z and object z8 to be different objects, but they were the same object.N)r~rr,rr)Ziter1Ziter2Z eql_kwargsZelem1Zelem2r!rbrbrc assert_copyFs  rtcCst|ot|S)z Checks that we have the combination of an ExtensionArraydtype and a dtype that should be converted to int64 Returns ------- bool Related to issue #37609 )r!r()Z left_dtypeZ right_dtyperbrbrcr^Xs r^cCstjd|Sr)rascii_uppercaserrbrbrcgetColsfsrvrmcCsttd|d|dSNrmrrr)r.rrrrbrbrcmakeStringIndexksrzcCsttd|d|dSrw)r.rryrbrbrcmakeUnicodeIndexosr{cKs4td|d}ttjt|||dfd|i|S)z' make a length k index or n categories r@rx)r8r)rr+r*Z from_codesrZarange)rnrrr#rbrbrcmakeCategoricalIndexss r~cKs*tjdd|dd}tj|fd|i|S)z make a length k IntervalIndex rdr)numr)rZlinspacer/Z from_breaks)rrrr#rbrbrcmakeIntervalIndex{srcCsL|dkrtdg|dS|dkr.tddg|dStddgdg|d|dS)NrTrrF)r.ryrbrbrc makeBoolIndexs rcCsttt||dS)Nr)r.rcrryrbrbrc makeIntIndexsrcCstddt|D|dS)NcSsg|] }d|qS)lrb.0rhrbrbrc sz!makeUIntIndex..r)r.rryrbrbrc makeUIntIndexsrcKstd|dfd|i|S)Nrrr)r1)rrrrbrbrcmakeRangeIndexsrcCs:ttj|tjd}t|dtjdd|dS)Nrrmr r)sortedrrZ random_sampler.randint)rrrrbrbrcmakeFloatIndexsrBcKs0tddd}t||||d}t|fd|i|S)Nr)periodsrrr)rr3r-)rrrrdtZdrrbrbrc makeDateIndexs rDcKstjfd|||d|S)Nz1 daystartrrr)rgZtimedelta_range)rrrrrbrbrcmakeTimedeltaIndexsrcKs&tddd}tjf||d|d|S)Nrrrr)rrgZ period_range)rrrrrbrbrcmakePeriodIndexs rcKstjdd|i|S)N)Zfoobar)rrr)r)r0Z from_product)rrrrbrbrcmakeMultiIndexsrZAliceZBobZCharlieZDanZEdithZFrankZGeorgeZHannahZIngridZJerryZKevinZLauraZMichaelZNorbertZOliverZPatriciaZQuinnZRayZSarahZTimZUrsulaZVictorZWendyZXavierZYvonneZZelda 2000-01-01 2000-12-311Dc Cstj|||dd}t|}tj|}|jt|d|jd|d| |dd| |ddd}tj ||t |d}|j d |kr|j d d }|S) a Make a DataFrame with a DatetimeIndex Parameters ---------- start : str or Timestamp, default "2000-01-01" The start of the index. Passed to date_range with `freq`. end : str or Timestamp, default "2000-12-31" The end of the index. Passed to date_range with `freq`. freq : str or Freq The frequency to use for the DatetimeIndex seed : int, optional The random state seed. * name : object dtype with string names * id : int dtype with * x, y : float dtype Examples -------- >>> _make_timeseries() id name x y timestamp 2000-01-01 982 Frank 0.031261 0.986727 2000-01-02 1025 Edith -0.086358 -0.032920 2000-01-03 982 Edith 0.473177 0.298654 2000-01-04 1009 Sarah 0.534344 -0.750377 2000-01-05 963 Zelda -0.271573 0.054424 ... ... ... ... ... 2000-12-27 980 Ingrid -0.132333 -0.422195 2000-12-28 972 Frank -0.376007 -0.298687 2000-12-29 1009 Ursula -0.865047 -0.503133 2000-12-30 1000 Hannah -0.063757 -0.507336 2000-12-31 972 Tim -0.869120 0.531685 timestamp)rendrrrirr)ridr#y)rrbN)rgZ date_rangerrr RandomStater_namesZpoissonrr,rrrg) rrrseedrr}staterbdfrbrbrc_make_timeseriess$   rccs tttttttg}|EdHdSr)rrrrrr~r)make_index_funcsrbrbrcindex_subclass_makers_generators rccs$tttg}|D]}||dVqdS)z Generator which can be iterated over to get instances of all the classes which represent time-series. Parameters ---------- k: length of each of the index instances rN)rrr)rrZmake_index_funcrbrbrcall_timeseries_index_generator s rcCstt}ttt||dSNrrrz_Nr2rrrrbrbrcmakeFloatSeriessrcCstt}ttt||dSrrrrbrbrcmakeStringSeries srcCs*tt}t|td}tt}t|||dS)Nrr)rzrr.rTr2)rrrrbrbrcmakeObjectSeries%s rcsttfddttDS)Ncsi|]}|tttdqS)r)r2rrrcrrbrc .sz!getSeriesData..)rzrrv_Krbrbrrc getSeriesData,srcCs&|dkr t}tt|t||d|dS)N)rr)rr2rr)nperrrrbrbrcmakeTimeSeries1srcCs"|dkr t}tt|t||dSr)rr2rr)rrrbrbrcmakePeriodSeries7srcsfddttDS)Ncsi|]}|tqSrb)rrrrrbrcr>sz%getTimeSeriesData..rvr)rrrbrrcgetTimeSeriesData=srcsfddttDS)Ncsi|]}|tqSrb)rrrrbrcrBsz!getPeriodData..rrrbrrc getPeriodDataAsrcCst||}t|Sr)rr,)rrrrbrbrcmakeTimeDataFrameFs rcCst}t|Sr)rr,)rrbrbrc makeDataFrameKsrcCsNtdddddg}dddd d gdddddgd d d ddgtdddd}||fS)Nabrdeg?g@g@g@Zfoo1Zfoo2Zfoo3Zfoo4Zfoo5z1/1/2009r)r)ArCr)r.r3)rrrbrbrcgetMixedTypeDictPs    rcCsttdS)Nr)r,rrbrbrbrcmakeMixedDataFrame]srcCst|}t|Sr)rr,)rrrbrbrcmakePeriodFrameasr#csN|dkrdg|}t|r&t||ks*t|dksR|dksR|dksRt||ksRt|dksn|dkrj|dksnt|dkrfddt|D}|dkrd}t|tr|dkr|g}tttt t t t d |}|r||}|r|d |_|S|dk rtt|d t||kr*|dg|t|t||ks 1 produces multindex) prefix - a string prefix for labels names - (Optional), bool or list of strings. if True will use default names, if false will use no names, if a list is given, the name of each level in the index will be taken from the list. ndupe_l - (Optional), list of ints, the number of rows for which the label will repeated at the corresponding level, you can specify just the first few, the rest will use the default ndupe_l of 1. len(ndupe_l) <= nlevels. idx_type - "i"/"f"/"s"/"u"/"dt"/"p"/"td". If idx_type is not None, `idx_nlevels` must be 1. "i"/"f" creates an integer/float index, "s"/"u" creates a string/unicode index "dt" create a datetime index. "td" create a datetime index. if unspecified, string labels will be generated. NrFTrhrsurrtdcsg|]}t|qSrb)rMrprefixrbrcrsz#makeCustomIndex..)rhrrrrrrrzI is not a legal value for `idx_type`, use 'i'/'f'/'s'/'u'/'dt'/'p'/'td'.css|]}|dkVqdSrNrbrr#rbrbrc sz"makeCustomIndex..cSs*ddl}|dd|d}dd|DS)Nrz[^\d_]_?r_cSsg|] }t|qSrb)r)rrrbrbrcrsz4makeCustomIndex..keyfunc..)resubsplit)r#rZ numeric_tuplerbrbrckeyfuncsz makeCustomIndex..keyfuncZ_lZ_g)keyrcss|]}|dVqdSrrbrrbrbrcrs)r)r&rrrrrMrrrzr{rrrr]rrr,extendr*rrelementsappendrcr~r.r0 from_tuples)Znentriesrrrndupe_lidx_typeZidx_funcidxZtuplesrhrZ div_factorZcntjlabelr+rrrbrrcmakeCustomIndexfsp (         rc s|dks t|dkst| dks4| dkr0|dks4t| dksP| dkrL|dksPtt|d||| d} t||d||| d} dkrdd fd d t|D}t|| | | d S) a Create a DataFrame using supplied parameters. Parameters ---------- nrows, ncols - number of data rows/cols c_idx_names, idx_names - False/True/list of strings, yields No names , default names or uses the provided names for the levels of the corresponding index. You can provide a single string when c_idx_nlevels ==1. c_idx_nlevels - number of levels in columns index. > 1 will yield MultiIndex r_idx_nlevels - number of levels in rows index. > 1 will yield MultiIndex data_gen_f - a function f(row,col) which return the data value at that position, the default generator used yields values of the form "RxCy" based on position. c_ndupe_l, r_ndupe_l - list of integers, determines the number of duplicates for each label at a given level of the corresponding index. The default `None` value produces a multiplicity of 1 across all levels, i.e. a unique index. Will accept a partial list of length N < idx_nlevels, for just the first N levels. If ndupe doesn't divide nrows/ncol, the last label might have lower multiplicity. dtype - passed to the DataFrame constructor as is, in case you wish to have more control in conjunction with a custom `data_gen_f` r_idx_type, c_idx_type - "i"/"f"/"s"/"u"/"dt"/"td". If idx_type is not None, `idx_nlevels` must be 1. "i"/"f" creates an integer/float index, "s"/"u" creates a string/unicode index "dt" create a datetime index. "td" create a timedelta index. if unspecified, string labels will be generated. Examples -------- # 5 row, 3 columns, default names on both, single index on both axis >> makeCustomDataframe(5,3) # make the data a random int between 1 and 100 >> mkdf(5,3,data_gen_f=lambda r,c:randint(1,100)) # 2-level multiindex on rows with each label duplicated # twice on first level, default names on both axis, single # index on both axis >> a=makeCustomDataframe(5,3,r_idx_nlevels=2,r_ndupe_l=[2]) # DatetimeIndex on row, index with unicode labels on columns # no names on either axis >> a=makeCustomDataframe(5,3,c_idx_names=False,r_idx_names=False, r_idx_type="dt",c_idx_type="u") # 4-level multindex on rows with names provided, 2-level multindex # on columns with default labels and default names. >> a=makeCustomDataframe(5,3,r_idx_nlevels=4, r_idx_names=["FEE","FI","FO","FAM"], c_idx_nlevels=2) >> a=mkdf(5,3,r_idx_nlevels=2,c_idx_nlevels=4) rNrrr)rrrrrRcSsd|d|S)Nrrrb)rrrbrbrc5 z%makeCustomDataframe..cs$g|]fddtDqS)csg|]}|qSrbrbr) data_gen_frrbrcr7 sz2makeCustomDataframe...)r)rrncols)rrcr7 sz'makeCustomDataframe..r)rrrr,)nrowsrZ c_idx_namesZ r_idx_namesZ c_idx_nlevelsZ r_idx_nlevelsrZ c_ndupe_lZ r_ndupe_lrZ c_idx_typeZ r_idx_typerbrrrbrrcmakeCustomDataframes@H   rc s|dkrtj}n tj|}ttd|d}d}t||}fdd}|||}|jkr|d9}|||}qjt|dt} || t} | | fS)NrrgRQ?cs.|t|}tt|dSr)rrrrfloor)rngZ _extra_sizeindrrrrbrc_gen_unique_randI sz-_create_missing_idx.._gen_unique_randg?r) rrrrrminrrrtolist) rrdensity random_stateZmin_rowsZfac extra_sizerrrrhrbrrc_create_missing_idx< s    r?cCs0t}t|j||d\}}tj|j||f<|S)N)rr)rrrSrrUr)rrrrhrrbrbrcmakeMissingDataframeW s rcstfdd}|S)aB allows a decorator to take optional positional and keyword arguments. Assumes that taking a single, callable, positional argument means that it is decorating a function, i.e. something like this:: @my_decorator def function(): pass Calls decorator with decorator(f, *args, **kwargs) csNfdd} o,tdko,td}|rFd}g||S|SdS)Ncs|fSrrb)r)r decoratorrrbrcdecs sz+optional_args..wrapper..decrr)rcallable)rrrZ is_decoratingrr)rrrcwrapperq szoptional_args..wrapperr)rrrbrrc optional_argse s r) z timed outz Server Hangupz#HTTP Error 503: Service Unavailablez502: Proxy ErrorzHTTP Error 502: internal errorzHTTP Error 502zHTTP Error 503zHTTP Error 403zHTTP Error 400z$Temporary failure in name resolutionzName or service not knownzConnection refusedzcertificate verify)eonh6<cCsddl}t|jjtfSNr) http.clientIOErrorclient HTTPException TimeoutError)httprbrbrc_get_default_network_errors src CsF|dkrt}zt|W5QRXWn|k r<YdSXdSdS)a@ Try to connect to the given url. True if succeeds, False if IOError raised Parameters ---------- url : basestring The URL to try to connect to Returns ------- connectable : bool Return True if no IOError (unable to connect) or URLError (bad url) was raised NFT)rr=)url error_classesrbrbrc can_connect s rzhttps://www.google.comc sFddlmdkrtd_tfdd}|S)a\ Label a test as requiring network connection and, if an error is encountered, only raise if it does not find a network connection. In comparison to ``network``, this assumes an added contract to your test: you must assert that, under normal conditions, your test will ONLY fail if it does not have network connectivity. You can call this in 3 ways: as a standard decorator, with keyword arguments, or with a positional argument that is the url to check. Parameters ---------- t : callable The test requiring network connectivity. url : path The url to test via ``pandas.io.common.urlopen`` to check for connectivity. Defaults to 'https://www.google.com'. raise_on_error : bool If True, never catches errors. check_before_test : bool If True, checks connectivity before running the test case. error_classes : tuple or Exception error classes to ignore. If not in ``error_classes``, raises the error. defaults to IOError. Be careful about changing the error classes here. skip_errnos : iterable of int Any exception that has .errno or .reason.erno set to one of these values will be skipped with an appropriate message. _skip_on_messages: iterable of string any exception e for which one of the strings is a substring of str(e) will be skipped with an appropriate message. Intended to suppress errors where an errno isn't available. Notes ----- * ``raise_on_error`` supersedes ``check_before_test`` Returns ------- t : callable The decorated test ``t``, with checks for connectivity errors. Example ------- Tests decorated with @network will fail if it's possible to make a network connection to another URL (defaults to google.com):: >>> from pandas._testing import network >>> from pandas.io.common import urlopen >>> @network ... def test_network(): ... with urlopen("rabbit://bonanza.com"): ... pass Traceback ... URLError: You can specify alternative URLs:: >>> @network("https://www.yahoo.com") ... def test_something_with_yahoo(): ... raise IOError("Failure Message") >>> test_something_with_yahoo() Traceback (most recent call last): ... IOError: Failure Message If you set check_before_test, it will check the url first and not run the test on failure:: >>> @network("failing://url.blaher", check_before_test=True) ... def test_something(): ... print("I ran!") ... raise ValueError("Failure") >>> test_something() Traceback (most recent call last): ... Errors not related to networking will always be raised. r)skipNTc srstsz ||WStk r}zt|dd}|s^t|dr^t|jdd}|krtd|t|tfddDrd|t|sstrnd|W5d}~XYnXdS)Nerrnoreasonz+Skipping test due to known errno and error c3s|]}|kVqdSr)lower)rr<Ze_strrbrcrF sz+network..wrapper..z;Skipping test because exception message is known and error z4Skipping test due to lack of connectivity and error )r ExceptionrhasattrrrManyr)rrerrr_skip_on_messagescheck_before_testrraise_on_errorr skip_errnostrrrcr0 s2   znetwork..wrapper)rsrrnetworkr)r"rr rrr!rrrbrrcr# s\ "r#rY)expected_warningcheck_stacklevelraise_on_extra_warningsmatchc cs4d}tjdd}d}d}t||Vg} |D]} |s>q4ttt|}t| j|rd}|rxt| jtt frxt | |dk rt |t | jrd}q4| | jj| j| j| jfq4|rttt|}|stdt|j|r|stdt|jd||r&| r&tdt| W5QRXdS) a Context manager for running code expected to either raise a specific warning, or not raise any warnings. Verifies that the code raises the expected warning, and that it does not raise any other unexpected warnings. It is basically a wrapper around ``warnings.catch_warnings``. Parameters ---------- expected_warning : {Warning, False, None}, default Warning The type of Exception raised. ``exception.Warning`` is the base class for all warnings. To check that no warning is returned, specify ``False`` or ``None``. filter_level : str or None, default "always" Specifies whether warnings are ignored, displayed, or turned into errors. Valid values are: * "error" - turns matching warnings into exceptions * "ignore" - discard the warning * "always" - always emit a warning * "default" - print the warning the first time it is generated from each location * "module" - print the warning the first time it is generated from each module * "once" - print the warning the first time it is generated check_stacklevel : bool, default True If True, displays the line that called the function containing the warning to show were the function is called. Otherwise, the line that implements the function is displayed. raise_on_extra_warnings : bool, default True Whether extra warnings not of the type `expected_warning` should cause the test to fail. match : str, optional Match warning message. Examples -------- >>> import warnings >>> with assert_produces_warning(): ... warnings.warn(UserWarning()) ... >>> with assert_produces_warning(False): ... warnings.warn(RuntimeWarning()) ... Traceback (most recent call last): ... AssertionError: Caused unexpected warning(s): ['RuntimeWarning']. >>> with assert_produces_warning(UserWarning): ... warnings.warn(RuntimeWarning()) Traceback (most recent call last): ... AssertionError: Did not see expected warning of class 'UserWarning'. ..warn:: This is *not* thread-safe. T)recordFNz&Did not see expected warning of class zDid not see warning z matching zCaused unexpected warning(s): )r^catch_warningsr_rrWarning issubclasscategoryrDeprecationWarning&_assert_raised_with_correct_stacklevelrsearchrMrKrrrlinenorr,) r$Z filter_levelr%r&r'rrZ saw_warningZmatched_messageZextra_warningsactual_warningrbrbrcassert_produces_warningY sR@      r2)r1rkcCsVddlm}m}||dd}d|jd|jd|j}|j|jksRt|dS)Nr) getframeinfostackr|zGWarning not set with correct stacklevel. File where warning is raised: rYz. Warning message: )inspectr3r4rrKr)r1r3r4Zcallerr!rbrbrcr. s r.c@s(eZdZdZddZddZddZdS) RNGContexta, Context manager to set the numpy random number generator speed. Returns to the original value upon exiting the context manager. Parameters ---------- seed : int Seed for numpy.random.seed Examples -------- with RNGContext(42): np.random.randn() cCs ||_dSr)r)selfrrbrbrc__init__ szRNGContext.__init__cCstj|_tj|jdSr)rrZ get_state start_staterr7rbrbrc __enter__ s zRNGContext.__enter__cCstj|jdSr)rrZ set_stater9)r7exc_type exc_value tracebackrbrbrc__exit__ szRNGContext.__exit__N)r __module__ __qualname____doc__r8r;r?rbrbrbrcr6 sr6cksDddl}dddh}||kr"td|j|f|dV||dS)au Context manager to temporarily register a CSV dialect for parsing CSV. Parameters ---------- name : str The name of the dialect. kwargs : mapping The parameters for the dialect. Raises ------ ValueError : the name of the dialect conflicts with a builtin one. See Also -------- csv : Python's CSV library. rNexcelz excel-tabunixz Cannot override builtin dialect.)csvrregister_dialectunregister_dialect)rrrEZ_BUILTIN_DIALECTSrbrbrcwith_csv_dialect s rHccsPddlm}|dkr|j}|j}|j}||||_dV||_||dS)Nr) expressions)Zpandas.core.computationrIZ _MIN_ELEMENTSZ USE_NUMEXPRZset_use_numexpr)ZuseZ min_elementsexprZolduseZoldminrbrbrc use_numexpr s  rKrcsFdks tdk r(tks(tddlfdd}|S)a  Decorator to run the same function multiple times in parallel. Parameters ---------- num_threads : int, optional The number of times the function is run in parallel. kwargs_list : list of dicts, optional The list of kwargs to update original function kwargs on different threads. Notes ----- This decorator does not pass the return value of the decorated function. Original from scikit-image: https://github.com/scikit-image/scikit-image/pull/1519 rNcs tfdd}|S)Ncs|rfdd}n fdd}g}tD]&}||}j||d}||q,|D] }|qX|D] }|qjdS)Ncstf|Sr)rrh)r kwargs_listrbrcrL rz?test_parallel..wrapper..inner..csSrrbrLrrbrcrN r)targetrr)rThreadrrr)rrZ update_kwargsthreadsrhZupdated_kwargsthread)funchas_kwargs_listrM num_threads threadingrNrcinnerI s    z-test_parallel..wrapper..innerr)rSrWrTrMrUrV)rSrcrH sztest_parallel..wrapper)rrrV)rUrMrrbrXrc test_parallel- s rYc@s,eZdZddgZeddZeddZdS)SubclassedSeriestestattrrcCstSrrZr:rbrbrc _constructora szSubclassedSeries._constructorcCstSrSubclassedDataFramer:rbrbrc_constructor_expanddime sz'SubclassedSeries._constructor_expanddimN)rr@rA _metadatapropertyr]r`rbrbrbrcrZ^ s  rZc@s*eZdZdgZeddZeddZdS)r_r[cCstSrr^r:rbrbrcr]m sz SubclassedDataFrame._constructorcCstSrr\r:rbrbrc_constructor_slicedq sz'SubclassedDataFrame._constructor_slicedN)rr@rArarbr]rcrbrbrbrcr_j s  r_c@seZdZeddZdS)SubclassedCategoricalcCstSr)rdr:rbrbrcr]w sz"SubclassedCategorical._constructorN)rr@rArbr]rbrbrbrcrdv srdrGc#sLddlddlfdd}jd}||z dVW5||XdS)a Context manager for temporarily setting a timezone. Parameters ---------- tz : str A string representing a valid timezone. Examples -------- >>> from datetime import datetime >>> from dateutil.tz import tzlocal >>> tzlocal().tzname(datetime.now()) 'IST' >>> with set_timezone('US/Eastern'): ... tzlocal().tzname(datetime.now()) ... 'EDT' rNcsB|dkr,z jd=Wq>tk r(Yq>Xn|jd<dS)NTZ)r\KeyErrortzsetrer[timerbrcsetTZ s  zset_timezone..setTZrf)r[rjr\r])rGrkZorig_tzrbrirc set_timezone| s  rlcs"rfdd}n fdd}|S)a` Create a function for calling on an array. Parameters ---------- alternative : function The function to be called on the array with no NaNs. Only used when 'skipna_alternative' is None. skipna_alternative : function The function to be called on the original array Returns ------- function cs |jSr)rr")skipna_alternativerbrcskipna_wrapper sz,_make_skipna_wrapper..skipna_wrappercs"|}t|dkrtjS|Sr )ZdropnarrrU)r#Znona) alternativerbrcrn s rb)rormrnrb)rormrc_make_skipna_wrapper s rp) rows_listcCstj}|||S)aW Convert list of CSV rows to single CSV-formatted string for current OS. This method is used for creating expected value of to_csv() method. Parameters ---------- rows_list : List[str] Each element represents the row of csv. Returns ------- str Expected output of to_csv() in current OS. )r[linesepr)rqseprbrbrcconvert_rows_list_to_csv_str srt)expected_exceptionrkcCsddl}|j|ddS)a$ Helper function to mark pytest.raises that have an external error message. Parameters ---------- expected_exception : Exception Expected error to raise. Returns ------- Callable Regular `pytest.raises` function with `match` equal to `None`. rN)r')rsZraises)rursrbrbrcexternal_error_raised srvcs@g}|D]2\|f|fddtD7}q|S)a Combine frame, functions from SelectionMixin._cython_table keys and expected result. Parameters ---------- ndframe : DataFrame or Series func_names_and_expected : Sequence of two items The first item is a name of a NDFrame method ('sum', 'prod') etc. The second item is the expected return value. Returns ------- list List of three items (DataFrame, function, expected result) cs"g|]\}}|kr|fqSrbrb)rrSrrm func_namendframerbrcr sz+get_cython_table_params..)r cython_table)ryZfunc_names_and_expectedresultsrbrwrcget_cython_table_params s  r|)op_namerkcsP|d}ztt|}Wn2tk rJtt|ddfdd}YnX|S)z The operator function for a given op name. Parameters ---------- op_name : string The op name, in form of "add" or "__add__". Returns ------- function A function performing the operation. rrNcs ||Srrb)r#rZroprbrcr! rz"get_op_from_name..)striproperatorAttributeError)r}Z short_opnameoprbr~rcget_op_from_name s r)N)N)N)r)T)rbr)r)r)N)NF)Tr)r&)TTr*)rr8)r9)r6T)r:T)NN)FTNNrN)T)rmN)rmN)rmr|N)rmN)rmN)rmN)rmN)rmN)rmN)rmrN)rmrN)rmN)rmN)rrrN)rm)N)N)N)NrN)NN)Nr)N)Nr)N)rFNN) TTrrNNNNNN)N)rN)N)N)rN)N)r| collectionsr contextlibrr functoolsrr{rr[rrrrrshutilrrrtypingr r r r r rrrrr^rnumpyrZ numpy.randomrrZpandas._config.localizationrrrZpandas._libs.librZpandas._libs.testingroZtestingrZpandas._typingrrrZ pandas.compatrrZpandas.core.dtypes.commonrrrr r!r"r#r$r%r&r'r(Zpandas.core.dtypes.missingr)Zpandasrgr*r+r,r-r.r/r0r1r2r3Zpandas.core.algorithmsr4r5Zpandas.core.arraysr6r7r8r9r:r;Zpandas.core.arrays.datetimeliker<Zpandas.io.commonr=Zpandas.io.formats.printingr>rrrZ_RAISE_NETWORK_ERROR_DEFAULTrA__annotations__rBrrFrGZALL_INT_DTYPESZALL_EA_INT_DTYPESfloatrJrKcomplexrLrMrOrPrQrRZ BOOL_DTYPESrSZ BYTES_DTYPESrTZ OBJECT_DTYPESZALL_REAL_DTYPESZALL_NUMPY_DTYPESrUZNaTZNAZ NULL_OBJECTSr-ResourceWarningr`rdrfrhrqrwryrrrrrrrr3rcrrrrrmapchrrrrrrrnrrorrrrrrr0r5rrrFrIrJrr1rXrrrBrnrlrqrsrtr^rvrzr{r~rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrZ_network_error_messagesZ_network_errno_valsrrr#Zwith_connectivity_checkr*r2WarningMessager.r6rHrKrYrZr_rdrlrprtrrvcorerMZSelectionMixinZ _cython_tableitemsrzr|rrbrbrbrcs      , 8 0          0 4,   m   ,      1-  -    ! S l u [( *%              3    nk   y1  *