zmc
2023-12-22 9fdbf60165db0400c2e8e6be2dc6e88138ac719a
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
U
¬ý°dq/ã@sÄdZddlmZddlmZddlZddlmZddl    m
Z
ddl m Z m Z ddlmZdd    lmZerxdd
lmZmZGd d „d ƒZe ed dddgddGdd„dee ƒƒZGdd„dee ƒZdS)zSparse accessoré)Ú annotations)Ú TYPE_CHECKINGN)Úimport_optional_dependency)Úfind_common_type)ÚPandasDelegateÚdelegate_names)Ú SparseArray)Ú SparseDtype)Ú    DataFrameÚSeriesc@s(eZdZdZd    ddœdd„Zdd„ZdS)
Ú BaseAccessorz5Can only use the '.sparse' accessor with Sparse data.NÚNone©ÚreturncCs||_| |¡dS©N)Ú_parentÚ    _validate©ÚselfÚdata©rúYd:\z\workplace\vscode\pyvenv\venv\Lib\site-packages\pandas/core/arrays/sparse/accessor.pyÚ__init__szBaseAccessor.__init__cCst‚dSr)ÚNotImplementedErrorrrrrr!szBaseAccessor._validate)N)Ú__name__Ú
__module__Ú __qualname__Ú_validation_msgrrrrrrr sr ZnpointsÚdensityÚ
fill_valueÚ    sp_valuesÚproperty)Útypc@s\eZdZdZdd„Zdd„Zdd„Zedd    d
d œd d „ƒZdd    dœdd„Z    d
dœdd„Z
dS)ÚSparseAccessorzH
    Accessor for SparseSparse from other sparse matrix data types.
    cCst|jtƒst|jƒ‚dSr)Ú
isinstanceÚdtyper    ÚAttributeErrorrrrrrr-s zSparseAccessor._validatecOst|jj|ƒSr)ÚgetattrrÚarray©rÚnameÚargsÚkwargsrrrÚ_delegate_property_get1sz%SparseAccessor._delegate_property_getcOs0|dkr|j||ŽS|dkr(|j||ŽSt‚dS)NÚfrom_cooÚto_coo)r.r/Ú
ValueErrorr)rrrÚ_delegate_method4s
  zSparseAccessor._delegate_methodFÚboolr )Ú dense_indexrcCs:ddlm}ddlm}|||d}||j|jdd}|S)am
        Create a Series with sparse values from a scipy.sparse.coo_matrix.
 
        Parameters
        ----------
        A : scipy.sparse.coo_matrix
        dense_index : bool, default False
            If False (default), the index consists of only the
            coords of the non-null entries of the original coo_matrix.
            If True, the index consists of the full sorted
            (row, col) coordinates of the coo_matrix.
 
        Returns
        -------
        s : Series
            A Series with sparse values.
 
        Examples
        --------
        >>> from scipy import sparse
 
        >>> A = sparse.coo_matrix(
        ...     ([3.0, 1.0, 2.0], ([1, 0, 0], [0, 2, 3])), shape=(3, 4)
        ... )
        >>> A
        <3x4 sparse matrix of type '<class 'numpy.float64'>'
        with 3 stored elements in COOrdinate format>
 
        >>> A.todense()
        matrix([[0., 0., 1., 2.],
        [3., 0., 0., 0.],
        [0., 0., 0., 0.]])
 
        >>> ss = pd.Series.sparse.from_coo(A)
        >>> ss
        0  2    1.0
           3    2.0
        1  0    3.0
        dtype: Sparse[float64, nan]
        r©r )Úcoo_to_sparse_series)r3F)ÚindexÚcopy)Úpandasr Ú&pandas.core.arrays.sparse.scipy_sparser5r(r6)ÚclsÚAr3r r5Úresultrrrr.<s
