zmc
2023-08-08 e792e9a60d958b93aef96050644f369feb25d61b
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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
U
¬ý°d˜Gã@söddlmZddlmZddlZddlmZmZddlZ    ddl
m Z ddl m Z ddlmZmZmZmZddlmZdd    lmZdd
lmZdd lmZmZdd lmZddddddddœdd„Zddddddddœdd„Zddddddœdd„Z dS) é)Ú annotations)Ú defaultdictN)ÚHashableÚIterable)ÚIntIndex)ÚNpDtype)Úis_integer_dtypeÚ is_list_likeÚis_object_dtypeÚ pandas_dtype)Ú SparseArray)Úfactorize_from_iterable)Ú    DataFrame)ÚIndexÚ default_index)ÚSeriesÚ_Fz$str | Iterable[str] | dict[str, str]ÚboolzNpDtype | Noner)Ú
prefix_sepÚdummy_naÚsparseÚ
drop_firstÚdtypeÚreturnc
sddlm}dddg}    t|tƒrv|dkr8|j|    d‰nt|ƒsJtdƒ‚n||‰‡fd    d
„}
|
ˆd ƒ|
ˆd ƒtˆtƒrˆt     ˆg¡‰tˆt
ƒr¦‡fd d„ˆj Dƒ‰ˆdkr´ˆj ‰tˆtƒrÌt     ˆg¡‰ntˆt
ƒrê‡fdd„ˆj Dƒ‰ˆj |j krüg} n*|dk    r|j |ddg} n|j|    dg} tˆ ¡ˆˆƒD]0\} } }t| d| |||||d}|  |¡q6|| dd}nt|ˆˆ||||d}|S)a£
    Convert categorical variable into dummy/indicator variables.
 
    Each variable is converted in as many 0/1 variables as there are different
    values. Columns in the output are each named after a value; if the input is
    a DataFrame, the name of the original variable is prepended to the value.
 
    Parameters
    ----------
    data : array-like, Series, or DataFrame
        Data of which to get dummy indicators.
    prefix : str, list of str, or dict of str, default None
        String to append DataFrame column names.
        Pass a list with length equal to the number of columns
        when calling get_dummies on a DataFrame. Alternatively, `prefix`
        can be a dictionary mapping column names to prefixes.
    prefix_sep : str, default '_'
        If appending prefix, separator/delimiter to use. Or pass a
        list or dictionary as with `prefix`.
    dummy_na : bool, default False
        Add a column to indicate NaNs, if False NaNs are ignored.
    columns : list-like, default None
        Column names in the DataFrame to be encoded.
        If `columns` is None then all the columns with
        `object`, `string`, or `category` dtype will be converted.
    sparse : bool, default False
        Whether the dummy-encoded columns should be backed by
        a :class:`SparseArray` (True) or a regular NumPy array (False).
    drop_first : bool, default False
        Whether to get k-1 dummies out of k categorical levels by removing the
        first level.
    dtype : dtype, default bool
        Data type for new columns. Only a single dtype is allowed.
 
    Returns
    -------
    DataFrame
        Dummy-coded data. If `data` contains other columns than the
        dummy-coded one(s), these will be prepended, unaltered, to the result.
 
    See Also
    --------
    Series.str.get_dummies : Convert Series of strings to dummy codes.
    :func:`~pandas.from_dummies` : Convert dummy codes to categorical ``DataFrame``.
 
    Notes
    -----
    Reference :ref:`the user guide <reshaping.dummies>` for more examples.
 
    Examples
    --------
    >>> s = pd.Series(list('abca'))
 
    >>> pd.get_dummies(s)
           a      b      c
    0   True  False  False
    1  False   True  False
    2  False  False   True
    3   True  False  False
 
    >>> s1 = ['a', 'b', np.nan]
 
    >>> pd.get_dummies(s1)
           a      b
    0   True  False
    1  False   True
    2  False  False
 
    >>> pd.get_dummies(s1, dummy_na=True)
           a      b    NaN
    0   True  False  False
    1  False   True  False
    2  False  False   True
 
    >>> df = pd.DataFrame({'A': ['a', 'b', 'a'], 'B': ['b', 'a', 'c'],
    ...                    'C': [1, 2, 3]})
 
    >>> pd.get_dummies(df, prefix=['col1', 'col2'])
       C  col1_a  col1_b  col2_a  col2_b  col2_c
    0  1    True   False   False    True   False
    1  2   False    True    True   False   False
    2  3    True   False   False   False    True
 
    >>> pd.get_dummies(pd.Series(list('abcaa')))
           a      b      c
    0   True  False  False
    1  False   True  False
    2  False  False   True
    3   True  False  False
    4   True  False  False
 
    >>> pd.get_dummies(pd.Series(list('abcaa')), drop_first=True)
           b      c
    0  False  False
    1   True  False
    2  False   True
    3  False  False
    4  False  False
 
    >>> pd.get_dummies(pd.Series(list('abc')), dtype=float)
         a    b    c
    0  1.0  0.0  0.0
    1  0.0  1.0  0.0
    2  0.0  0.0  1.0
    r©ÚconcatÚobjectÚstringÚcategoryN)Úincludez1Input must be a list-like for parameter `columns`csHt|ƒrDt|ƒˆjdksDd|›dt|ƒ›dˆjd›d}t|ƒ‚dS)Néz Length of 'z' (ú9) did not match the length of the columns being encoded (z).)r    ÚlenÚshapeÚ
ValueError)ÚitemÚnameÚlen_msg)Údata_to_encode©úSd:\z\workplace\vscode\pyvenv\venv\Lib\site-packages\pandas/core/reshape/encoding.pyÚ    check_len¡s
 ÿzget_dummies.<locals>.check_lenÚprefixrcsg|] }ˆ|‘qSr)r)©Ú.0Úcol)r,r)r*Ú
<listcomp>±szget_dummies.<locals>.<listcomp>csg|] }ˆ|‘qSr)r)r-)rr)r*r0ºsr ©Úaxis)Úexclude)r,rrrrr)rrr)Úpandas.core.reshape.concatrÚ
isinstancerZ select_dtypesr    Ú    TypeErrorÚstrÚ    itertoolsÚcycleÚdictÚcolumnsr#ZdropÚzipÚitemsÚ_get_dummies_1dÚappend)Údatar,rrr;rrrrZdtypes_to_encoder+Z with_dummiesr/ÚpreÚsepÚdummyÚresultr))r(r,rr*Ú get_dummies s`s 
 
 
 
 
 
 
 
 
 
ù    ù    rEc    sŠddlm}tt|ddƒ\}}    |dkr2t t¡}t|ƒ}
t|
ƒrJt    dƒ‚ddœdd    „} |spt
|    ƒdkrp| |ƒS|  ¡}|ržt
|    ƒ||d
k<|      t
|    ƒtj ¡}    |r¶t
|    ƒd kr¶| |ƒSt
|    ƒ} ˆdkrÌ|    } nt‡‡fd d „|    Dƒƒ} t|tƒrö|j}nd}|r
t|ƒrd}n|t t¡kr&d}nd}g}t
|ƒ}dd „tt
| ƒƒDƒ}|d
k}||}t |¡|}t||ƒD]\}}|| |¡qt|r¬|d d…}| d d…} t| |ƒD]D\}}ttjt
|ƒ|dt||ƒ||d}| t|||dd¡q¶||d ddSt|
tjƒr|
}ntj}tj| |dj|d dj}|sPd||d
k<|rv|dd…d d…f}| d d…} t||| |
dSdS)NrrF©Úcopyz1dtype=object is not a valid dtype for get_dummiesr)rcSs(t|tƒr|j}n tt|ƒƒ}t|dS)N)Úindex)r5rrHrr"r)r@rHr)r)r*Úget_empty_frameøs
 z(_get_dummies_1d.<locals>.get_empty_frameéÿÿÿÿr csg|]}ˆ›ˆ›|›‘qSr)r))r.Úlevel©r,rr)r*r0sz#_get_dummies_1d.<locals>.<listcomp>gcSsg|]}g‘qSr)r))r.rr)r)r*r0%s©r)Z sparse_indexÚ
