PythonとNumpyの間でデータ型を変換する方法について説明します。具体的には、Pythonのint
型とNumpyのint64
型の間での変換について見ていきましょう。
PythonのintからNumpyのint64へ
Pythonのint
型をNumpyのint64
型に変換するには、Numpyのnp.int64()
関数を使用します。以下にその使用例を示します。
import numpy as np
# Pythonのint型
a = 123
print(type(a)) # <class 'int'>
# Numpyのint64型に変換
b = np.int64(a)
print(type(b)) # <class 'numpy.int64'>
このように、np.int64()
関数を使用することでPythonのint
型をNumpyのint64
型に簡単に変換することができます。
Numpyのint64からPythonのintへ
一方、Numpyのint64
型からPythonのint
型に変換するには、.item()
メソッドを使用します。以下にその使用例を示します。
import numpy as np
# Numpyのint64型
np_int = np.int64(0)
print(type(np_int)) # <class 'numpy.int64'>
# Pythonのint型に変換
py_int = np_int.item()
print(type(py_int)) # <class 'int'>
このように、.item()
メソッドを使用することでNumpyのint64
型をPythonのint
型に簡単に変換することができます。
以上、PythonとNumpyの間でint
型とint64
型を変換する方法について説明しました。これらの知識を活用して、PythonとNumpyをより効率的に使いこなしてください。.