numpy_色々¶
In [2]:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import animation as ani
import seaborn as sns
In [3]:
vstacked = np.vstack(([1, 2], [3, 4]))
vstacked
Out[3]:
array([[1, 2],
[3, 4]])
In [4]:
np.hstack(([1, 2], [3, 4]))
Out[4]:
array([1, 2, 3, 4])
In [5]:
np.hstack((vstacked, vstacked))
Out[5]:
array([[1, 2, 1, 2],
[3, 4, 3, 4]])
In [6]:
np.stack([[1, 2], [3, 4]])
Out[6]:
array([[1, 2],
[3, 4]])
In [7]:
np.stack([[1, 2], [3, 4]], axis=1)
Out[7]:
array([[1, 3],
[2, 4]])
In [8]:
mat = np.matrix([[1, 2, 3], [4, 5, 6]])
mat
Out[8]:
matrix([[1, 2, 3],
[4, 5, 6]])
In [9]:
ary = np.array(mat)
ary
Out[9]:
array([[1, 2, 3],
[4, 5, 6]])
In [10]:
type(mat), type(ary)
Out[10]:
(numpy.matrixlib.defmatrix.matrix, numpy.ndarray)
In [11]:
ary + mat
Out[11]:
matrix([[ 2, 4, 6],
[ 8, 10, 12]])
In [12]:
mat + ary
Out[12]:
matrix([[ 2, 4, 6],
[ 8, 10, 12]])
In [13]:
mat + mat
Out[13]:
matrix([[ 2, 4, 6],
[ 8, 10, 12]])
In [14]:
mat * mat.T
Out[14]:
matrix([[14, 32],
[32, 77]])
In [15]:
mat.T * mat
Out[15]:
matrix([[17, 22, 27],
[22, 29, 36],
[27, 36, 45]])
In [16]:
mat.T @ mat
Out[16]:
matrix([[17, 22, 27],
[22, 29, 36],
[27, 36, 45]])
In [17]:
ary @ ary.T
Out[17]:
array([[14, 32],
[32, 77]])
In [18]:
np.zeros(10)
Out[18]:
array([ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])
In [19]:
from scipy.spatial import distance
In [20]:
distance.euclidean([0, 0], [1, 1])
Out[20]:
1.4142135623730951
In [21]:
# http://stackoverflow.com/questions/1401712/how-can-the-euclidean-distance-be-calculated-with-numpy
np.linalg.norm(np.array([0, 0]) - np.array([1, 1]))
Out[21]:
1.4142135623730951
In [24]:
np.array([[0, 0], [1, 1]])
Out[24]:
array([[0, 0],
[1, 1]])
In [27]:
np.sum(np.array([[0, 0], [1, 1]]), axis=1)
Out[27]:
array([0, 2])
In [23]:
np.sqrt(np.sum(np.array([[0, 0], [1, 1]]), axis=1))
Out[23]:
array([ 0. , 1.41421356])
In [28]:
# http://docs.scipy.org/doc/numpy/reference/generated/numpy.argmin.html
np.argmin([2,3,1]), np.argmax([2,3,1])
Out[28]:
(2, 1)
In [29]:
reshaped = np.array([4,5,6,1,2,3]).reshape(2, 3)
reshaped
Out[29]:
array([[4, 5, 6],
[1, 2, 3]])
In [30]:
np.argmin(reshaped), np.argmax(reshaped)
# flattenしたときのIndex
Out[30]:
(3, 2)
In [31]:
import pandas as pd
print(pd.isnull(np.array(['a', 1, 'b', np.nan, np.nan])))
print(pd.isnull(np.array(['a', 1, 'b', np.nan, None])))
np.array(['a', 1, 'b', np.nan, None])
[False False False False False]
[False False False True True]
Out[31]:
array(['a', 1, 'b', nan, None], dtype=object)
In [32]:
(np.linalg.norm(np.array([3.33, 2.67]) - np.array([5, 1])) ) ** 2
Out[32]:
5.5777999999999999
In [33]:
# ランダムにクラスタとなるデータをK個選ぶ
# 各データは、K個のデータうち、一番近いクラスタに属させる
# クラスタ内の重心を変更する
In [34]:
round(1.16, 1)
Out[34]:
1.2
In [35]:
np.where(np.array([1,2,3,4]) == np.array([4,2,3,1]))
Out[35]:
(array([1, 2]),)
In [36]:
np.array([1,2,3]) == np.array([1,2,3])
Out[36]:
array([ True, True, True], dtype=bool)
In [ ]:
In [ ]: