1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
U
¬ý°drã @s@ddlmZddlmZmZmZmZmZddlZ    ddl
m Z ddl m Z mZmZmZddlmZmZddlmZddlmZmZmZmZmZdd    lmZmZddlm m!Z"dd
l#m$Z$dd l%m&Z&dd l'm(Z(m)Z)m*Z*dd l+m,Z,ddl-m.Z.ddl/m0Z0erddl1m2Z2edƒee$ddddGdddddddddœdd„ƒƒZ3dddddddddœd d!„Z4dHd"ddd#œd$d%„Z5dIddd&œd'd(„Z6dJdd)œd*d+„Z7dKddd,œd-d.„Z8d/d0„Z9edƒee$d1dde j:e j:d2œdd3d4d4dd5œd6d1„ƒƒZ;dLdddddd7œd8d9„Z<dMddddd:œd;d<„Z=dNd>d?œd@dA„Z>dBdBdCdDœdEdF„Z?dS)Oé)Ú annotations)Ú TYPE_CHECKINGÚCallableÚHashableÚSequenceÚcastN)Úlib)Ú AggFuncTypeÚAggFuncTypeBaseÚAggFuncTypeDictÚ
IndexLabel)ÚAppenderÚ Substitution)Úmaybe_downcast_to_dtype)Úis_extension_array_dtypeÚis_integer_dtypeÚ is_list_likeÚis_nested_list_likeÚ    is_scalar)Ú ABCDataFrameÚ    ABCSeries)Ú _shared_docs)ÚGrouper)ÚIndexÚ
MultiIndexÚget_objs_combined_axis)Úconcat)Úcartesian_product)ÚSeries©Ú    DataFramez
data : DataFrameÚ pivot_tableé)ÚindentsÚmeanFTÚAllr r    Úboolr)ÚdataÚaggfuncÚmarginsÚdropnaÚ margins_nameÚobservedÚsortÚreturnc Cs¬t|ƒ}t|ƒ}t|tƒr‚g} g} |D]>} t|||||| ||||    |
d }|  |¡|  t| d| ƒ¡q&t| | dd}|j|ddSt||||||||||    |
ƒ }|j|ddS)N)
ÚvaluesÚindexÚcolumnsÚ
fill_valuer(r)r*r+r,r-Ú__name__r")ÚkeysÚaxisr!)Úmethod)Ú _convert_byÚ
isinstanceÚlistÚ__internal_pivot_tableÚappendÚgetattrrZ __finalize__)r'r/r0r1r(r2r)r*r+r,r-Úpiecesr4ÚfuncZ_tableÚtable©r@úPd:\z\workplace\vscode\pyvenv\venv\Lib\site-packages\pandas/core/reshape/pivot.pyr!8sJ
õ
õ z!AggFuncTypeBase | AggFuncTypeDictc  Cs”||} |dk    } | r¸t|ƒr*d} t|ƒ}n
d} |g}|D]}||kr8t|ƒ‚q8g}| |D]@}t|tƒrn|j}z||kr‚| |¡WqZtk
r˜YqZXqZt|ƒt|j    ƒkrú||}nB|j    }| D].}z| 
|¡}WqÂtt tfk
rîYqÂXqÂt|ƒ}|j | |    |
d}|  |¡}|r¶t|tƒr¶t|j    ƒr¶|jdd}|D]r}||krBt||ƒrB||krBt||ƒsBt||tƒsBt||jtjƒrBt||||jƒ||<qB|}|jjdkr@|r@|jjdt|ƒ…}g}tt|ƒt| ƒƒD]<}|jj|}|dks||kr(| |¡n
| |¡qø| |¡}|s²t|jtƒr|tjt|jjƒ|jjd}|j|d    d
}t|j    tƒr²tjt|j    jƒ|j    jd}|j|dd
}|
dkrÔt|tƒrÔ|jdd
}|dk    rì|j|d d }|r&|r ||  ¡j!dd
}t"|||||||||d     }| rN| sN|j    jdkrN|j#d    dd
}t|ƒd    krpt|ƒd    krp|j$}t|tƒr|r|jddd}|S)zL
    Helper of :func:`pandas.pivot_table` for any non-list ``aggfunc``.
    NTF)r,r-Úall)Úhowr"©Únamesr©r5Zinfer)Zdowncast)ÚrowsÚcolsr(r,r+r2)rCr5)%rr9ÚKeyErrorr8rÚkeyr;Ú    TypeErrorÚlenr1ZdropÚ
ValueErrorÚgroupbyÚaggrr*rÚdtypeÚnprr0ÚnlevelsrEÚrangeÚunstackrÚ from_arraysrÚlevelsÚreindexZ
sort_indexÚfillnaZnotnarBÚ _add_marginsZ    droplevelÚT)r'r/r0r1r(r2r)r*r+r,r-r4Z values_passedZ values_multiÚiZ    to_filterÚxrJZgroupedZaggedÚvr?Z index_namesZ
to_unstackÚnameÚmr@r@rAr:qs¾
 
 
 
 
 ÿ
þý
üÿ  
 
ÿ
ÿ 
÷ r:zDataFrame | Series)r?r'r+c        Cst|tƒstdƒ‚d|›d}    |jjD]}
||j |
¡kr&t|    ƒ‚q&t||||ƒ} |jdkrŠ|jjdd…D]}
||j |
¡krlt|    ƒ‚qlt    |ƒdkr®|fdt    |ƒd} n|} |sÖt|t
ƒrÖ|  t | | |iƒ¡S|rt ||||||||ƒ} t| tƒs| S| \}}}n>t|tƒst‚t|||||||ƒ} t| tƒsB| S| \}}}|j|j|d}|D]0}t|tƒr~| |||<n| |d||<q`dd    lm}||t| gƒd
j}|jj}t|jƒD]:}t|ƒr֐qÄ| |g¡j}||jt|fd ||<qÄ|  |¡}||j_|S) Nz&margins_name argument must be a stringzConflicting name "z " in marginsér"©Ú)r2rr)r1)Úargs)r8ÚstrrMr0rEÚget_level_valuesÚ_compute_grand_marginÚndimr1rLrÚ_appendrÚ_generate_marginal_resultsÚtuplerÚAssertionErrorÚ)_generate_marginal_results_without_valuesrWÚpandasr rrZÚsetZdtypesrZ select_dtypesÚapplyr)r?r'r/rGrHr(r,r+r2ÚmsgÚlevelÚ grand_marginrJZmarginal_result_setÚresultÚ margin_keysÚ
row_marginÚkr Z margin_dummyZ    row_namesrPr@r@rArYs|
 
 
 
 ÿ  ÿ 
 
ÿ
rY)r'r+c    Cs¶|r¤i}|| ¡D]Š\}}zlt|tƒr:t||ƒƒ||<nLt|tƒrzt||tƒrht|||ƒƒ||<q†|||ƒ||<n ||ƒ||<Wqtk
rœYqXq|S|||jƒiSdS©N)Úitemsr8rdr<ÚdictrKr0)r'r/r(r+rrrvr]r@r@rArfVs
 
rf)r+csøtˆƒdkrxg}g}    ‡‡fdd„}
t|ƒdkrœ|||j||d |¡} d} |jd| |dD]8\} }|
| ƒ}| ¡}| | ||<| |¡|     |¡q`n²ddlm}d} |jd| |dD]\} }tˆƒdkrÚ|
| ƒ}nˆ}| |¡|| |¡ƒj}t    |j
t ƒr$t j |g|j
j dgd|_
nt|g|j
jd    |_
| |¡|     |¡q¼|sX|St|| d
}t|ƒdkr‚|Sn
|}|j}    tˆƒdkrÞ|ˆ|jˆ|d |¡}| ¡}tˆƒgtttˆƒƒƒ}|j
 |¡|_