fill_valuer)r@rHr&rG)r2rGr1)rHr;r)r4rr rÚnprrr r
r$r"rGÚinsertÚnanrr5rHrÚrangeZaranger<r?r ZonesrZbool_ZeyeZtakeÚTr)r@r,rrrrrrÚcodesÚlevelsZ_dtyperIZnumber_of_colsZ
dummy_colsrHrNZ sparse_seriesÚNZ
sp_indicesÚmaskZn_idxZndxÚcoder/ZixsZsarrZ    eye_dtypeZ    dummy_matr)rLr*r>ãsv     
    
 
  ü  r>z
None | strz%None | Hashable | dict[str, Hashable])r@rBÚdefault_categoryrcs®ddlm}t|tƒs*tdt|ƒj›ƒ‚| ¡ ¡ ¡rVt    d| ¡ ¡ 
¡›dƒ‚z|j ddd}Wntk
r„td    ƒ‚YnXt t ƒ}ˆd
kr¦t |jƒ|d <nftˆtƒrø|jD]>}| ˆ¡d‰tˆƒt|ƒkræt    d |›ƒ‚|ˆ |¡q¶ntd tˆƒj›ƒ‚|d
k    r’t|tƒrXt|ƒt|ƒks’dt|ƒ›dt|ƒ›d}t    |ƒ‚n:t|tƒr~tt||gt|ƒƒƒ}ntdt|ƒj›ƒ‚i}| ¡D]\‰}    ˆd
kr¼|     ¡}
n‡‡fdd„|    Dƒ}
|jd
d
…|    fjdd} t| dkƒr
t    d|  
¡›ƒ‚t| dkƒrjt|tƒr4|
 |ˆ¡nt    d|  ¡›ƒ‚||jd
d
…|    f| dkfdd} n|jd
d
…|    f} tj|
dd} | |  ¡ ¡d|ˆ<qžt|ƒS)a>
    Create a categorical ``DataFrame`` from a ``DataFrame`` of dummy variables.
 
    Inverts the operation performed by :func:`~pandas.get_dummies`.
 
    .. versionadded:: 1.5.0
 
    Parameters
    ----------
    data : DataFrame
        Data which contains dummy-coded variables in form of integer columns of
        1's and 0's.
    sep : str, default None
        Separator used in the column names of the dummy categories they are
        character indicating the separation of the categorical names from the prefixes.
        For example, if your column names are 'prefix_A' and 'prefix_B',
        you can strip the underscore by specifying sep='_'.
    default_category : None, Hashable or dict of Hashables, default None
        The default category is the implied category when a value has none of the
        listed categories specified with a one, i.e. if all dummies in a row are
        zero. Can be a single value for all variables or a dict directly mapping
        the default categories to a prefix of a variable.
 
    Returns
    -------
    DataFrame
        Categorical data decoded from the dummy input-data.
 
    Raises
    ------
    ValueError
        * When the input ``DataFrame`` ``data`` contains NA values.
        * When the input ``DataFrame`` ``data`` contains column names with separators
          that do not match the separator specified with ``sep``.
        * When a ``dict`` passed to ``default_category`` does not include an implied
          category for each prefix.
        * When a value in ``data`` has more than one category assigned to it.
        * When ``default_category=None`` and a value in ``data`` has no category
          assigned to it.
    TypeError
        * When the input ``data`` is not of type ``DataFrame``.
        * When the input ``DataFrame`` ``data`` contains non-dummy data.
        * When the passed ``sep`` is of a wrong data type.
        * When the passed ``default_category`` is of a wrong data type.
 
    See Also
    --------
    :func:`~pandas.get_dummies` : Convert ``Series`` or ``DataFrame`` to dummy codes.
    :class:`~pandas.Categorical` : Represent a categorical variable in classic.
 
    Notes
    -----
    The columns of the passed dummy data should only include 1's and 0's,
    or boolean values.
 
    Examples
    --------
    >>> df = pd.DataFrame({"a": [1, 0, 0, 1], "b": [0, 1, 0, 0],
    ...                    "c": [0, 0, 1, 0]})
 
    >>> df
       a  b  c
    0  1  0  0
    1  0  1  0
    2  0  0  1
    3  1  0  0
 
    >>> pd.from_dummies(df)
    0     a
    1     b
    2     c
    3     a
 
    >>> df = pd.DataFrame({"col1_a": [1, 0, 1], "col1_b": [0, 1, 0],
    ...                    "col2_a": [0, 1, 0], "col2_b": [1, 0, 0],
    ...                    "col2_c": [0, 0, 1]})
 
    >>> df
          col1_a  col1_b  col2_a  col2_b  col2_c
    0       1       0       0       1       0
    1       0       1       1       0       0
    2       1       0       0       0       1
 
    >>> pd.from_dummies(df, sep="_")
        col1    col2
    0    a       b
    1    b       a
    2    a       c
 
    >>> df = pd.DataFrame({"col1_a": [1, 0, 0], "col1_b": [0, 1, 0],
    ...                    "col2_a": [0, 1, 0], "col2_b": [1, 0, 0],
    ...                    "col2_c": [0, 0, 0]})
 
    >>> df
          col1_a  col1_b  col2_a  col2_b  col2_c
    0       1       0       0       1       0
    1       0       1       1       0       0
    2       0       0       0       0       0
 
    >>> pd.from_dummies(df, sep="_", default_category={"col1": "d", "col2": "e"})
        col1    col2
    0    a       b
    1    b       a
    2    d       e
    rrz>Expected 'data' to be a 'DataFrame'; Received 'data' of type: z.Dummy DataFrame contains NA value in column: 'ú'ÚbooleanFrFz(Passed DataFrame contains non-dummy dataNÚz$Separator not specified for column: zFExpected 'sep' to be of type 'str' or 'None'; Received 'sep' of type: zLength of 'default_category' (r!ú)znExpected 'default_category' to be of type 'None', 'Hashable', or 'dict'; Received 'default_category' of type: cs g|]}|tˆˆƒd…‘qS)N)r"r-©r,rBr)r*r0ýsz from_dummies.<locals>.<listcomp>r r1zEDummy DataFrame contains multi-assignment(s); First instance in row: zEDummy DataFrame contains unassigned value(s); First instance in row: rrM)r4rr5rr6ÚtypeÚ__name__ZisnaÚanyr$ZidxmaxZastyperÚlistr;r7Úsplitr"r?r:rr<r=rGÚlocÚsumZidxminrOÚarrayZto_numpyZnonzero)r@rBrYrZdata_to_decodeZvariables_slicer/r'Zcat_dataZ prefix_sliceZcatsÚassignedZ
data_sliceZ
cats_arrayr)r^r*Ú from_dummiesQs|n 
ÿÿ
 
ÿ
 ÿ
 ÿÿ
 
 ÿ  ÿÿrh)NrFNFFN)rFFFN)NN)!Ú
__future__rÚ collectionsrr8ÚtypingrrÚnumpyrOZpandas._libs.sparserZpandas._typingrZpandas.core.dtypes.commonrr    r
r Zpandas.core.arraysr Zpandas.core.arrays.categoricalr Zpandas.core.framerZpandas.core.indexes.apirrZpandas.core.seriesrrEr>rhr)r)r)r*Ú<module>s<        øGùpý