[英]TypeError when converting to sparse matrix
這是 dataframe 的數據類型。我想將其轉換為稀疏的 dataframe,但由於某種原因它返回錯誤。 我的代碼有什么問題?
>X[nums].dtypes
bin_1 float64
bin_2 float64
bin_3 float64
bin_4 float64
ord_0 float64
ord_1 float64
ord_2 float64
ord_3 float64
ord_4 float64
day_sin float64
day_cos float64
month_sin float64
month_cos float64
ord_5 float64
dtype: object
這是我嘗試將其轉換為稀疏矩陣時的錯誤。 我也用 pandas sparse 嘗試過它,它返回了相同的結果。 為什么說 TypeError: no supported conversion for types: (dtype('O'),)
>scipy.sparse.csr_matrix(X[nums].values)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/opt/conda/lib/python3.6/site-packages/scipy/sparse/base.py in asformat(self, format, copy)
326 try:
--> 327 return convert_method(copy=copy)
328 except TypeError:
/opt/conda/lib/python3.6/site-packages/scipy/sparse/coo.py in tocsr(self, copy)
399 indices = np.empty_like(col, dtype=idx_dtype)
--> 400 data = np.empty_like(self.data, dtype=upcast(self.dtype))
401
/opt/conda/lib/python3.6/site-packages/scipy/sparse/sputils.py in upcast(*args)
51
---> 52 raise TypeError('no supported conversion for types: %r' % (args,))
53
TypeError: no supported conversion for types: (dtype('O'),)
During handling of the above exception, another exception occurred:
TypeError Traceback (most recent call last)
<ipython-input-102-20bd81b47238> in <module>
----> 1 scipy.sparse.csr_matrix(X[notToDummy].values)
/opt/conda/lib/python3.6/site-packages/scipy/sparse/compressed.py in __init__(self, arg1, shape, dtype, copy)
81 "".format(self.format))
82 from .coo import coo_matrix
---> 83 self._set_self(self.__class__(coo_matrix(arg1, dtype=dtype)))
84
85 # Read matrix dimensions given, if any
/opt/conda/lib/python3.6/site-packages/scipy/sparse/compressed.py in __init__(self, arg1, shape, dtype, copy)
30 arg1 = arg1.copy()
31 else:
---> 32 arg1 = arg1.asformat(self.format)
33 self._set_self(arg1)
34
/opt/conda/lib/python3.6/site-packages/scipy/sparse/base.py in asformat(self, format, copy)
327 return convert_method(copy=copy)
328 except TypeError:
--> 329 return convert_method()
330
331 ###################################################################
/opt/conda/lib/python3.6/site-packages/scipy/sparse/coo.py in tocsr(self, copy)
398 indptr = np.empty(M + 1, dtype=idx_dtype)
399 indices = np.empty_like(col, dtype=idx_dtype)
--> 400 data = np.empty_like(self.data, dtype=upcast(self.dtype))
401
402 coo_tocsr(M, N, self.nnz, row, col, self.data,
/opt/conda/lib/python3.6/site-packages/scipy/sparse/sputils.py in upcast(*args)
50 return t
51
---> 52 raise TypeError('no supported conversion for types: %r' % (args,))
53
54
TypeError: no supported conversion for types: (dtype('O'),)
正如@bglbrt 在此評論中指定的那樣,使用:
scipy.sparse.csr_matrix(X[nums].values.astype(float))
這個答案是在 CC BY-SA 4.0 下由 OP Elizabeth McBeth 轉換為稀疏矩陣時作為對問題 TypeError的編輯發布的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.