Numpy-quick-guide

提供:Dev Guides
移動先:案内検索

NumPy-はじめに

NumPyはPythonパッケージです。 「数値Python」の略です。 これは、多次元配列オブジェクトと、配列を処理するためのルーチンのコレクションで構成されるライブラリです。

  • NumPyの祖先であるNumericは、Jim Huguninによって開発されました。 いくつかの追加機能を備えた別のパッケージNumarrayも開発されました。 2005年、Travis Oliphantは、Numarrayの機能をNumericパッケージに組み込むことにより、NumPyパッケージを作成しました。 このオープンソースプロジェクトには多くの貢献者がいます。

NumPyを使用した操作

NumPyを使用すると、開発者は次の操作を実行できます-

  • 配列の数学および論理演算。
  • 形状操作のためのフーリエ変換とルーチン。
  • 線形代数に関連する操作。 NumPyには、線形代数と乱数生成のための組み込み関数があります。

NumPy – MatLabの代替品

NumPyは、多くの場合、 SciPy (Scientific Python)や Mat-plotlib (プロットライブラリ)などのパッケージとともに使用されます。 この組み合わせは、テクニカルコンピューティングの一般的なプラットフォームであるMatLabの代替として広く使用されています。 ただし、MatLabに代わるPythonは、より現代的で完全なプログラミング言語と見なされています。

これはオープンソースであり、NumPyの追加の利点です。

NumPy-環境

標準のPythonディストリビューションには、NumPyモジュールがバンドルされていません。 軽量の代替手段は、人気のあるPythonパッケージインストーラー pip を使用してNumPyをインストールすることです。

pip install numpy

NumPyを有効にする最良の方法は、オペレーティングシステムに固有のインストール可能なバイナリパッケージを使用することです。 これらのバイナリには、完全なSciPyスタック(NumPy、SciPy、matplotlib、IPython、SymPy、およびnoseパッケージとコアPythonを含む)が含まれています。

Windows

Anaconda(https://www.continuum.ioから)は、SciPyスタック用の無料のPythonディストリビューションです。 LinuxおよびMacでも利用可能です。

Canopy(https://www.enthought.com/products/canopy/)は、Windows、Linux、およびMac向けの完全なSciPyスタックを備えた無料配布および商用配布として利用できます。

Python(x、y):Windows OS用のSciPyスタックとSpyder IDEを備えた無料のPythonディストリビューションです。 (https://python-xy.github.io/[https://www.python-xy.github.io/]からダウンロード可能)

Linux

各Linuxディストリビューションのパッケージマネージャーを使用して、1つ以上のパッケージをSciPyスタックにインストールします。

Ubuntuの場合

sudo apt-get install python-numpy
python-scipy python-matplotlibipythonipythonnotebook python-pandas
python-sympy python-nose

Fedoraの場合

sudo yum install numpyscipy python-matplotlibipython
python-pandas sympy python-nose atlas-devel

ソースからの構築

コアPython(2.6.x、2.7.x、および3.2.x以降)をdistutilsとともにインストールし、zlibモジュールを有効にする必要があります。

GNU gcc(4.2以降)Cコンパイラが利用可能でなければなりません。

NumPyをインストールするには、次のコマンドを実行します。

Python setup.py install

NumPyモジュールが適切にインストールされているかどうかをテストするには、Pythonプロンプトからインポートしてみてください。

import numpy

インストールされていない場合は、次のエラーメッセージが表示されます。

Traceback (most recent call last):
   File "<pyshell#0>", line 1, in <module>
      import numpy
ImportError: No module named 'numpy'

あるいは、NumPyパッケージは次の構文を使用してインポートされます-

import numpy as np

NumPy-Ndarrayオブジェクト

NumPyで定義されている最も重要なオブジェクトは、 ndarray と呼ばれるN次元配列型です。 同じタイプのアイテムのコレクションを記述します。 コレクション内のアイテムには、ゼロベースのインデックスを使用してアクセスできます。

ndarrayのすべてのアイテムは、メモリ内で同じサイズのブロックを取ります。 ndarrayの各要素は、データ型オブジェクト( dtype と呼ばれる)のオブジェクトです。

(スライスによって)ndarrayオブジェクトから抽出された項目は、配列スカラー型のいずれかのPythonオブジェクトによって表されます。 次の図は、ndarray、データ型オブジェクト(dtype)、配列スカラー型の関係を示しています-

Ndarray

ndarrayクラスのインスタンスは、チュートリアルで後述するさまざまな配列作成ルーチンによって構築できます。 基本的なndarrayは、次のようにNumPyの配列関数を使用して作成されます-

numpy.array

配列インターフェイスを公開するオブジェクト、または配列を返すメソッドからndarrayを作成します。

numpy.array(object, dtype = None, copy = True, order = None, subok = False, ndmin = 0)

上記のコンストラクタは、次のパラメータを取ります-

Sr.No. Parameter & Description
1

object

配列インターフェイスメソッドを公開するオブジェクトは、配列または任意の(ネストされた)シーケンスを返します。

2

dtype

必要な配列のデータ型、オプション

3

copy

オプションです。 デフォルト(true)では、オブジェクトがコピーされます

4

order

C(メジャー列)またはF(メジャー列)またはA(任意)(デフォルト)

5

subok

デフォルトでは、返される配列は強制的に基本クラス配列になります。 trueの場合、サブクラスが通過します

6

ndmin

結果の配列の最小寸法を指定します

よりよく理解するには、次の例を見てください。

例1

import numpy as np
a = np.array([1,2,3])
print a

出力は次のとおりです-

[1, 2, 3]

例2

# more than one dimensions
import numpy as np
a = np.array([[print a

出力は次のとおりです-

[[Example 3

[source,prettyprint,notranslate]

#最小寸法は、numpyをnp a = np.array([1、2、3,4,5]、ndmin = 2)としてインポートしますprint a

The output is as follows −

[source,result,notranslate]

[[例4

# dtype parameter
import numpy as np
a = np.array([1, 2, 3], dtype = complex)
print a

出力は次のとおりです-

[ 1.+0.j,  2.+0.j,  3.+0.j]
*ndarray* オブジェクトは、コンピューターメモリの連続する1次元セグメントと、各アイテムをメモリブロック内の場所にマッピングするインデックススキームで構成されます。 メモリブロックは、行優先順(Cスタイル)または列優先順(FORTRANまたはMatLabスタイル)で要素を保持します。

NumPy-データ型

NumPyは、Pythonよりもはるかに多様な数値型をサポートしています。 次の表は、NumPyで定義されているさまざまなスカラーデータ型を示しています。

Sr.No. Data Types & Description
1

bool_

バイトとして保存されるブール値(TrueまたはFalse)

2

int_

デフォルトの整数型(C longと同じ。通常はint64またはint32)

3

intc

C intと同じ(通常はint32またはint64)

4

intp

インデックスに使用される整数(C ssize_tと同じ。通常はint32またはint64)

5

int8

バイト(-128から127)

6

int16

整数(-32768から32767)

7

int32

整数(-2147483648から2147483647)

8

int64

整数(-9223372036854775808から9223372036854775807)

9

uint8

符号なし整数(0〜255)

10

uint16

符号なし整数(0〜65535)

11

uint32

符号なし整数(0〜4294967295)

12

uint64

符号なし整数(0から18446744073709551615)

13

float_

float64の省略形

14

float16

半精度浮動小数点数:符号ビット、5ビットの指数、10ビットの仮数

15

float32

単精度浮動小数点数:符号ビット、8ビット指数、23ビット仮数

16

float64

倍精度浮動小数点数:符号ビット、11ビットの指数、52ビットの仮数

17

complex_

complex128の省略形

18

complex64

2つの32ビット浮動小数点数で表される複素数(実数部と虚数部)

19

complex128

2つの64ビットフロート(実数部と虚数部)で表される複素数

NumPy数値型は、dtype(データ型)オブジェクトのインスタンスであり、それぞれに固有の特性があります。 dtypesはnp.bool_、np.float32などとして利用可能です。

データ型オブジェクト(dtype)

データ型オブジェクトは、次の側面に応じて、配列に対応するメモリの固定ブロックの解釈を説明します-

  • データのタイプ(整数、フロート、またはPythonオブジェクト)
  • データのサイズ
  • バイト順(リトルエンディアンまたはビッグエンディアン)
  • 構造化タイプの場合、フィールドの名前、各フィールドのデータタイプ、および各フィールドが使用するメモリブロックの一部。
  • データ型がサブ配列の場合、その形状とデータ型

バイト順は、データ型の前に「<」または「>」を付けることで決定されます。 「<」は、エンコードがリトルエンディアンであることを意味します(最下位アドレスは最小アドレスに格納されます)。 '>'は、エンコードがビッグエンディアンであることを意味します(最上位バイトは最小アドレスに格納されます)。

dtypeオブジェクトは、次の構文を使用して構築されます-

numpy.dtype(object, align, copy)

パラメータは次のとおりです-

  • Object -データ型オブジェクトに変換されます
  • Align -trueの場合、フィールドにパディングを追加してC構造体に似たものにします
  • コピー-dtypeオブジェクトの新しいコピーを作成します。 falseの場合、結果は組み込みデータ型オブジェクトへの参照です

例1

# using array-scalar type
import numpy as np
dt = np.dtype(np.int32)
print dt

出力は次のとおりです-

int32

例2

#int8, int16, int32, int64 can be replaced by equivalent string 'i1', 'i2','i4', etc.
import numpy as np

dt = np.dtype('i4')
print dt

出力は次のとおりです-

int32

実施例3

# using endian notation
import numpy as np
dt = np.dtype('>i4')
print dt

出力は次のとおりです-

>i4

次の例は、構造化データ型の使用を示しています。 ここでは、フィールド名と対応するスカラーデータ型が宣言されます。

実施例4

# first create structured data type
import numpy as np
dt = np.dtype([('age',np.int8)])
print dt

出力は次のとおりです-

[('age', 'i1')]

実施例5

# now apply it to ndarray object
import numpy as np

dt = np.dtype([('age',np.int8)])
a = np.array([(10,),(20,),(30,)], dtype = dt)
print a

出力は次のとおりです-

[(10,) (20,) (30,)]

実施例6

# file name can be used to access content of age column
import numpy as np

dt = np.dtype([('age',np.int8)])
a = np.array([(10,),(20,),(30,)], dtype = dt)
print a['age']

出力は次のとおりです-

[10 20 30]

実施例7

次の例では、文字列フィールド「名前」、「整数フィールド」「年齢」、および「浮動フィールド」「マーク」を使用して、「学生」と呼ばれる構造化データ型を定義します。 このdtypeはndarrayオブジェクトに適用されます。

import numpy as np
student = np.dtype([('name','S20'), ('age', 'i1'), ('marks', 'f4')])
print student

出力は次のとおりです-

[('name', 'S20'), ('age', 'i1'), ('marks', '<f4')])

例8

import numpy as np

student = np.dtype([('name','S20'), ('age', 'i1'), ('marks', 'f4')])
a = np.array([('abc', 21, 50),('xyz', 18, 75)], dtype = student)
print a

出力は次のとおりです-

[('abc', 21, 50.0), ('xyz', 18, 75.0)]

各組み込みデータ型には、一意に識別する文字コードがあります。

  • 'b' -ブール
  • 'i' -(符号付き)整数
  • 'u' -符号なし整数
  • 'f' -浮動小数点
  • 'c' -複素浮動小数点
  • 'm' -タイムデルタ
  • 'M' -日時
  • 'O' -(Python)オブジェクト
  • 'S'、 'a' -(バイト)文字列
  • 'U' -Unicode
  • 'V' -生データ(void)

NumPy-配列属性

この章では、NumPyのさまざまな配列属性について説明します。

ndarray.shape

この配列属性は、配列の次元で構成されるタプルを返します。 配列のサイズ変更にも使用できます。

例1

import numpy as np
a = np.array([[print a.shape

出力は次のとおりです-

(2, 3)

例2

# this resizes the ndarray
import numpy as np

a = np.array([[a.shape = (3,2)
print a

出力は次のとおりです-

[[Example 3

NumPy also provides a reshape function to resize an array.

[source,prettyprint,notranslate]

numpy as np a = np.array([[b = a.reshape(3,2)print bとしてインポート

The output is as follows −

[source,result,notranslate]

[[ndarray.ndim

この配列属性は、配列の次元数を返します。

例1

# an array of evenly spaced numbers
import numpy as np
a = np.arange(24)
print a

出力は次のとおりです-

[0 1  2  3  4  5  6  7  8  9  10  11  12  13  14  15  16 17 18 19 20 21 22 23]

例2

# this is one dimensional array
import numpy as np
a = np.arange(24)
a.ndim

# now reshape it
b = a.reshape(2,4,3)
print b
# b is having three dimensions

出力は次のとおりです-

[[numpy.itemsize

This array attribute returns the length of each element of array in bytes.

==== Example 1

[source,prettyprint,notranslate]

#配列のdtypeはint8(1バイト)numpyをインポートnp x = np.array([1,2,3,4,5]、dtype = np.int8)print x.itemsize

The output is as follows −

[source,result,notranslate]

1

==== Example 2

[source,prettyprint,notranslate]

#配列のdtypeはfloat32(4バイト)になりましたnpとしてインポートnumpy = np.array([1,2,3,4,5]、dtype = np.float32)print x.itemsize

The output is as follows −

[source,result,notranslate]

4

=== numpy.flags

The ndarray object has the following attributes. Its current values are returned by this function.

[width="100%",cols="50%,50%",options="header",]
|===
|Sr.No. |Attribute & Description
|1 a|
*C_CONTIGUOUS (C)*

The data is in a single, C-style contiguous segment

|2 a|
*F_CONTIGUOUS (F)*

The data is in a single, Fortran-style contiguous segment

|3 a|
*OWNDATA (O)*

The array owns the memory it uses or borrows it from another object

|4 a|
*WRITEABLE (W)*

The data area can be written to. Setting this to False locks the data, making it read-only

|5 a|
*ALIGNED (A)*

The data and all elements are aligned appropriately for the hardware

|6 a|
*UPDATEIFCOPY (U)*

This array is a copy of some other array. When this array is deallocated, the base array will be updated with the contents of this array

|===

==== Example

The following example shows the current values of flags.

[source,prettyprint,notranslate]

numpyをnp x = np.array([1,2,3,4,5])としてインポートx.flagsを出力

The output is as follows −

[source,result,notranslate]

C_CONTIGUOUS:True F_CONTIGUOUS:True OWNDATA:True WRITEABLE:True ALIGNED:True UPDATEIFCOPY:False

NumPy-配列作成ルーチン

新しい ndarray オブジェクトは、次の配列作成ルーチンのいずれか、または低レベルのndarrayコンストラクターを使用して構築できます。

numpy.empty

指定された形状とdtypeの初期化されていない配列を作成します。 それは次のコンストラクタを使用します-

numpy.empty(shape, dtype = float, order = 'C')

コンストラクターは次のパラメーターを取ります。

Sr.No. Parameter & Description
1

Shape

intまたはintのタプルの空配列の形状

2

Dtype

必要な出力データ型。 オプション

3

Order

Cスタイルの行優先配列の場合は 'C'、FORTRANスタイルの列優先配列の場合は 'F'

次のコードは、空の配列の例を示しています。

import numpy as np
x = np.empty([3,2], dtype = int)
print x

出力は次のとおりです-

[[Note* − The elements in an array show random values as they are not initialized.

=== numpy.zeros

Returns a new array of specified size, filled with zeros.

[source,result,notranslate]

numpy.zeros(shape、dtype = float、order = 'C')

The constructor takes the following parameters.

[width="100%",cols="50%,50%",options="header",]
|===
|Sr.No. |Parameter & Description
|1 a|
*Shape*

Shape of an empty array in int or sequence of int

|2 a|
*Dtype*

Desired output data type. Optional

|3 a|
*Order*

'C' for C-style row-major array, 'F' for FORTRAN style column-major array

|===

==== Example 1

[source,prettyprint,notranslate]

#5つのゼロの配列。 デフォルトのdtypeはfloat import numpy as np x = np.zeros(5)print x

The output is as follows −

[source,result,notranslate]

[ 0. 0. 0. 0. 0.]

==== Example 2

[source,prettyprint,notranslate]

numpyをnp x = np.zeros((5、)、dtype = np.int)としてインポートprint x

Now, the output would be as follows −

[source,result,notranslate]
==== Example 3

[source,prettyprint,notranslate]

#カスタムタイプimport numpy as np x = np.zeros((2,2)、dtype = [( 'x'、 'i4')、( 'y'、 'i4')])print x

It should produce the following output −

[source,result,notranslate]

[[numpy.ones

1で満たされた、指定されたサイズとタイプの新しい配列を返します。

numpy.ones(shape, dtype = None, order = 'C')

コンストラクターは次のパラメーターを取ります。

Sr.No. Parameter & Description
1

Shape

intまたはintのタプルの空配列の形状

2

Dtype

必要な出力データ型。 オプション

3

Order

Cスタイルの行優先配列の場合は 'C'、FORTRANスタイルの列優先配列の場合は 'F'

例1

# array of five ones. Default dtype is float
import numpy as np
x = np.ones(5)
print x

出力は次のとおりです-

[ 1.  1.  1.  1.  1.]

例2

import numpy as np
x = np.ones([2,2], dtype = int)
print x

今、出力は次のようになります-

[[

NumPy-既存のデータからの配列

この章では、既存のデータから配列を作成する方法について説明します。

numpy.asarray

この関数は、パラメーターが少ないという点を除いて、numpy.arrayに似ています。 このルーチンは、Pythonシーケンスをndarrayに変換するのに役立ちます。

numpy.asarray(a, dtype = None, order = None)

コンストラクターは次のパラメーターを取ります。

Sr.No. Parameter & Description
1

a

リスト、タプルのリスト、タプル、タプルのタプル、リストのタプルなどの任意の形式の入力データ

2

dtype

デフォルトでは、入力データのデータ型は結果のndarrayに適用されます

3

order

C(行メジャー)またはF(列メジャー)。 Cはデフォルトです

次の例は、 asarray 関数の使用方法を示しています。

例1

# convert list to ndarray
import numpy as np

x = [1,2,3]
a = np.asarray(x)
print a

その出力は次のようになります-

[1  2  3]

例2

# dtype is set
import numpy as np

x = [1,2,3]
a = np.asarray(x, dtype = float)
print a

今、出力は次のようになります-

[ 1.  2.  3.]

実施例3

# ndarray from tuple
import numpy as np

x = (1,2,3)
a = np.asarray(x)
print a

その出力は-

[1  2  3]

実施例4

# ndarray from list of tuples
import numpy as np

x = [(1,2,3),(4,5)]
a = np.asarray(x)
print a

ここでは、出力は次のようになります-

[(1, 2, 3) (4, 5)]

numpy.frombuffer

この関数は、バッファーを1次元配列として解釈します。 バッファーインターフェイスを公開するオブジェクトは、 ndarray を返すパラメーターとして使用されます。

numpy.frombuffer(buffer, dtype = float, count = -1, offset = 0)

コンストラクターは次のパラメーターを取ります。

Sr.No. Parameter & Description
1

buffer

バッファインターフェイスを公開するオブジェクト

2

dtype

返されるndarrayのデータ型。 デフォルトはフロート

3

count

読み込むアイテムの数。デフォルトは-1はすべてのデータを意味します

4

offset

読み込む開始位置。 デフォルトは0

次の例は、 frombuffer 関数の使用方法を示しています。

import numpy as np
s = 'Hello World'
a = np.frombuffer(s, dtype = 'S1')
print a

ここにその出力があります-

['H'  'e'  'l'  'l'  'o'  ' '  'W'  'o'  'r'  'l'  'd']

numpy.fromiter

この関数は、反復可能なオブジェクトから ndarray オブジェクトを構築します。 この関数により、新しい1次元配列が返されます。

numpy.fromiter(iterable, dtype, count = -1)

ここで、コンストラクターは次のパラメーターを取ります。

Sr.No. Parameter & Description
1

iterable

反復可能なオブジェクト

2

dtype

結果の配列のデータ型

3

count

イテレータから読み込むアイテムの数。 デフォルトは-1で、これはすべてのデータが読み取られることを意味します

次の例は、組み込みの* range()関数を使用してリストオブジェクトを返す方法を示しています。 このリストの反復子は、 *ndarray オブジェクトを形成するために使用されます。

例1

# create list object using range function
import numpy as np
list = range(5)
print list

その出力は次のとおりです-

[0,  1,  2,  3,  4]

例2

# obtain iterator object from list
import numpy as np
list = range(5)
it = iter(list)

# use iterator to create ndarray
x = np.fromiter(it, dtype = float)
print x

今、出力は次のようになります-

[0.   1.   2.   3.   4.]

NumPy-数値範囲からの配列

この章では、数値範囲から配列を作成する方法を説明します。

numpy.arange

この関数は、指定された範囲内の等間隔の値を含む ndarray オブジェクトを返します。 関数の形式は次のとおりです-

numpy.arange(start, stop, step, dtype)

コンストラクターは次のパラメーターを取ります。

Sr.No. Parameter & Description
1

start

インターバルの開始。 省略した場合、デフォルトは0

2

stop

間隔の終わり(この数値は含まれません)

3

step

値間の間隔。デフォルトは1

4

dtype

結果のndarrayのデータ型。 指定しない場合、入力のデータ型が使用されます

次の例は、この関数の使用方法を示しています。

例1

import numpy as np
x = np.arange(5)
print x

その出力は次のようになります-

[0  1  2  3  4]

例2

import numpy as np
# dtype set
x = np.arange(5, dtype = float)
print x

ここでは、出力は次のようになります-

[0.  1.  2.  3.  4.]

実施例3

# start and stop parameters set
import numpy as np
x = np.arange(10,20,2)
print x

その出力は次のとおりです-

[10  12  14  16  18]

numpy.linspace

この関数は* arange()*関数に似ています。 この関数では、ステップサイズの代わりに、間隔間の等間隔の値の数が指定されます。 この関数の使用法は次のとおりです-

numpy.linspace(start, stop, num, endpoint, retstep, dtype)

コンストラクターは次のパラメーターを取ります。

Sr.No. Parameter & Description
1

start

シーケンスの開始値

2

stop

エンドポイントがtrueに設定されている場合、シーケンスに含まれるシーケンスの終了値

3

num

生成される等間隔のサンプルの数。 デフォルトは50

4

endpoint

デフォルトではtrueであるため、停止値はシーケンスに含まれます。 falseの場合、含まれません

5

retstep

trueの場合、サンプルを返し、連続する番号の間をステップします

6

dtype

出力 ndarray のデータ型

次の例は、 linspace 関数の使用を示しています。

例1

import numpy as np
x = np.linspace(10,20,5)
print x

その出力は-

[10.   12.5   15.   17.5  20.]

例2

# endpoint set to false
import numpy as np
x = np.linspace(10,20, 5, endpoint = False)
print x

出力は次のようになります-

[10.   12.   14.   16.   18.]

実施例3

# find retstep value
import numpy as np

x = np.linspace(1,2,5, retstep = True)
print x
# retstep here is 0.25

今、出力は次のようになります-

(array([ 1.  ,  1.25,  1.5 ,  1.75,  2.  ]), 0.25)

numpy.logspace

この関数は、対数スケールで等間隔に配置された数値を含む ndarray オブジェクトを返します。 スケールの開始および終了エンドポイントは、ベースのインデックスであり、通常は10です。

numpy.logspace(start, stop, num, endpoint, base, dtype)

以下のパラメーターは、 logspace 関数の出力を決定します。

Sr.No. Parameter & Description
1

start

シーケンスの開始点はbase ^ start ^です

2

stop

シーケンスの最終値はbase ^ stop ^です

3

num

範囲内の値の数。 デフォルトは50

4

endpoint

trueの場合、stopは範囲内の最後の値です

5

base

ログ領域のベース、デフォルトは10

6

dtype

出力配列のデータ型。 指定しない場合、他の入力引数に依存します

次の例は、 logspace 関数を理解するのに役立ちます。

例1

import numpy as np
# default base is 10
a = np.logspace(1.0, 2.0, num = 10)
print a

その出力は次のようになります-

[ 10.           12.91549665     16.68100537      21.5443469  27.82559402
  35.93813664   46.41588834     59.94842503      77.42636827    100.    ]

例2

# set base of log space to 2
import numpy as np
a = np.logspace(1,10,num = 10, base = 2)
print a

今、出力は次のようになります-

[ 2.     4.     8.    16.    32.    64.   128.   256.    512.   1024.]

NumPy-インデックス作成とスライス

ndarrayオブジェクトの内容は、Pythonの組み込みコンテナーオブジェクトと同様に、インデックス付けまたはスライスによってアクセスおよび変更できます。

前述したように、ndarrayオブジェクトのアイテムはゼロベースのインデックスに従います。 3種類のインデックス方法が利用可能です-フィールドアクセス、基本スライシング*および*高度なインデックス

基本的なスライシングは、Pythonのn次元へのスライシングの基本概念の拡張です。 Pythonスライスオブジェクトは、組み込みの slice 関数に start、stop 、および step パラメーターを与えることで構築されます。 このスライスオブジェクトは、配列の一部を抽出するために配列に渡されます。

例1

import numpy as np
a = np.arange(10)
s = slice(2,7,2)
print a[s]

その出力は次のとおりです-

[2  4  6]

上記の例では、 ndrange オブジェクトは* arange()*関数によって準備されます。 次に、開始、停止、およびステップ値2、7、および2でスライスオブジェクトがそれぞれ定義されます。 このスライスオブジェクトがndarrayに渡されると、インデックス2から7までのステップ2の部分がスライスされます。

同じ結果は、コロン:(start:stop:step)で区切られたスライスパラメーターを ndarray オブジェクトに直接与えることでも取得できます。

例2

import numpy as np
a = np.arange(10)
b = a[2:7:2]
print b

ここでは、同じ出力が得られます-

[2  4  6]

パラメーターが1つだけの場合、インデックスに対応する単一のアイテムが返されます。 :がその前に挿入されると、そのインデックス以降のすべてのアイテムが抽出されます。 2つのパラメーター(間に:がある)が使用される場合、デフォルトのステップ1を持つ2つのインデックス間のアイテム(ストップインデックスを含まない)がスライスされます。

実施例3

# slice single item
import numpy as np

a = np.arange(10)
b = a[5]
print b

その出力は次のとおりです-

5

実施例4

# slice items starting from index
import numpy as np
a = np.arange(10)
print a[2:]

今、出力は次のようになります-

[2  3  4  5  6  7  8  9]

実施例5

# slice items between indexes
import numpy as np
a = np.arange(10)
print a[2:5]

ここでは、出力は次のようになります-

[2  3  4]

上記の説明は、多次元の ndarray にも適用されます。

実施例6

import numpy as np
a = np.array([[print a

# slice items starting from index
print 'Now we will slice the array from the index a[1:]'
print a[1:]

出力は次のとおりです-

[[Now we will slice the array from the index a[1:]
[[Slicing can also include ellipsis (…) to make a selection tuple of the same length as the dimension of an array. If ellipsis is used at the row position, it will return an ndarray comprising of items in rows.

=== Example 7

[source,prettyprint,notranslate]

#import numpy as np a = np.array([[print 'Our array is:' print a print '\ n’で始まる配列

#これは、2列目の項目の配列を返しますprint '2列目の項目は次のとおりです:' print a […​、1] print '\ n'

#次に、2行目のすべてのアイテムをスライスしますprint '2行目のアイテムは:' print a [1、…​] print '\ n'

#ここで、列1以降のすべてのアイテムをスライスしますprint 'アイテム1列目以降は:' print a […​、1:]

The output of this program is as follows −

[source,result,notranslate]

配列は次のとおりです。[[2列目の項目は次のとおりです。

2行目の項目は次のとおりです。

アイテム列1以降は次のとおりです。[[

NumPy-高度なインデックス作成

非タプルシーケンスであるndarray、整数またはブールデータ型のndarrayオブジェクト、または少なくとも1つの項目がシーケンスオブジェクトであるタプルから選択を行うことができます。 高度なインデックスは、常にデータのコピーを返します。 これに対して、スライスはビューのみを表示します。

高度なインデックスには、*整数*と*ブール*の2種類があります。

整数のインデックス付け

このメカニズムは、N次元インデックスに基づいて配列内の任意のアイテムを選択するのに役立ちます。 各整数配列は、そのディメンションへのインデックスの数を表します。 インデックスがターゲットndarrayの次元と同じ数の整数配列で構成される場合、それは簡単になります。

次の例では、ndarrayオブジェクトの各行から指定された列の1つの要素が選択されます。 したがって、行インデックスにはすべての行番号が含まれ、列インデックスは選択される要素を指定します。

例1

import numpy as np

x = np.array([[y = x[[0,1,2], [0,1,0]]
print y

その出力は次のようになります-

[1  4  5]

選択範囲には、最初の配列の(0,0)、(1,1)、および(2,0)の要素が含まれます。

次の例では、4X3配列の角に配置された要素が選択されています。 選択の行インデックスは[0、0]および[3,3]ですが、列インデックスは[0,2]および[0,2]です。

例2

import numpy as np
x = np.array([[print 'Our array is:'
print x
print '\n'

rows = np.array([[cols = np.array([[0,2],[0,2]])
y = x[rows,cols]

print 'The corner elements of this array are:'
print y

このプログラムの出力は次のとおりです-

Our array is:
[[The corner elements of this array are:
[[The resultant selection is an ndarray object containing corner elements.

Advanced and basic indexing can be combined by using one slice (:) or ellipsis (…) with an index array. The following example uses slice for row and advanced index for column. The result is the same when slice is used for both. But advanced index results in copy and may have different memory layout.

==== Example 3

[source,prettyprint,notranslate]

numpyをnp x = np.array([[print 'Our array is:' print x print '\ n’としてインポート

#z = x [1:4,1:3]のスライス

print 'スライス後、配列は次のようになります:' print z print '\ n'

#列y = x [1:4、[1,2]]に高度なインデックスを使用

print '列に高度なインデックスを使用したスライス:' print y

The output of this program would be as follows −

[source,result,notranslate]

配列は次のとおりです。[[スライス後、配列は次のようになります。[[列の高度なインデックスを使用したスライス:[[Boolean Array Indexing

このタイプの高度なインデックスは、結果のオブジェクトが比較演算子などのブール演算の結果である場合に使用されます。

例1

この例では、ブールインデックスの結果として5を超えるアイテムが返されます。

import numpy as np
x = np.array([[print 'Our array is:'
print x
print '\n'

# Now we will print the items greater than 5
print 'The items greater than 5 are:'
print x[x > 5]

このプログラムの出力は次のようになります-

Our array is:
[[The items greater than 5 are:
[ 6  7  8  9 10 11]

例2

この例では、NaN(Not a Number)要素は〜(補数演算子)を使用して省略されています。

import numpy as np
a = np.array([np.nan, 1,2,np.nan,3,4,5])
print a[~np.isnan(a)]

その出力は-

[ 1.   2.   3.   4.   5.]

実施例3

次の例は、配列から非複雑な要素を除外する方法を示しています。

import numpy as np
a = np.array([1, 2+6j, 5, 3.5+5j])
print a[np.iscomplex(a)]

ここでは、出力は次のとおりです-

[2.0+6.j  3.5+5.j]

NumPy-放送

「ブロードキャスト」という用語は、算術演算中にさまざまな形状の配列を処理するNumPyの機能を指します。 配列の算術演算は通常、対応する要素で実行されます。 2つの配列がまったく同じ形状である場合、これらの操作はスムーズに実行されます。

例1

import numpy as np

a = np.array([1,2,3,4])
b = np.array([10,20,30,40])
c = a * b
print c

その出力は次のとおりです-

[10   40   90   160]

2つの配列の次元が異なる場合、要素間の操作はできません。 ただし、NumPyでは、ブロードキャスト機能があるため、非類似形状の配列に対する操作は引き続き可能です。 小さい配列は、互換性のある形状を持つように、大きい配列のサイズに*ブロードキャスト*されます。

次のルールが満たされている場合、ブロードキャストが可能です-

  • 他方よりも ndim が小さい配列は、その形状に「1」が付加されます。
  • 出力形状の各次元のサイズは、その次元の入力サイズの最大値です。
  • 特定の次元のサイズが出力サイズと一致する場合、または値が正確に1である場合、計算で入力を使用できます。
  • 入力の次元サイズが1の場合、その次元の最初のデータエントリが、その次元に沿ったすべての計算に使用されます。

上記のルールが有効な結果を生成し、次のいずれかが真である場合、配列のセットは broadcastable と呼ばれます-

  • 配列の形状はまったく同じです。
  • 配列の次元数は同じで、各次元の長さは共通の長さまたは1です。 *次元が少なすぎる配列は、形状に長さ1の次元を追加できるため、上記のプロパティが真になります。

次のプログラムは、ブロードキャストの例を示しています。

例2

import numpy as np
a = np.array([[b = np.array([1.0,2.0,3.0])

print 'First array:'
print a
print '\n'

print 'Second array:'
print b
print '\n'

print 'First Array + Second Array'
print a + b

このプログラムの出力は次のようになります-

First array:
[[Second array:
[ 1. 2. 3.]

First Array + Second Array
[[The following figure demonstrates how array* b *is broadcast to become compatible with* a*.

image:/numpy/array.jpg[array]

NumPy-配列の繰り返し

NumPyパッケージには、イテレータオブジェクト numpy.nditer が含まれています。 これは効率的な多次元反復子オブジェクトであり、これを使用して配列を反復処理できます。 配列の各要素には、Pythonの標準のIteratorインターフェースを使用してアクセスします。

arange()関数を使用して3X4配列を作成し、 nditer を使用して繰り返します。

例1

import numpy as np
a = np.arange(0,60,5)
a = a.reshape(3,4)

print 'Original array is:'
print a
print '\n'

print 'Modified array is:'
for x in np.nditer(a):
   print x,

このプログラムの出力は次のとおりです-

Original array is:
[[Modified array is:
0 5 10 15 20 25 30 35 40 45 50 55

例2

反復の順序は、特定の順序を考慮せずに、アレイのメモリレイアウトに一致するように選択されます。 これは、上記の配列の転置を反復することで確認できます。

import numpy as np
a = np.arange(0,60,5)
a = a.reshape(3,4)

print 'Original array is:'
print a
print '\n'

print 'Transpose of the original array is:'
b = a.T
print b
print '\n'

print 'Modified array is:'
for x in np.nditer(b):
   print x,

上記のプログラムの出力は次のとおりです-

Original array is:
[[Transpose of the original array is:
[[Modified array is:
0 5 10 15 20 25 30 35 40 45 50 55

反復順序

同じ要素がFスタイルの順序を使用して格納されている場合、反復子は配列を反復するより効率的な方法を選択します。

例1

import numpy as np
a = np.arange(0,60,5)
a = a.reshape(3,4)
print 'Original array is:'
print a
print '\n'

print 'Transpose of the original array is:'
b = a.T
print b
print '\n'

print 'Sorted in C-style order:'
c = b.copy(order = 'C')
print c
for x in np.nditer(c):
   print x,

print '\n'

print 'Sorted in F-style order:'
c = b.copy(order = 'F')
print c
for x in np.nditer(c):
   print x,

その出力は次のようになります-

Original array is:
[[Transpose of the original array is:
[[Sorted in C-style order:
[[Sorted in F-style order:
[[Example 2

It is possible to force *nditer *object to use a specific order by explicitly mentioning it.

[source,prettyprint,notranslate]

numpyをnp a = np.arange(0,60,5)a = a.reshape(3,4)としてインポート

print '元の配列は:' print '\ n'

np.nditer(a、order = 'C')のxに対して 'Cスタイルの順序で並べ替え:'を出力:xを印刷、 '\ n’を印刷

np.nditer(a、order = 'F')のxに対して 'Fスタイルの順序で並べ替え:'を印刷:xを印刷、

Its output would be −

[source,result,notranslate]

元の配列は次のとおりです。[[Cスタイルの順序で並べ替え:0 5 10 15 20 25 30 35 40 45 50 55

Fスタイルの順序で並べ替え:0 20 40 5 25 45 10 30 50 15 35 55

=== Modifying Array Values

The* nditer *object has another optional parameter called* op_flags*. Its default value is read-only, but can be set to read-write or write-only mode. This will enable modifying array elements using this iterator.

==== Example

[source,prettyprint,notranslate]

import numpy as np a = np.arange(0,60,5)a = a.reshape(3,4)print 'Original array is:' print a print '\ n'

np.nditer(a、op_flags = ['readwrite'])のxの場合:x […​] = 2 * x print 'Modified array is:' print a

Its output is as follows −

[source,result,notranslate]

元の配列:[[変更された配列:[[外部ループ

nditerクラスのコンストラクターには、次の値を取ることができる ’flags’ パラメーターがあります-

Sr.No. Parameter & Description
1

c_index

C_orderインデックスを追跡できます

2

f_index

Fortran_orderインデックスが追跡されます

3

multi-index

反復ごとに1つのインデックスのタイプを追跡できます

4

external_loop

指定された値を、ゼロ次元配列ではなく複数の値を持つ1次元配列にします

次の例では、各列に対応する1次元配列が反復子によって走査されます。

import numpy as np
a = np.arange(0,60,5)
a = a.reshape(3,4)

print 'Original array is:'
print a
print '\n'

print 'Modified array is:'
for x in np.nditer(a, flags = ['external_loop'], order = 'F'):
   print x,

出力は次のとおりです-

Original array is:
[[Modified array is:
[ 0 20 40] [ 5 25 45] [10 30 50] [15 35 55]

放送の反復

2つの配列が broadcastable である場合、結合された nditer オブジェクトはそれらを同時に反復処理できます。 配列 a の次元が3X4であり、次元1X4の別の配列 b があると仮定すると、次の型の反復子が使用されます(配列 ba のサイズにブロードキャストされます)。

import numpy as np
a = np.arange(0,60,5)
a = a.reshape(3,4)

print 'First array is:'
print a
print '\n'

print 'Second array is:'
b = np.array([1, 2, 3, 4], dtype = int)
print b
print '\n'

print 'Modified array is:'
for x,y in np.nditer([a,b]):
   print "%d:%d" % (x,y),

その出力は次のようになります-

First array is:
[[Second array is:
[1 2 3 4]

Modified array is:
0:1 5:2 10:3 15:4 20:1 25:2 30:3 35:4 40:1 45:2 50:3 55:4

NumPy-配列操作

NumPyパッケージには、ndarrayオブジェクトの要素を操作するためのいくつかのルーチンが用意されています。 彼らは次のタイプに分類することができます-

形を変える

Sr.No. Shape & Description
1

reshape

データを変更せずに、配列に新しい形状を与えます

2

flat

配列の1次元イテレーター

3

flatten

一次元に折りたたまれた配列のコピーを返します

4

ravel

連続した平坦化された配列を返します

転置演算

Sr.No. Operation & Description
1

transpose

配列の次元を並べ替えます

2

ndarray.T

self.transpose()と同じ

3

rollaxis

指定された軸を後方にロールします

4

swapaxes

配列の2つの軸を交換します

寸法の変​​更

Sr.No. Dimension & Description
1

broadcast

放送を模倣するオブジェクトを生成します

2

broadcast_to

配列を新しい形状にブロードキャストします

3

expand_dims

配列の形状を拡張します

4

squeeze

配列の形状から1次元のエントリを削除します

配列の結合

Sr.No. Array & Description
1

concatenate

既存の軸に沿って配列のシーケンスを結合します

2

stack

新しい軸に沿って配列のシーケンスを結合します

3

hstack

配列を水平方向に順番にスタックします(列方向)。

4

vstack

配列を垂直に(行ごとに)順番にスタックします

配列の分割

Sr.No. Array & Description
1

split

配列を複数のサブ配列に分割します

2

hsplit

配列を複数のサブ配列に水平方向(列方向)に分割します

3

vsplit

配列を複数のサブ配列に垂直方向(行方向)に分割します

要素の追加/削除

Sr.No. Element & Description
1

resize

指定された形状の新しい配列を返します

2

append

配列の最後に値を追加します

3

insert

指定されたインデックスの前に指定された軸に沿って値を挿入します

4

delete

軸に沿ったサブ配列が削除された新しい配列を返します

5

unique

配列の一意の要素を検索します

NumPy-二項演算子

以下は、NumPyパッケージで使用可能なビット演算の関数です。

Sr.No. Operation & Description
1

bitwise_and

配列要素のビット単位のAND演算を計算します

2

bitwise_or

配列要素のビット単位のOR演算を計算します

3

invert

ビット単位のNOTを計算します

4

left_shift

バイナリ表現のビットを左にシフトします

5

right_shift

バイナリ表現のビットを右にシフトします

NumPy-文字列関数

次の関数は、dtype numpy.string_またはnumpy.unicode_の配列に対してベクトル化された文字列操作を実行するために使用されます。 これらは、Pythonの組み込みライブラリの標準の文字列関数に基づいています。

Sr.No. Function & Description
1

add()

strまたはUnicodeの2つの配列の要素ごとの文字列連結を返します

2

multiply()

要素ごとに複数の連結を持つ文字列を返します

3

center()

指定された長さの文字列の中心に要素がある、指定された文字列のコピーを返します

4

capitalize()

最初の文字のみを大文字にして文字列のコピーを返します

5

title()

文字列またはUnicodeの要素ごとのタイトルケースバージョンを返します

6

lower()

要素を小文字に変換した配列を返します

7

upper()

要素を大文字に変換した配列を返します

8

split()

separatordelimiterを使用して、文字列内の単語のリストを返します

9

splitlines()

要素内の行のリストを返します。行の境界で分割します

10

strip()

先頭と末尾の文字を削除したコピーを返します

11

join()

シーケンス内の文字列を連結した文字列を返します

12

replace()

部分文字列のすべての出現を新しい文字列で置き換えた文字列のコピーを返します

13

decode()

str.decodeを要素ごとに呼び出します

14

encode()

str.encodeを要素ごとに呼び出します

これらの関数は、文字配列クラス(numpy.char)で定義されています。 古いNumarrayパッケージにはchararrayクラスが含まれていました。 numpy.charクラスの上記の関数は、ベクトル化された文字列操作の実行に役立ちます。

NumPy-数学関数

当然のことながら、NumPyには多数のさまざまな数学演算が含まれています。 NumPyは、標準の三角関数、算術演算、複素数の処理などの関数を提供します。

三角関数

NumPyには、ラジアン単位で指定された角度の三角比を返す標準の三角関数があります。

import numpy as np
a = np.array([0,30,45,60,90])

print 'Sine of different angles:'
# Convert to radians by multiplying with pi/180
print np.sin(a*np.pi/180)
print '\n'

print 'Cosine values for angles in array:'
print np.cos(a*np.pi/180)
print '\n'

print 'Tangent values for given angles:'
print np.tan(a*np.pi/180)

ここにその出力があります-

Sine of different angles:
[ 0.          0.5         0.70710678  0.8660254   1.        ]

Cosine values for angles in array:
[  1.00000000e+00   8.66025404e-01   7.07106781e-01   5.00000000e-01
   6.12323400e-17]

Tangent values for given angles:
[  0.00000000e+00   5.77350269e-01   1.00000000e+00   1.73205081e+00
   1.63312394e+16]
  • arcsin、arcos、、および *arctan 関数は、指定された角度のsin、cos、およびtanの三角関数の逆関数を返します。 これらの関数の結果は、ラジアンを度に変換する* numpy.degrees()関数*で検証できます。

import numpy as np
a = np.array([0,30,45,60,90])

print 'Array containing sine values:'
sin = np.sin(a*np.pi/180)
print sin
print '\n'

print 'Compute sine inverse of angles. Returned values are in radians.'
inv = np.arcsin(sin)
print inv
print '\n'

print 'Check result by converting to degrees:'
print np.degrees(inv)
print '\n'

print 'arccos and arctan functions behave similarly:'
cos = np.cos(a*np.pi/180)
print cos
print '\n'

print 'Inverse of cos:'
inv = np.arccos(cos)
print inv
print '\n'

print 'In degrees:'
print np.degrees(inv)
print '\n'

print 'Tan function:'
tan = np.tan(a*np.pi/180)
print tan
print '\n'

print 'Inverse of tan:'
inv = np.arctan(tan)
print inv
print '\n'

print 'In degrees:'
print np.degrees(inv)

その出力は次のとおりです-

Array containing sine values:
[ 0.          0.5         0.70710678  0.8660254   1.        ]

Compute sine inverse of angles. Returned values are in radians.
[ 0.          0.52359878  0.78539816  1.04719755  1.57079633]

Check result by converting to degrees:
[  0.  30.  45.  60.  90.]

arccos and arctan functions behave similarly:
[  1.00000000e+00   8.66025404e-01   7.07106781e-01   5.00000000e-01
   6.12323400e-17]

Inverse of cos:
[ 0.          0.52359878  0.78539816  1.04719755  1.57079633]

In degrees:
[  0.  30.  45.  60.  90.]

Tan function:
[  0.00000000e+00   5.77350269e-01   1.00000000e+00   1.73205081e+00
   1.63312394e+16]

Inverse of tan:
[ 0.          0.52359878  0.78539816  1.04719755  1.57079633]

In degrees:
[  0.  30.  45.  60.  90.]

丸めの関数

numpy.around()

これは、目的の精度に丸められた値を返す関数です。 この関数は、次のパラメーターを取ります。

numpy.around(a,decimals)

どこで、

Sr.No. Parameter & Description
1

a

入力データ

2

decimals

丸める小数の数。 デフォルトは0です。 負の場合、整数は小数点の左側の位置に丸められます

  • 例 *
import numpy as np
a = np.array([1.0,5.55, 123, 0.567, 25.532])

print 'Original array:'
print a
print '\n'

print 'After rounding:'
print np.around(a)
print np.around(a, decimals = 1)
print np.around(a, decimals = -1)

それは次の出力を生成します-

Original array:
[   1.       5.55   123.       0.567   25.532]

After rounding:
[   1.    6.   123.    1.   26. ]
[   1.    5.6  123.    0.6  25.5]
[   0.    10.  120.    0.   30. ]

numpy.floor()

この関数は、入力パラメーター以下の最大整数を返します。* scalar x のフロアは、 *i ⇐ x のように、最大​​の*整数i *です。 Pythonでは、フローリングは常に0から丸められます。

  • 例 *
import numpy as np
a = np.array([-1.7, 1.5, -0.2, 0.6, 10])

print 'The given array:'
print a
print '\n'

print 'The modified array:'
print np.floor(a)

それは次の出力を生成します-

The given array:
[ -1.7   1.5  -0.2   0.6  10. ]

The modified array:
[ -2.   1.  -1.   0.  10.]

numpy.ceil()

ceil()関数は、入力値の上限を返します。* scalar x のceilは、 i> = x。のような最小の *integer i です。

import numpy as np
a = np.array([-1.7, 1.5, -0.2, 0.6, 10])

print 'The given array:'
print a
print '\n'

print 'The modified array:'
print np.ceil(a)

それは次の出力を生成します-

The given array:
[ -1.7   1.5  -0.2   0.6  10. ]

The modified array:
[ -1.   2.  -0.   1.  10.]

NumPy-算術演算

add()、subtract()、multiply()、divide()などの算術演算を実行するための入力配列は、同じ形状であるか、配列のブロードキャストルールに準拠する必要があります。

import numpy as np
a = np.arange(9, dtype = np.float_).reshape(3,3)

print 'First array:'
print a
print '\n'

print 'Second array:'
b = np.array([10,10,10])
print b
print '\n'

print 'Add the two arrays:'
print np.add(a,b)
print '\n'

print 'Subtract the two arrays:'
print np.subtract(a,b)
print '\n'

print 'Multiply the two arrays:'
print np.multiply(a,b)
print '\n'

print 'Divide the two arrays:'
print np.divide(a,b)

それは次の出力を生成します-

First array:
[[Second array:
[10 10 10]

Add the two arrays:
[[Subtract the two arrays:
[[Multiply the two arrays:
[[Divide the two arrays:
[[Let us now discuss some of the other important arithmetic functions available in NumPy.

=== numpy.reciprocal()

This function returns the reciprocal of argument, element-wise. For elements with absolute values larger than 1, the result is always 0 because of the way in which Python handles integer division. For integer 0, an overflow warning is issued.

==== Example

[source,prettyprint,notranslate]

numpyをnp a = np.array([0.25、1.33、1、0、100])としてインポート

print 'Our array is:' print a '\ n'

print '逆関数を適用した後:' print np.reciprocal(a)print '\ n'

b = np.array([100]、dtype = int)print '2番目の配列は:' print b print '\ n'

print '相反関数を適用した後:' print np.reciprocal(b)

It will produce the following output −

[source,result,notranslate]

配列は次のとおりです。 [ 0.25 1.33 1. 0. 100. ]

相互関数を適用した後:main.py:9:RuntimeWarning:相互印刷でゼロ除算が発生しましたnp.reciprocal(a) [ 4. 0.7518797 1. inf 0.01 ]

2番目の配列は次のとおりです。

相互関数を適用した後:

=== numpy.power()

This function treats elements in the first input array as base and returns it raised to the power of the corresponding element in the second input array.

[source,prettyprint,notranslate]

numpyをnp a = np.array([10,100,1000])としてインポート

print 'Our array is:' print a '\ n'

print 'パワー関数の適用:' print np.power(a、2)print '\ n'

print '2番目の配列:' b = np.array([1,2,3])print b print '\ n'

print '電力関数の再適用:' print np.power(a、b)

It will produce the following output −

[source,result,notranslate]

配列は次のとおりです。 [ 10 100 1000]

べき関数の適用: [ 100 10000 1000000]

2番目の配列:

再び電源機能を適用する: [ 10 10000 1000000000]

=== numpy.mod()

This function returns the remainder of division of the corresponding elements in the input array. The function *numpy.remainder()* also produces the same result.

[source,prettyprint,notranslate]

numpyをnp a = np.array([10,20,30])b = np.array([3,5,7])としてインポート

印刷 '最初の配列:'印刷 '\ n'

print '2番目の配列:' print b print '\ n'

print 'mod()関数の適用:' print np.mod(a、b)print '\ n'

print 'Applying remaining()function:' print np.remainder(a、b)

It will produce the following output −

[source,result,notranslate]

最初の配列:

2番目の配列:

mod()関数の適用:

remaining()関数の適用:

The following functions are used to perform operations on array with complex numbers.

* *numpy.real()* − returns the real part of the complex data type argument.
* *numpy.imag()* − returns the imaginary part of the complex data type argument.
* *numpy.conj()* − returns the complex conjugate, which is obtained by changing the sign of the imaginary part.
* *numpy.angle()* − returns the angle of the complex argument. The function has degree parameter. If true, the angle in the degree is returned, otherwise the angle is in radians.

[source,prettyprint,notranslate]

numpyをnp a = np.array([-5.6j、0.2j、11。 、1 + 1j])

print 'Our array is:' print a '\ n'

print 'real()関数の適用:' print np.real(a)print '\ n'

print 'imag()関数の適用:' print np.imag(a)print '\ n'

print 'conj()関数の適用:' print np.conj(a)print '\ n'

print 'applying angle()function:' print np.angle(a)print '\ n'

print '再度angle()関数を適用(度で結果)' print np.angle(a、deg = True)

It will produce the following output −

[source,result,notranslate]

配列は次のとおりです。 [ 0.-5.6j 0.+0.2j 11.+0.j 1.+1.j ]

real()関数の適用: [ 0. 0. 11. 1.]

imag()関数の適用: [-5.6 0.2 0. 1. ]

conj()関数の適用: [ 0.+5.6j 0.-0.2j 11.-0.j 1.-1.j ]

angle()関数の適用: [-1.57079633 1.57079633 0. 0.78539816]

angle()関数を再度適用します(度で結果) [-90. 90. 0. 45.]

NumPy-統計関数

NumPyには、最小値、最大値、パーセンタイルの標準偏差と分散などを見つけるための便利な統計関数が多数あります。 配列内の指定された要素から。 機能は次のように説明されています-

numpy.amin()およびnumpy.amax()

これらの関数は、指定された軸に沿って、指定された配列の要素から最小値と最大値を返します。

import numpy as np
a = np.array([[print 'Our array is:'
print a
print '\n'

print 'Applying amin() function:'
print np.amin(a,1)
print '\n'

print 'Applying amin() function again:'
print np.amin(a,0)
print '\n'

print 'Applying amax() function:'
print np.amax(a)
print '\n'

print 'Applying amax() function again:'
print np.amax(a, axis = 0)

それは次の出力を生成します-

Our array is:
[[Applying amin() function:
[3 3 2]

Applying amin() function again:
[2 4 3]

Applying amax() function:
9

Applying amax() function again:
[8 7 9]

numpy.ptp()

  • numpy.ptp()*関数は、軸に沿った値の範囲(最大-最小)を返します。
import numpy as np
a = np.array([[print 'Our array is:'
print a
print '\n'

print 'Applying ptp() function:'
print np.ptp(a)
print '\n'

print 'Applying ptp() function along axis 1:'
print np.ptp(a, axis = 1)
print '\n'

print 'Applying ptp() function along axis 0:'
print np.ptp(a, axis = 0)

それは次の出力を生成します-

Our array is:
[[Applying ptp() function:
7

Applying ptp() function along axis 1:
[4 5 7]

Applying ptp() function along axis 0:
[6 3 6]

numpy.percentile()

百分位数(または百分位数)は、統計値で使用される測定値であり、その値を下回ると、観測グループ内の観測の特定のパーセンテージが低下します。 関数* numpy.percentile()*は次の引数を取ります。

numpy.percentile(a, q, axis)

どこで、

Sr.No. Argument & Description
1

a

入力配列

2

q

計算するパーセンタイルは0〜100の間である必要があります

3

axis

パーセンタイルが計算される軸

import numpy as np
a = np.array([[print 'Our array is:'
print a
print '\n'

print 'Applying percentile() function:'
print np.percentile(a,50)
print '\n'

print 'Applying percentile() function along axis 1:'
print np.percentile(a,50, axis = 1)
print '\n'

print 'Applying percentile() function along axis 0:'
print np.percentile(a,50, axis = 0)

それは次の出力を生成します-

Our array is:
[[Applying percentile() function:
50.0

Applying percentile() function along axis 1:
[ 40. 20. 60.]

Applying percentile() function along axis 0:
[ 50. 40. 60.]

numpy.median()

  • 中央値*は、データサンプルの上位半分と下位半分を分離する値として定義されます。 * numpy.median()*関数は、次のプログラムに示すように使用されます。

import numpy as np
a = np.array([[print 'Our array is:'
print a
print '\n'

print 'Applying median() function:'
print np.median(a)
print '\n'

print 'Applying median() function along axis 0:'
print np.median(a, axis = 0)
print '\n'

print 'Applying median() function along axis 1:'
print np.median(a, axis = 1)

それは次の出力を生成します-

Our array is:
[[Applying median() function:
65.0

Applying median() function along axis 0:
[ 50. 90. 60.]

Applying median() function along axis 1:
[ 65. 80. 60.]

numpy.mean()

算術平均は、軸に沿った要素の合計を要素数で割ったものです。 * numpy.mean()*関数は、配列内の要素の算術平均を返します。 軸に言及している場合、それに沿って計算されます。

import numpy as np
a = np.array([[print 'Our array is:'
print a
print '\n'

print 'Applying mean() function:'
print np.mean(a)
print '\n'

print 'Applying mean() function along axis 0:'
print np.mean(a, axis = 0)
print '\n'

print 'Applying mean() function along axis 1:'
print np.mean(a, axis = 1)

それは次の出力を生成します-

Our array is:
[[Applying mean() function:
3.66666666667

Applying mean() function along axis 0:
[ 2.66666667 3.66666667 4.66666667]

Applying mean() function along axis 1:
[ 2. 4. 5.]

numpy.average()

加重平均は、各コンポーネントにその重要性を反映する係数を乗算した結果の平均です。 * numpy.average()*関数は、別の配列で指定されたそれぞれの重みに従って、配列内の要素の加重平均を計算します。 この関数は軸パラメーターを持つことができます。 軸が指定されていない場合、配列はフラット化されます。

配列[1,2,3,4]および対応する重み[4,3,2,1]を考慮して、対応する要素の積を加算し、合計を重みの合計で除算することにより、加重平均が計算されます。

加重平均=(1 4 + 2 3 + 3 2 + 4 1)/(4 + 3 + 2 + 1)

import numpy as np
a = np.array([1,2,3,4])

print 'Our array is:'
print a
print '\n'

print 'Applying average() function:'
print np.average(a)
print '\n'

# this is same as mean when weight is not specified
wts = np.array([4,3,2,1])

print 'Applying average() function again:'
print np.average(a,weights = wts)
print '\n'

# Returns the sum of weights, if the returned parameter is set to True.
print 'Sum of weights'
print np.average([1,2,3, 4],weights = [4,3,2,1], returned = True)

それは次の出力を生成します-

Our array is:
[1 2 3 4]

Applying average() function:
2.5

Applying average() function again:
2.0

Sum of weights
(2.0, 10.0)

多次元配列では、計算の軸を指定できます。

import numpy as np
a = np.arange(6).reshape(3,2)

print 'Our array is:'
print a
print '\n'

print 'Modified array:'
wt = np.array([3,5])
print np.average(a, axis = 1, weights = wt)
print '\n'

print 'Modified array:'
print np.average(a, axis = 1, weights = wt, returned = True)

それは次の出力を生成します-

Our array is:
[[Modified array:
[ 0.625 2.625 4.625]

Modified array:
(array([ 0.625, 2.625, 4.625]), array([ 8., 8., 8.]))

標準偏差

標準偏差は、平均からの偏差の平方の平均の平方根です。 標準偏差の式は次のとおりです-

std = sqrt(mean(abs(x - x.mean())**2))

配列が[1、2、3、4]の場合、平均は2.5です。 したがって、偏差の平方は[2.25、0.25、0.25、2.25]であり、その平均を4で除算した平方根、つまりsqrt(5/4)は1.1180339887498949です。

import numpy as np
print np.std([1,2,3,4])

それは次の出力を生成します-

1.1180339887498949

分散

分散は偏差の二乗の平均、つまり* mean(abs(x-x.mean())** 2)*です。 つまり、標準偏差は分散の平方根です。

import numpy as np
print np.var([1,2,3,4])

それは次の出力を生成します-

1.25

NumPy-ソート、検索、カウント機能

NumPyでは、さまざまな並べ替え関連の機能を使用できます。 これらの並べ替え関数は、さまざまな並べ替えアルゴリズムを実装します。それぞれのアルゴリズムは、実行速度、最悪の場合のパフォーマンス、必要なワークスペース、およびアルゴリズムの安定性によって特徴付けられます。 次の表は、3つの並べ替えアルゴリズムの比較を示しています。

kind speed worst case work space stable
‘quicksort’ 1 O(n^2) 0 no
‘mergesort’ 2 O(n*log(n)) ~n/2 yes
‘heapsort’ 3 O(n*log(n)) 0 no

numpy.sort()

sort()関数は、入力配列のソートされたコピーを返します。 次のパラメータがあります-

numpy.sort(a, axis, kind, order)

どこで、

Sr.No. Parameter & Description
1

a

ソートされる配列

2

axis

配列が並べ替えられる軸。 存在しない場合、配列は平坦化され、最後の軸でソートされます

3

kind

デフォルトはクイックソートです

4

order

配列にフィールドが含まれる場合、ソートされるフィールドの順序

import numpy as np
a = np.array([[print 'Our array is:'
print a
print '\n'

print 'Applying sort() function:'
print np.sort(a)
print '\n'

print 'Sort along axis 0:'
print np.sort(a, axis = 0)
print '\n'

# Order parameter in sort function
dt = np.dtype([('name', 'S10'),('age', int)])
a = np.array([("raju",21),("anil",25),("ravi", 17), ("amar",27)], dtype = dt)

print 'Our array is:'
print a
print '\n'

print 'Order by name:'
print np.sort(a, order = 'name')

それは次の出力を生成します-

Our array is:
[[Applying sort() function:
[[Sort along axis 0:
[[Our array is:
[('raju', 21) ('anil', 25) ('ravi', 17) ('amar', 27)]

Order by name:
[('amar', 27) ('anil', 25) ('raju', 21) ('ravi', 17)]

numpy.argsort()

  • numpy.argsort()*関数は、指定された軸に沿って入力配列で間接ソートを実行し、指定された種類のソートを使用してデータのインデックスの配列を返します。 このインデックス配列は、ソートされた配列を作成するために使用されます。

import numpy as np
x = np.array([3, 1, 2])

print 'Our array is:'
print x
print '\n'

print 'Applying argsort() to x:'
y = np.argsort(x)
print y
print '\n'

print 'Reconstruct original array in sorted order:'
print x[y]
print '\n'

print 'Reconstruct the original array using loop:'
for i in y:
   print x[i],

それは次の出力を生成します-

Our array is:
[3 1 2]

Applying argsort() to x:
[1 2 0]

Reconstruct original array in sorted order:
[1 2 3]

Reconstruct the original array using loop:
1 2 3

numpy.lexsort()

関数は、キーのシーケンスを使用して間接ソートを実行します。 キーはスプレッドシートの列として見ることができます。 この関数は、インデックスの配列を返します。これを使用して、ソートされたデータを取得できます。 最後のキーがたまたま主キーであることに注意してください。

import numpy as np

nm = ('raju','anil','ravi','amar')
dv = ('f.y.', 's.y.', 's.y.', 'f.y.')
ind = np.lexsort((dv,nm))

print 'Applying lexsort() function:'
print ind
print '\n'

print 'Use this index to get sorted data:'
print [nm[i] + ", " + dv[i] for i in ind]

それは次の出力を生成します-

Applying lexsort() function:
[3 1 0 2]

Use this index to get sorted data:
['amar, f.y.', 'anil, s.y.', 'raju, f.y.', 'ravi, s.y.']

NumPyモジュールには、配列内を検索するための多くの関数があります。 最大値、最小値、および特定の条件を満たす要素を見つけるための関数が利用できます。

numpy.argmax()およびnumpy.argmin()

これらの2つの関数は、指定された軸に沿ってそれぞれ最大要素と最小要素のインデックスを返します。

import numpy as np
a = np.array([[print 'Our array is:'
print a
print '\n'

print 'Applying argmax() function:'
print np.argmax(a)
print '\n'

print 'Index of maximum number in flattened array'
print a.flatten()
print '\n'

print 'Array containing indices of maximum along axis 0:'
maxindex = np.argmax(a, axis = 0)
print maxindex
print '\n'

print 'Array containing indices of maximum along axis 1:'
maxindex = np.argmax(a, axis = 1)
print maxindex
print '\n'

print 'Applying argmin() function:'
minindex = np.argmin(a)
print minindex
print '\n'

print 'Flattened array:'
print a.flatten()[minindex]
print '\n'

print 'Flattened array along axis 0:'
minindex = np.argmin(a, axis = 0)
print minindex
print '\n'

print 'Flattened array along axis 1:'
minindex = np.argmin(a, axis = 1)
print minindex

それは次の出力を生成します-

Our array is:
[[Applying argmax() function:
7

Index of maximum number in flattened array
[30 40 70 80 20 10 50 90 60]

Array containing indices of maximum along axis 0:
[1 2 0]

Array containing indices of maximum along axis 1:
[2 0 1]

Applying argmin() function:
5

Flattened array:
10

Flattened array along axis 0:
[0 1 1]

Flattened array along axis 1:
[0 2 0]

numpy.nonzero()

  • numpy.nonzero()*関数は、入力配列内の非ゼロ要素のインデックスを返します。

import numpy as np
a = np.array([[print 'Our array is:'
print a
print '\n'

print 'Applying nonzero() function:'
print np.nonzero (a)

それは次の出力を生成します-

Our array is:
[[Applying nonzero() function:
(array([0, 0, 1, 1, 2, 2]), array([0, 1, 1, 2, 0, 2]))

numpy.where()

where()関数は、指定された条件が満たされる入力配列の要素のインデックスを返します。

import numpy as np
x = np.arange(9.).reshape(3, 3)

print 'Our array is:'
print x

print 'Indices of elements > 3'
y = np.where(x > 3)
print y

print 'Use these indices to get elements satisfying the condition'
print x[y]

それは次の出力を生成します-

Our array is:
[[Indices of elements > 3
(array([1, 1, 2, 2, 2]), array([1, 2, 0, 1, 2]))

Use these indices to get elements satisfying the condition
[ 4. 5. 6. 7. 8.]

numpy.extract()

  • extract()*関数は、任意の条件を満たす要素を返します。
import numpy as np
x = np.arange(9.).reshape(3, 3)

print 'Our array is:'
print x

# define a condition
condition = np.mod(x,2) == 0

print 'Element-wise value of condition'
print condition

print 'Extract elements using condition'
print np.extract(condition, x)

それは次の出力を生成します-

Our array is:
[[Element-wise value of condition
[[True False True]
 [False True False]
 [ True False True]]

Extract elements using condition
[ 0. 2. 4. 6. 8.]

NumPy-バイト交換

コンピュータのメモリに保存されるデータは、CPUが使用するアーキテクチャに依存することがわかりました。 リトルエンディアン(最下位アドレスが最小アドレスに格納される)またはビッグエンディアン(最小アドレスの最上位バイト)になります。

numpy.ndarray.byteswap()

  • numpy.ndarray.byteswap()*関数は、ビッグエンディアンとリトルエンディアンの2つの表現を切り替えます。
import numpy as np
a = np.array([1, 256, 8755], dtype = np.int16)

print 'Our array is:'
print a

print 'Representation of data in memory in hexadecimal form:'
print map(hex,a)
# byteswap() function swaps in place by passing True parameter

print 'Applying byteswap() function:'
print a.byteswap(True)

print 'In hexadecimal form:'
print map(hex,a)
# We can see the bytes being swapped

それは次の出力を生成します-

Our array is:
[1 256 8755]

Representation of data in memory in hexadecimal form:
['0x1', '0x100', '0x2233']

Applying byteswap() function:
[256 1 13090]

In hexadecimal form:
['0x100', '0x1', '0x3322']

NumPy-コピーとビュー

関数の実行中に、入力配列のコピーを返す関数と、ビューを返す関数があります。 コンテンツが物理的に別の場所に保存されている場合、それは*コピー*と呼ばれます。 一方、同じメモリコンテンツの別のビューが提供される場合、 View と呼びます。

コピーなし

単純な割り当てでは、配列オブジェクトのコピーは作成されません。 代わりに、元の配列と同じid()を使用してアクセスします。 * id()*は、Cのポインターに似たPythonオブジェクトのユニバーサル識別子を返します。

さらに、いずれかの変更が他方に反映されます。 たとえば、一方の形状が変化すると、他方の形状も変化します。

import numpy as np
a = np.arange(6)

print 'Our array is:'
print a

print 'Applying id() function:'
print id(a)

print 'a is assigned to b:'
b = a
print b

print 'b has same id():'
print id(b)

print 'Change shape of b:'
b.shape = 3,2
print b

print 'Shape of a also gets changed:'
print a

それは次の出力を生成します-

Our array is:
[0 1 2 3 4 5]

Applying id() function:
139747815479536

a is assigned to b:
[0 1 2 3 4 5]
b has same id():
139747815479536

Change shape of b:
[[Shape of a also gets changed:
[[View or Shallow Copy

NumPy has *ndarray.view() *method which is a new array object that looks at the same data of the original array. Unlike the earlier case, change in dimensions of the new array doesn’t change dimensions of the original.

==== Example

[source,prettyprint,notranslate]

import numpy as np#そもそも、aは3X2配列a = np.arange(6).reshape(3,2)

print 'Array a:' print a

print 'a:のビューを作成' b = a.view()print b

両方の配列のprint 'id()は異なります:' print 'id()of a:' print id(a)print 'id()of b:' print id(b)

#bの形状を変更します。 b.shape = 2,3の形状は変更しません

'bの形状:'印刷b

'Shape of a:'を印刷します

It will produce the following output −

[source,result,notranslate]

配列a:[[aのビューを作成:[[id()両方の配列は異なります:id()of a:140424307227264 id()of b:140424151696288

bの形状:[[aの形状:[[配列のスライスはビューを作成します。

import numpy as np
a = np.array([[print 'Our array is:'
print a

print 'Create a slice:'
s = a[:, :2]
print s

それは次の出力を生成します-

Our array is:
[[Create a slice:
[[Deep Copy

The* ndarray.copy()* function creates a deep copy. It is a complete copy of the array and its data, and doesn’t share with the original array.

==== Example

[source,prettyprint,notranslate]

numpy as np a = np.array([[print 'Array a is:' print a

print 'aのディープコピーを作成:' b = a.copy()print 'Array b is:' print b

  1. bは印刷のメモリを共有しません 'b is a can' write a b 'print b is a

print 'b:の内容を変更します' b [0,0] = 100

print 'Modified array b:' print b

印刷 'aは変わりません:'印刷

It will produce the following output −

[source,result,notranslate]

配列aは次のとおりです。[[aのディープコピーを作成:配列bは次のとおりです。

bの内容を変更します:変更された配列b:[[aは変更されないままです:[[

NumPy-マトリックスライブラリ

NumPyパッケージには、マトリックスライブラリ numpy.matlib が含まれています。 このモジュールには、ndarrayオブジェクトの代わりに行列を返す関数があります。

matlib.empty()

  • matlib.empty()*関数は、エントリを初期化せずに新しい行列を返します。 この関数は、次のパラメーターを取ります。
numpy.matlib.empty(shape, dtype, order)

どこで、

Sr.No. Parameter & Description
1

shape

  • int* または新しいマトリックスの形状を定義する *int* のタプル
2

Dtype

オプションです。 出力のデータ型

3

order

CまたはF

import numpy.matlib
import numpy as np

print np.matlib.empty((2,2))
# filled with random data

それは次の出力を生成します-

[[e-314,   4.24399158e-314]
 [ 4.24399158e-314,   2.12199579e-314]]

numpy.matlib.zeros()

この関数は、ゼロで満たされた行列を返します。

import numpy.matlib
import numpy as np
print np.matlib.zeros((2,2))

それは次の出力を生成します-

[[numpy.matlib.ones()

This function returns the matrix filled with 1s.

[source,prettyprint,notranslate]

import numpy.matlib import numpy as np print np.matlib.ones((2,2))

It will produce the following output −

[source,result,notranslate]

[[numpy.matlib.eye()

この関数は、対角要素に沿って1を持ち、他の場所にゼロを持つ行列を返します。 この関数は、次のパラメーターを取ります。

numpy.matlib.eye(n, M,k, dtype)

どこで、

Sr.No. Parameter & Description
1

n

結果の行列の行数

2

M

列数、デフォルトはn

3

k

対角線のインデックス

4

dtype

出力のデータ型

import numpy.matlib
import numpy as np
print np.matlib.eye(n = 3, M = 4, k = 0, dtype = float)

それは次の出力を生成します-

[[numpy.matlib.identity()

The *numpy.matlib.identity()* function returns the Identity matrix of the given size. An identity matrix is a square matrix with all diagonal elements as 1.

[source,prettyprint,notranslate]

import numpy.matlib import numpy as np print np.matlib.identity(5、dtype = float)

It will produce the following output −

[source,result,notranslate]

[[numpy.matlib.rand()

  • numpy.matlib.rand()*関数は、ランダムな値で満たされた指定サイズの行列を返します。

import numpy.matlib
import numpy as np
print np.matlib.rand(3,3)

それは次の出力を生成します-

[[Note* that a matrix is always two-dimensional, whereas ndarray is an n-dimensional array. Both the objects are inter-convertible.

==== Example

[source,prettyprint,notranslate]

import numpy.matlib import numpy as np

i = np.matrix( '1,2; 3,4')print i

It will produce the following output −

[source,result,notranslate]

[[例

import numpy.matlib
import numpy as np

j = np.asarray(i)
print j

それは次の出力を生成します-

[[Example

[source,prettyprint,notranslate]

import numpy.matlib import numpy as np

k = np.asmatrix(j)kを出力

It will produce the following output −

[source,result,notranslate]

[[

NumPy-線形代数

NumPyパッケージには、線形代数に必要なすべての機能を提供する numpy.linalg モジュールが含まれています。 このモジュールの重要な機能の一部を次の表に示します。

Sr.No. Function & Description
1

dot

2つの配列のドット積

2

vdot

2つのベクトルのドット積

3

inner

2つの配列の内積

4

matmul

2つの配列の行列積

5

determinant

配列の行列式を計算します

6

solve

線形行列方程式を解きます

7

inv

行列の乗法的逆行列を見つける

NumPy-Matplotlib

Matplotlibは、Python用のプロットライブラリです。 NumPyと一緒に使用して、MatLabの効果的なオープンソースの代替となる環境を提供します。 PyQtやwxPythonなどのグラフィックツールキットでも使用できます。

Matplotlibモジュールは、John Dによって最初に作成されました。 ハンター。 2012年以来、Michael Droettboomが主な開発者です。 現在、Matplotlib ver。 1.5.1は安定版です。 このパッケージは、バイナリ配布およびhttp://www.matplotlib.org [www.matplotlib.org]のソースコード形式で入手できます。

従来、パッケージは次のステートメントを追加することによりPythonスクリプトにインポートされます-

from matplotlib import pyplot as plt

ここで、* pyplot()はmatplotlibライブラリの最も重要な関数であり、2Dデータをプロットするために使用されます。 次のスクリプトは方程式をプロットします *y = 2x + 5

import numpy as np
from matplotlib import pyplot as plt

x = np.arange(1,11)
y = 2 * x + 5
plt.title("Matplotlib demo")
plt.xlabel("x axis caption")
plt.ylabel("y axis caption")
plt.plot(x,y)
plt.show()

ndarrayオブジェクトxは、* x軸*の値として np.arange()function から作成されます。 * y軸*の対応する値は、別の ndarrayオブジェクトy に保存されます。 これらの値は、matplotlibパッケージのpyplotサブモジュールの* plot()*関数を使用してプロットされます。

グラフィック表示は、* show()*関数によって表示されます。

上記のコードは、次の出力を生成する必要があります-

Matplotlibデモ

線形グラフの代わりに、* plot()*関数にフォーマット文字列を追加することにより、値を個別に表示できます。 次のフォーマット文字を使用できます。

Sr.No. Character & Description
1

'-'

実線スタイル

2

'--'

破線のスタイル

3

'-.'

一点鎖線スタイル

4

':'

点線スタイル

5

'.'

ポイントマーカー

6

','

ピクセルマーカー

7

'o'

サークルマーカー

8

'v'

Triangle_downマーカー

9

'^'

Triangle_upマーカー

10

'<'

Triangle_leftマーカー

11

'>'

Triangle_rightマーカー

12

'1'

Tri_downマーカー

13

'2'

トライアップマーカー

14

'3'

Tri_leftマーカー

15

'4'

Tri_rightマーカー

16

's'

スクエアマーカー

17

'p'

五角形マーカー

18

'''*

スターマーカー

19

'h'

Hexagon1マーカー

20

'H'

Hexagon2マーカー

21

'+'

プラスマーカー

22

'x'

Xマーカー

23

'D'

ダイヤモンドマーカー

24

'd'

Thin_diamondマーカー

25 *'

'*

Vlineマーカー

26

次の色の略語も定義されています。

Character Color
'b' Blue
'g' Green
'r' Red
'c' Cyan
'm' Magenta
'y' Yellow
'k' Black
'w' White

上記の例の線の代わりに、点を表す円を表示するには、plot()関数のフォーマット文字列として*“ ob” *を使用します。

import numpy as np
from matplotlib import pyplot as plt

x = np.arange(1,11)
y = 2 * x + 5
plt.title("Matplotlib demo")
plt.xlabel("x axis caption")
plt.ylabel("y axis caption")
plt.plot(x,y,"ob")
plt.show()

上記のコードは、次の出力を生成する必要があります-

色の略語

正弦波プロット

次のスクリプトは、matplotlibを使用して*正弦波プロット*を生成します。

import numpy as np
import matplotlib.pyplot as plt

# Compute the x and y coordinates for points on a sine curve
x = np.arange(0, 3 * np.pi, 0.1)
y = np.sin(x)
plt.title("sine wave form")

# Plot the points using matplotlib
plt.plot(x, y)
plt.show()

サイン波

subplot()

subplot()関数を使用すると、同じ図にさまざまなものをプロットできます。 次のスクリプトでは、*サイン*および*コサイン値*がプロットされています。

import numpy as np
import matplotlib.pyplot as plt

# Compute the x and y coordinates for points on sine and cosine curves
x = np.arange(0, 3 * np.pi, 0.1)
y_sin = np.sin(x)
y_cos = np.cos(x)

# Set up a subplot grid that has height 2 and width 1,
# and set the first such subplot as active.
plt.subplot(2, 1, 1)

# Make the first plot
plt.plot(x, y_sin)
plt.title('Sine')

# Set the second subplot as active, and make the second plot.
plt.subplot(2, 1, 2)
plt.plot(x, y_cos)
plt.title('Cosine')

# Show the figure.
plt.show()

上記のコードは、次の出力を生成する必要があります-

サブプロット

バー()

  • pyplotサブモジュール*は、棒グラフを生成する* bar()関数を提供します。 次の例では、2組の *x および y 配列の棒グラフを作成します。

from matplotlib import pyplot as plt
x = [5,8,10]
y = [12,16,6]

x2 = [6,9,11]
y2 = [6,15,7]
plt.bar(x, y, align = 'center')
plt.bar(x2, y2, color = 'g', align = 'center')
plt.title('Bar graph')
plt.ylabel('Y axis')
plt.xlabel('X axis')

plt.show()

このコードは、次の出力を生成する必要があります-

棒グラフ

NumPy-Matplotlibを使用したヒストグラム

NumPyには、データの度数分布のグラフィカルな表現である* numpy.histogram()関数があります。 *bin と呼ばれるクラス間隔に対応する水平サイズが等しい長方形と、周波数に対応する*可変高*。

numpy.histogram()

numpy.histogram()関数は、入力配列とビンを2つのパラメーターとして受け取ります。 ビン配列内の連続する要素は、各ビンの境界として機能します。

import numpy as np

a = np.array([22,87,5,43,56,73,55,54,11,20,51,5,79,31,27])
np.histogram(a,bins = [0,20,40,60,80,100])
hist,bins = np.histogram(a,bins = [0,20,40,60,80,100])
print hist
print bins

それは次の出力を生成します-

[3 4 5 2 1]
[0 20 40 60 80 100]

plt()

Matplotlibは、ヒストグラムのこの数値表現をグラフに変換できます。 pyplotサブモジュールの* plt()関数*は、データとビン配列を含む配列をパラメーターとして受け取り、ヒストグラムに変換します。

from matplotlib import pyplot as plt
import numpy as np

a = np.array([22,87,5,43,56,73,55,54,11,20,51,5,79,31,27])
plt.hist(a, bins = [0,20,40,60,80,100])
plt.title("histogram")
plt.show()

それは次の出力を生成する必要があります-

ヒストグラムプロット

NumPyを使用したI/O

ndarrayオブジェクトは、ディスクファイルに保存したり、ディスクファイルからロードしたりできます。 利用可能なIO機能は次のとおりです-

  • * load()および save()関数は/numPyバイナリファイルを処理します( *npy 拡張子付き)
  • * loadtxt()および savetxt()*関数は通常のテキストファイルを処理します

NumPyは、ndarrayオブジェクト用のシンプルなファイル形式を導入しています。 この .npy ファイルは、ファイルが異なるアーキテクチャの別のマシン上にある場合でもアレイが正しく取得されるように、ディスクファイルにndarrayを再構築するために必要なデータ、形状、dtypeおよびその他の情報を保存します。

numpy.save()

  • numpy.save()ファイルは、入力配列を *npy 拡張子を持つディスクファイルに保存します。
import numpy as np
a = np.array([1,2,3,4,5])
np.save('outfile',a)
*outfile.npy* から配列を再構築するには、* load()*関数を使用します。
import numpy as np
b = np.load('outfile.npy')
print b

それは次の出力を生成します-

array([1, 2, 3, 4, 5])

save()およびload()関数は、追加のブール値パラメーター allow_pickles を受け入れます。 Pythonのpickleは、ディスクファイルに保存したり、ディスクファイルから読み取ったりする前に、オブジェクトをシリアル化および非シリアル化するために使用されます。

savetxt()

単純なテキストファイル形式での配列データの保存と取得は、* savetxt()および loadtxt()*関数を使用して行われます。

import numpy as np

a = np.array([1,2,3,4,5])
np.savetxt('out.txt',a)
b = np.loadtxt('out.txt')
print b

それは次の出力を生成します-

[ 1.  2.  3.  4.  5.]

savetxt()およびloadtxt()関数は、ヘッダー、フッター、区切り文字などの追加のオプションパラメーターを受け入れます。