nttj|jd }||    |fS) Nrcs|ˆfdtˆƒdS)Nrar"©rL)rJ©rHr+r@rAÚ_all_keyusz,_generate_marginal_results.<locals>._all_key©r,r"©rqr5r,rrD©r^rF©r0)rLrNrOÚcopyr;rmr rorZr8r0rÚ from_tuplesrErr^rr1Ústackr9rSZreorder_levelsrrQÚnan)r?r'r/rGrHr(r,r+Z table_piecesrtr|ÚmarginZcat_axisrJZpieceÚall_keyr Ztransformed_piecersruZ    new_orderr@r{rArimsV  
 
 
 ÿ
 
  ri)r?r+c sÞtˆƒdkr˜g}‡‡fdd„}t|ƒdkr`||j||d |¡}    |ƒ}
|    ||
<|} | |
¡q¢|jdd|d |¡}    |ƒ}
|    ||
<|} | |
¡| Sn
|} |j}tˆƒrÄ|ˆjˆ|d |¡} nttj| jd} | || fS)Nrcs&tˆƒdkrˆSˆfdtˆƒdS)Nr"rarzr@r{r@rAr|Äs z;_generate_marginal_results_without_values.<locals>._all_keyr}r~r€)rLrNror;r1rrQr„) r?r'rGrHr(r,r+rtr|r…r†rsrur@r{rArl·s*       
rlcCsF|dkrg}n4t|ƒs2t|tjtttfƒs2t|ƒr:|g}nt|ƒ}|Srw)    rr8rQZndarrayrrrÚcallabler9)Zbyr@r@rAr7ãsÿþýr7Úpivot)r0r/r zIndexLabel | lib.NoDefault)r'r1r0r/r.c stt |¡}ˆjdd‰ˆj ¡ˆ_dd„ˆjjDƒˆj_|tjkrz|tjk    rXt |¡}ng}|tjk}ˆj|||d}nÖ|tjkrÂtˆjt    ƒr¬‡fdd„t
ˆjj ƒDƒ}qÚt ˆjˆjj dg}n‡fdd„t |¡Dƒ}‡fd    d„|Dƒ}    | |    ¡t     |¡}
t|ƒr<t|tƒs<ttt|ƒ}ˆjˆ|j|
|d
}nˆjˆ|j|
d }| |¡} d d„| jjDƒ| j_| S) NF)ÚdeepcSsg|]}|dk    r|ntj‘qSrw©rÚ    NoDefault©Ú.0r^r@r@rAÚ
<listcomp>szpivot.<locals>.<listcomp>)r;csg|]}ˆj |¡‘qSr@)r0re)rr[©r'r@rArŽsrcsg|] }ˆ|‘qSr@r@)rÚidxrr@rArŽscsg|] }ˆ|‘qSr@r@)rÚcolrr@rArŽs)r0r1r€cSsg|]}|tjk    r|nd‘qSrwrŠrŒr@r@rArŽ.s)ÚcomZconvert_to_list_likerr0rErr‹Z    set_indexr8rrSrRrr^ÚextendrUrrjrrrZ _constructorZ_valuesZ_constructor_slicedrT) r'r1r0r/Zcolumns_listlikerHr;ZindexedZ
index_listZ data_columnsZ
multiindexrsr@rrArˆñsL    
  ÿ
 
 
 
ÿ
 
 
ÿ
 
ÿ
ÿ
)r)r+r*Ú    normalizer.c
CsX|dkr|dk    rtdƒ‚|dk    r0|dkr0tdƒ‚t|ƒs>|g}t|ƒsL|g}d}
dd„||Dƒ} | rtt| ddd}
t||d    d
}t||d d
}t||ƒ\} } }}d d lm}tt| |ƒƒtt||ƒƒ–}|||
d}|dkròd |d<t    d dœ}n||d<d|i}|j
d| ||||dœ|—Ž}|    dk    r8t ||    ||d}|j | d d}|j |dd}|S)aº
    Compute a simple cross tabulation of two (or more) factors.
 
    By default, computes a frequency table of the factors unless an
    array of values and an aggregation function are passed.
 
    Parameters
    ----------
    index : array-like, Series, or list of arrays/Series
        Values to group by in the rows.
    columns : array-like, Series, or list of arrays/Series
        Values to group by in the columns.
    values : array-like, optional
        Array of values to aggregate according to the factors.
        Requires `aggfunc` be specified.
    rownames : sequence, default None
        If passed, must match number of row arrays passed.
    colnames : sequence, default None
        If passed, must match number of column arrays passed.
    aggfunc : function, optional
        If specified, requires `values` be specified as well.
    margins : bool, default False
        Add row/column margins (subtotals).
    margins_name : str, default 'All'
        Name of the row/column that will contain the totals
        when margins is True.
    dropna : bool, default True
        Do not include columns whose entries are all NaN.
    normalize : bool, {'all', 'index', 'columns'}, or {0,1}, default False
        Normalize by dividing all values by the sum of values.
 
        - If passed 'all' or `True`, will normalize over all values.
        - If passed 'index' will normalize over each row.
        - If passed 'columns' will normalize over each column.
        - If margins is `True`, will also normalize margin values.
 
    Returns
    -------
    DataFrame
        Cross tabulation of the data.
 
    See Also
    --------
    DataFrame.pivot : Reshape data based on column values.
    pivot_table : Create a pivot table as a DataFrame.
 
    Notes
    -----
    Any Series passed will have their name attributes used unless row or column
    names for the cross-tabulation are specified.
 
    Any input passed containing Categorical data will have **all** of its
    categories included in the cross-tabulation, even if the actual data does
    not contain any instances of a particular category.
 
    In the event that there aren't overlapping indexes an empty DataFrame will
    be returned.
 
    Reference :ref:`the user guide <reshaping.crosstabulations>` for more examples.
 
    Examples
    --------
    >>> a = np.array(["foo", "foo", "foo", "foo", "bar", "bar",
    ...               "bar", "bar", "foo", "foo", "foo"], dtype=object)
    >>> b = np.array(["one", "one", "one", "two", "one", "one",
    ...               "one", "two", "two", "two", "one"], dtype=object)
    >>> c = np.array(["dull", "dull", "shiny", "dull", "dull", "shiny",
    ...               "shiny", "dull", "shiny", "shiny", "shiny"],
    ...              dtype=object)
    >>> pd.crosstab(a, [b, c], rownames=['a'], colnames=['b', 'c'])
    b   one        two
    c   dull shiny dull shiny
    a
    bar    1     2    1     0
    foo    2     2    1     2
 
    Here 'c' and 'f' are not represented in the data and will not be
    shown in the output because dropna is True by default. Set
    dropna=False to preserve categories with no data.
 
    >>> foo = pd.Categorical(['a', 'b'], categories=['a', 'b', 'c'])
    >>> bar = pd.Categorical(['d', 'e'], categories=['d', 'e', 'f'])
    >>> pd.crosstab(foo, bar)
    col_0  d  e
    row_0
    a      1  0
    b      0  1
    >>> pd.crosstab(foo, bar, dropna=False)
    col_0  d  e  f
    row_0
    a      1  0  0
    b      0  1  0
    c      0  0  0
    Nz&aggfunc cannot be used without values.z)values cannot be used without an aggfunc.cSsg|]}t|ttfƒr|‘qSr@)r8rr)rr\r@r@rArŽ«szcrosstab.<locals>.<listcomp>TF)Z    intersectr-Úrow©Úprefixr‘rrr€Ú    __dummy__)r(r2r()r0r1r)r+r*)r”r)r+)r0r5r")r1r5)r˜) rMrrÚ
_get_namesÚ_build_names_mapperrmr ryÚziprLr!Ú
_normalizeZ rename_axis)r0r1r/ÚrownamesÚcolnamesr(r)r+r*r”Z
common_idxZ    pass_objsÚrownames_mapperÚunique_rownamesÚcolnames_mapperÚunique_colnamesr r'ZdfÚkwargsr?r@r@rAÚcrosstab5sfjû   þ  ÿúù
ÿr¤)r?r)r+r.c
CsHt|ttfƒsRdddœ}z ||}Wn,tk
rP}ztdƒ|‚W5d}~XYnX|dkrÎdd„dd„d    d„d
œ}|d |d <z ||}Wn,tk
r¶}ztdƒ|‚W5d}~XYnX||ƒ}| d ¡}nv|d kr<|j}|j}    |jddd…fj    }
||
k||
k@rt|›dƒ‚|jdd…df} |jddd…f} |jdd…dd…f}t
||dd}|dkr˜| |   ¡} t || gdd}| d ¡}|    |_n¢|dkrÊ| |   ¡} |  | ¡}| d ¡}||_np|d ksÞ|d kr2| |   ¡} | |   ¡} d| j|<t || gdd}|  | ¡}| d ¡}||_|    |_ntdƒ‚ntdƒ‚|S)Nr0r1)rr"zNot a valid normalize argumentFcSs||jddjddS©Nr"rFr©Úsum©r\r@r@rAÚ<lambda>îóz_normalize.<locals>.<lambda>cSs || ¡Srwr¦r¨r@r@rAr©ïrªcSs|j|jddddSr¥)Údivr§r¨r@r@rAr©ðrª)rBr1r0rBTréÿÿÿÿz not in pivoted DataFrame)r”r)r"rFzNot a valid margins argument)r8r&rdrIrMrXr0r1Zilocr^rœr§rrhÚloc) r?r”r)r+Z    axis_subsÚerrZ normalizersÚfZ table_indexZ table_columnsZlast_ind_or_colZ column_marginZ index_marginr@r@rArœásd
 ý  
 
 
 
 
 
 
 
 
 
rœr•rdr–cCs„|dkrVg}t|ƒD]>\}}t|tƒr>|jdk    r>| |j¡q| |›d|›¡qn*t|ƒt|ƒkrntdƒ‚t|tƒs€t|ƒ}|S)NÚ_z*arrays and names must have the same length)Ú    enumerater8rr^r;rLrkr9)ZarrsrEr—r[Zarrr@r@rAr™1s
r™z    list[str]z;tuple[dict[str, str], list[str], dict[str, str], list[str]])rržr.cs’dd„}t|ƒ t|ƒ¡}||ƒ||ƒB|B‰‡fdd„t|ƒDƒ}‡fdd„t|ƒDƒ}‡fdd„t|ƒDƒ}‡fdd„t|ƒDƒ}||||fS)    a¤
    Given the names of a DataFrame's rows and columns, returns a set of unique row
    and column names and mappers that convert to original names.
 
    A row or column name is replaced if it is duplicate among the rows of the inputs,
    among the columns of the inputs or between the rows and the columns.
 
    Parameters
    ----------
    rownames: list[str]
    colnames: list[str]
 
    Returns
    -------
    Tuple(Dict[str, str], List[str], Dict[str, str], List[str])
 
    rownames_mapper: dict[str, str]
        a dictionary with new row names as keys and original rownames as values
    unique_rownames: list[str]
        a list of rownames with duplicate names replaced by dummy names
    colnames_mapper: dict[str, str]
        a dictionary with new column names as keys and original column names as values
    unique_colnames: list[str]
        a list of column names with duplicate names replaced by dummy names
 
    cstƒ‰‡fdd„|DƒS)Ncsh|]}|ˆkr|’qSr@r@rŒ©Úseenr@rAÚ    <setcomp>bsz>_build_names_mapper.<locals>.get_duplicates.<locals>.<setcomp>)rnrDr@r²rAÚget_duplicates`sz+_build_names_mapper.<locals>.get_duplicatescs$i|]\}}|ˆkrd|›|“qS©Zrow_r@©rr[r^©Z    dup_namesr@rAÚ
<dictcomp>gsz'_build_names_mapper.<locals>.<dictcomp>cs&g|]\}}|ˆkrd|›n|‘qSr¶r@r·r¸r@rArŽjsz'_build_names_mapper.<locals>.<listcomp>cs$i|]\}}|ˆkrd|›|“qS©Zcol_r@r·r¸r@rAr¹nscs&g|]\}}|ˆkrd|›n|‘qSrºr@r·r¸r@rArŽqs)rnÚ intersectionr±)rržrµZ shared_namesrŸr r¡r¢r@r¸rAršBs 
ÿ
ÿ
ÿ
ÿrš)
NNNr$NFTr%FT)Nr%N)r%)r%)r%)NNNNFr%TF)r%)r•)@Ú
__future__rÚtypingrrrrrÚnumpyrQZ pandas._libsrZpandas._typingr    r
r r Zpandas.util._decoratorsr rZpandas.core.dtypes.castrZpandas.core.dtypes.commonrrrrrZpandas.core.dtypes.genericrrZpandas.core.commonÚcoreÚcommonr’Zpandas.core.framerZpandas.core.groupbyrZpandas.core.indexes.apirrrZpandas.core.reshape.concatrZpandas.core.reshape.utilrZpandas.core.seriesrrmr r!r:rYrfrirlr7r‹rˆr¤rœr™ršr@r@r@rAÚ<module>s|         õ"7÷UÿÿQù,ûEö.ÿP