*   zSparseAccessor.from_coo©r©é©Ú sort_labelscCs.ddlm}||j|||d\}}}|||fS)a    
        Create a scipy.sparse.coo_matrix from a Series with MultiIndex.
 
        Use row_levels and column_levels to determine the row and column
        coordinates respectively. row_levels and column_levels are the names
        (labels) or numbers of the levels. {row_levels, column_levels} must be
        a partition of the MultiIndex level names (or numbers).
 
        Parameters
        ----------
        row_levels : tuple/list
        column_levels : tuple/list
        sort_labels : bool, default False
            Sort the row and column labels before forming the sparse matrix.
            When `row_levels` and/or `column_levels` refer to a single level,
            set to `True` for a faster execution.
 
        Returns
        -------
        y : scipy.sparse.coo_matrix
        rows : list (row labels)
        columns : list (column labels)
 
        Examples
        --------
        >>> s = pd.Series([3.0, np.nan, 1.0, 3.0, np.nan, np.nan])
        >>> s.index = pd.MultiIndex.from_tuples(
        ...     [
        ...         (1, 2, "a", 0),
        ...         (1, 2, "a", 1),
        ...         (1, 1, "b", 0),
        ...         (1, 1, "b", 1),
        ...         (2, 1, "b", 0),
        ...         (2, 1, "b", 1)
        ...     ],
        ...     names=["A", "B", "C", "D"],
        ... )
        >>> s
        A  B  C  D
        1  2  a  0    3.0
                 1    NaN
           1  b  0    1.0
                 1    3.0
        2  1  b  0    NaN
                 1    NaN
        dtype: float64
 
        >>> ss = s.astype("Sparse")
        >>> ss
        A  B  C  D
        1  2  a  0    3.0
                 1    NaN
           1  b  0    1.0
                 1    3.0
        2  1  b  0    NaN
                 1    NaN
        dtype: Sparse[float64, nan]
 
        >>> A, rows, columns = ss.sparse.to_coo(
        ...     row_levels=["A", "B"], column_levels=["C", "D"], sort_labels=True
        ... )
        >>> A
        <3x4 sparse matrix of type '<class 'numpy.float64'>'
        with 3 stored elements in COOrdinate format>
        >>> A.todense()
        matrix([[0., 0., 1., 3.],
        [3., 0., 0., 0.],
        [0., 0., 0., 0.]])
 
        >>> rows
        [(1, 1), (1, 2), (2, 1)]
        >>> columns
        [('a', 0), ('a', 1), ('b', 0), ('b', 1)]
        r)Úsparse_series_to_coor@)r9rBr)rZ
row_levelsZ column_levelsrArBr;ÚrowsÚcolumnsrrrr/nsK ÿ zSparseAccessor.to_coorcCs,ddlm}||jj ¡|jj|jjddS)aà
        Convert a Series from sparse values to dense.
 
        Returns
        -------
        Series:
            A Series with the same values, stored as a dense array.
 
        Examples
        --------
        >>> series = pd.Series(pd.arrays.SparseArray([0, 1, 0]))
        >>> series
        0    0
        1    1
        2    0
        dtype: Sparse[int64, 0]
 
        >>> series.sparse.to_dense()
        0    0
        1    1
        2    0
        dtype: int64
        rr4F)r6r*r7)r8r rr(Úto_denser6r*)rr rrrrEÀs 
üzSparseAccessor.to_denseN)F)r=r>F) rrrÚ__doc__rr-r1Ú classmethodr.r/rErrrrr#%s1Rr#c@s`eZdZdZdd„Zedddœdd„ƒZddœd    d
„Zd d „Ze    d dœdd„ƒZ
e dd„ƒZ dS)ÚSparseFrameAccessorz-
    DataFrame accessor for sparse data.
    cCs&|j}tdd„|Dƒƒs"t|jƒ‚dS)Ncss|]}t|tƒVqdSr)r$r    )Ú.0ÚtrrrÚ    <genexpr>ész0SparseFrameAccessor._validate.<locals>.<genexpr>)ÚdtypesÚallr&r)rrrLrrrrçszSparseFrameAccessor._validateNr
rcCsÊddlm}ddlm}| ¡}| |||¡\}}|j\}}| ¡|j}|j    }    |j
}
t |
j dƒ} g} t |ƒD]H} t|    | |    | dƒ}||||dd}t |
||| ¡}|  |¡qn|j| ||ddS)aè
        Create a new DataFrame from a scipy sparse matrix.
 
        Parameters
        ----------
        data : scipy.sparse.spmatrix
            Must be convertible to csc format.
        index, columns : Index, optional
            Row and column labels to use for the resulting DataFrame.
            Defaults to a RangeIndex.
 
        Returns
        -------
        DataFrame
            Each column of the DataFrame is stored as a
            :class:`arrays.SparseArray`.
 
        Examples
        --------
        >>> import scipy.sparse
        >>> mat = scipy.sparse.eye(3)
        >>> pd.DataFrame.sparse.from_spmatrix(mat)
             0    1    2
        0  1.0  0.0  0.0
        1  0.0  1.0  0.0
        2  0.0  0.0  1.0
        r)ÚIntIndex©r
