簡體   English   中英

python numpy:更改numpy矩陣的列類型

[英]python numpy: Change the column type of a numpy matrix

我有一個 numpy 矩陣 X,我嘗試使用以下代碼更改第 1 列的數據類型:

X[:, 1].astype('str')
print(type(X[0, 1]))

但我得到了以下結果:

<type 'numpy.float64'>

有人知道為什么類型沒有更改為 str 嗎? 更改 X 的列類型的正確方法是什么?謝謝!

提供一個簡單的例子會更好地解釋它。

>>> a = np.array([[1,2,3],[4,5,6]])
array([[1, 2, 3],
       [4, 5, 6]])
>>> a[:,1]
array([2, 5])
>>> a[:,1].astype('str') # This generates copy and then cast.
array(['2', '5'], dtype='<U21')
>>> a                    # So the original array did not change.
array([[1, 2, 3],
       [4, 5, 6]])

更清晰和直接的答案。 類型沒有更改為 str 因為 NumPy 數組應該只有一種數據類型。 更改 X 的列類型的正確方法是使用結構化數組或此問題的解決方案之一。

我有同樣的問題,我不想使用結構化數組。 如果適合您的任務,一個可能的選擇是使用 Pandas。 如果您只想更改一列,則可能意味着您的數據是表格形式。 然后您可以輕松更改列的數據類型。 另一個折衷是制作列的副本並將其與原始數組分開使用。

>>> x = np.ones((3, 3), dtype=np.float)
array([[1., 1., 1.],
       [1., 1., 1.],
       [1., 1., 1.]])
>>> x[:, 1] = x[:, 1].astype(np.int)
>>> type(x[:, 1][0])
numpy.float64
>>> x_pd = pd.DataFrame(x)
>>> x_pd[1] = x_pd[1].astype(np.int16)
>>> type(x_pd[1][0])
numpy.int16

回答第二個問題,因為我也遇到了同樣的問題。

正如 dinarkino 所提到的,只分配類型是行不通的。

>>> X = np.array([[1.1,2.2],[3.3,4.4]])
>>> print(X[:,1].dtype)
<class 'numpy.float64'>

>>> X[:,1] = X[:,1].astype('str')
>>> print(X[:,1].dtype)
<class 'numpy.float64'>

所以我的方法是首先將整個矩陣的 dtypes 分配給 'object',然后將 str 數據類型分配回來。

>>> X = X.astype('object')
>>> print(type(X[0,1]))
<class 'float'>

>>> X[:,1] = X[:,1].astype('str')
>>> print(type(X[0,1]))
<class 'str'>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM