0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

pythonで小数型を整数型に変換したい

Last updated at Posted at 2019-09-23

やりたいこと

以下を実行すると

[in]
import numpy as np
print(np.logspace(0, 3, 4))
print(type(np.logspace(0, 3, 4)[0]))

以下のように、float64型になってしまうが、整数型に変換したい。

[out]
[   1.   10.  100. 1000.]
<class 'numpy.float64'>

動作環境

jupyter Lab
Python3.6
numpy

方法

追記。1つ目。

[in]
x = np.logspace(0, 3, 4, dtype=int)
print(x)
print(type(x[0]))

[out]
[   1   10  100 1000]
<class 'numpy.int64'>

コメントありがとうございます。

2つ目。numpy.arrayオブジェクトを利用して、第2引数にdtype=intと指定する方法。1つ目のやり方でやりましょう。

[in]
x = np.array(np.logspace(0, 3, 4), dtype=int)
print(x)
print(type(x[0]))

[out]
[   1   10  100 1000]
<class 'numpy.int64'>

3つ目。astypeをメソッドチェインで利用する。1つ目のやり方やりましょう。

[in]
y = np.logspace(0, 3, 4).astype(np.int64)
print(y)
print(type(y[0]))
[out]
[   1   10  100 1000]
<class 'numpy.int64'>

そもそもの発端

以下のエラーが出たので、解決するために以上の方法を行った。

ValueError: n_estimators must be an integer, got <class 'numpy.float64'>.
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?