r?F)Zcheck_integrity)rDr6Zverify_integrity)Zpandas._libs.sparserNr8r
ZtocscÚ _prep_indexÚshapeZ sort_indicesÚindicesÚindptrrr    r%ÚrangeÚslicerZ _simple_newÚappendZ _from_arrays)r:rr6rDrNr
Zn_rowsZ    n_columnsrRrSZ
array_datar%ZarraysÚiÚslÚidxZarrrrrÚ from_spmatrixìs,  
   ÿz!SparseFrameAccessor.from_spmatrixcCs6ddlm}dd„|j ¡Dƒ}|||jj|jjdS)ay
        Convert a DataFrame with sparse values to dense.
 
        Returns
        -------
        DataFrame
            A DataFrame with the same values stored as dense arrays.
 
        Examples
        --------
        >>> df = pd.DataFrame({"A": pd.arrays.SparseArray([0, 1, 0])})
        >>> df.sparse.to_dense()
           A
        0  0
        1  1
        2  0
        rrOcSsi|]\}}||j ¡“qSr)r(rE)rIÚkÚvrrrÚ
<dictcomp>7sz0SparseFrameAccessor.to_dense.<locals>.<dictcomp>)r6rD)r8r
rÚitemsr6rD)rr
rrrrrE#s zSparseFrameAccessor.to_densec Csìtdƒddlm}t|jj ¡ƒ}t|tƒr4|j    }ggg}}}t
|j  ¡ƒD]b\}\}}|j }    |    j dkrvtdƒ‚|    jj}
| t |t|
ƒ¡¡| |
¡| |    jj|dd¡qRt |¡}t |¡}t |¡}||||ff|jjdS)aÍ
        Return the contents of the frame as a sparse SciPy COO matrix.
 
        Returns
        -------
        scipy.sparse.spmatrix
            If the caller is heterogeneous and contains booleans or objects,
            the result will be of dtype=object. See Notes.
 
        Notes
        -----
        The dtype will be the lowest-common-denominator type (implicit
        upcasting); that is to say if the dtypes (even of numeric types)
        are mixed, the one that accommodates all will be chosen.
 
        e.g. If the dtypes are float16 and float32, dtype will be upcast to
        float32. By numpy.find_common_type convention, mixing int64 and
        and uint64 will result in a float64 dtype.
        Zscipyr)Ú
coo_matrixz2fill value must be 0 when converting to COO matrixF)r7)rQ)rZ scipy.sparser_rrrLZto_listr$r    ÚsubtypeÚ    enumerater^r(rr0Zsp_indexrRrVÚnpÚrepeatÚlenr ZastypeZ concatenaterQ) rr_r%ÚcolsrCrÚcolÚ_ZserZsp_arrÚrowrrrr/:s$ 
 
 
 
 
 
zSparseFrameAccessor.to_cooÚfloatcCst dd„|j ¡Dƒ¡}|S)zJ
        Ratio of non-sparse points to total (dense) data points.
        cSsg|]\}}|jj‘qSr)r(r)rIrgÚcolumnrrrÚ
<listcomp>jsz/SparseFrameAccessor.density.<locals>.<listcomp>)rbZmeanrr^)rÚtmprrrreszSparseFrameAccessor.densitycCsžddlm}m}|j\}}|dkr,||ƒ}n||ƒ}|dkrF||ƒ}n||ƒ}t|ƒ|krrtdt|ƒ›d|›ƒ‚t|ƒ|kr–tdt|ƒ›d|›ƒ‚||fS)Nr)Ú default_indexÚ ensure_indexzColumn length mismatch: z vs. zIndex length mismatch: )Zpandas.core.indexes.apirmrnrQrdr0)rr6rDrmrnÚNÚKrrrrPms
 
 
  zSparseFrameAccessor._prep_index)NN) rrrrFrrGrZrEr/r!rÚ staticmethodrPrrrrrHâs6+rH)rFÚ
__future__rÚtypingrÚnumpyrbZpandas.compat._optionalrZpandas.core.dtypes.castrZpandas.core.accessorrrZpandas.core.arrays.sparse.arrayrZpandas.core.arrays.sparse.dtyper    r8r
r r r#rHrrrrÚ<module>s&       
ÿ;