Python数据分析学习(二):Numpy数组对象基础

1.1数组对象基础

 

1.初识数组对象

In [1]:
import numpy as np
np.__version__
Out[1]:
'1.14.0'
In [2]:
data = np.array([1,2,3,4,5])
data
Out[2]:
array([1, 2, 3, 4, 5])
In [3]:
type(data)
Out[3]:
numpy.ndarray
In [4]:
dir(data)
Out[4]:
['T',
 '__abs__',
 '__add__',
 '__and__',
 '__array__',
 '__array_finalize__',
 '__array_interface__',
 '__array_prepare__',
 '__array_priority__',
 '__array_struct__',
 '__array_ufunc__',
 '__array_wrap__',
 '__bool__',
 '__class__',
 '__complex__',
 '__contains__',
 '__copy__',
 '__deepcopy__',
 '__delattr__',
 '__delitem__',
 '__dir__',
 '__divmod__',
 '__doc__',
 '__eq__',
 '__float__',
 '__floordiv__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getitem__',
 '__gt__',
 '__hash__',
 '__iadd__',
 '__iand__',
 '__ifloordiv__',
 '__ilshift__',
 '__imatmul__',
 '__imod__',
 '__imul__',
 '__index__',
 '__init__',
 '__init_subclass__',
 '__int__',
 '__invert__',
 '__ior__',
 '__ipow__',
 '__irshift__',
 '__isub__',
 '__iter__',
 '__itruediv__',
 '__ixor__',
 '__le__',
 '__len__',
 '__lshift__',
 '__lt__',
 '__matmul__',
 '__mod__',
 '__mul__',
 '__ne__',
 '__neg__',
 '__new__',
 '__or__',
 '__pos__',
 '__pow__',
 '__radd__',
 '__rand__',
 '__rdivmod__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__rfloordiv__',
 '__rlshift__',
 '__rmatmul__',
 '__rmod__',
 '__rmul__',
 '__ror__',
 '__rpow__',
 '__rrshift__',
 '__rshift__',
 '__rsub__',
 '__rtruediv__',
 '__rxor__',
 '__setattr__',
 '__setitem__',
 '__setstate__',
 '__sizeof__',
 '__str__',
 '__sub__',
 '__subclasshook__',
 '__truediv__',
 '__xor__',
 'all',
 'any',
 'argmax',
 'argmin',
 'argpartition',
 'argsort',
 'astype',
 'base',
 'byteswap',
 'choose',
 'clip',
 'compress',
 'conj',
 'conjugate',
 'copy',
 'ctypes',
 'cumprod',
 'cumsum',
 'data',
 'diagonal',
 'dot',
 'dtype',
 'dump',
 'dumps',
 'fill',
 'flags',
 'flat',
 'flatten',
 'getfield',
 'imag',
 'item',
 'itemset',
 'itemsize',
 'max',
 'mean',
 'min',
 'nbytes',
 'ndim',
 'newbyteorder',
 'nonzero',
 'partition',
 'prod',
 'ptp',
 'put',
 'ravel',
 'real',
 'repeat',
 'reshape',
 'resize',
 'round',
 'searchsorted',
 'setfield',
 'setflags',
 'shape',
 'size',
 'sort',
 'squeeze',
 'std',
 'strides',
 'sum',
 'swapaxes',
 'take',
 'tobytes',
 'tofile',
 'tolist',
 'tostring',
 'trace',
 'transpose',
 'var',
 'view']
In [5]:
data?
In [6]:
# 数组元素的类型
data.dtype
Out[6]:
dtype('int64')
In [7]:
# 修改数组类型
new_data = data.astype(np.float)
new_data
Out[7]:
array([1., 2., 3., 4., 5.])
In [8]:
new_data.dtype
Out[8]:
dtype('float64')
In [9]:
data,data.dtype
Out[9]:
(array([1, 2, 3, 4, 5]), dtype('int64'))
In [10]:
# 数组的外貌
a = np.array([1,2,3])
b = np.array([1.0,2.0,3.0])
a.dtype,b.dtype
Out[10]:
(dtype('int64'), dtype('float64'))
In [11]:
a.shape
Out[11]:
(3,)
In [12]:
b.shape
Out[12]:
(3,)
In [13]:
c = np.array([1.0,2.0,3.0,4.0])
c.shape
Out[13]:
(4,)
In [14]:
# 维度
a.ndim
Out[14]:
1
In [15]:
# 返回元素个数
a.size
Out[15]:
3
In [16]:
c.size
Out[16]:
4
 

常用属性

  • dtype:返回数组元素的类型
  • shape:返回一个元组,元组中的每个整数依次对应数组的每个轴的元素个数
  • size:返回数组中元素个数
  • ndim:返回数组维度
  • nbytes:返回保存数据的字节数
 

2.创建数组

In [17]:
np.array?
In [18]:
a = np.array([1,2,3,4])
b = np.array([1,2,3,4],dtype=float)

a
Out[18]:
array([1, 2, 3, 4])
In [19]:
a.dtype
Out[19]:
dtype('int64')
In [20]:
a.shape
Out[20]:
(4,)
In [21]:
a.size
Out[21]:
4
In [22]:
a.ndim
Out[22]:
1
In [23]:
b
Out[23]:
array([1., 2., 3., 4.])
In [24]:
b.dtype
Out[24]:
dtype('float64')
In [25]:
# 多维数组,数组的元素类型必须一致
da = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]])
da
Out[25]:
array([[ 1,  2,  3,  4],
       [ 5,  6,  7,  8],
       [ 9, 10, 11, 12]])
In [26]:
np.array([[1,2,3],[4,5,6,7],[8,9]])
Out[26]:
array([list([1, 2, 3]), list([4, 5, 6, 7]), list([8, 9])], dtype=object)
In [27]:
da.shape
Out[27]:
(3, 4)
In [28]:
da.size
Out[28]:
12
In [29]:
db = np.array([[1,2,3,4,5,6,7]],ndmin=2)
db
Out[29]:
array([[1, 2, 3, 4, 5, 6, 7]])
In [30]:
db.shape
Out[30]:
(1, 7)
In [31]:
db.ndim
Out[31]:
2
In [32]:
dc = np.array([1,2,3,4,5,6,7])
dc
Out[32]:
array([1, 2, 3, 4, 5, 6, 7])
In [33]:
dc.shape
Out[33]:
(7,)
In [34]:
dc.ndim
Out[34]:
1
In [35]:
a
Out[35]:
array([1, 2, 3, 4])
In [36]:
de = np.array(a,dtype=complex)
de
Out[36]:
array([1.+0.j, 2.+0.j, 3.+0.j, 4.+0.j])
In [37]:
de.dtype
Out[37]:
dtype('complex128')
In [38]:
# 用函数创建数组
np.zeros((2,10))
Out[38]:
array([[0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]])
In [39]:
np.zeros?
In [40]:
# zeros(shape, dtype=float, order='C')
 

同一种元素的数组

In [41]:
np.ones((6,))
Out[41]:
array([1., 1., 1., 1., 1., 1.])
In [42]:
# 一维数组才能这样写
np.ones(6)
Out[42]:
array([1., 1., 1., 1., 1., 1.])
In [43]:
da
Out[43]:
array([[ 1,  2,  3,  4],
       [ 5,  6,  7,  8],
       [ 9, 10, 11, 12]])
In [44]:
da.shape
Out[44]:
(3, 4)
In [45]:
np.ones(da.shape)
Out[45]:
array([[1., 1., 1., 1.],
       [1., 1., 1., 1.],
       [1., 1., 1., 1.]])
In [46]:
np.ones_like(da)
Out[46]:
array([[1, 1, 1, 1],
       [1, 1, 1, 1],
       [1, 1, 1, 1]])
In [47]:
np.ones_like(da,dtype=np.float)
Out[47]:
array([[1., 1., 1., 1.],
       [1., 1., 1., 1.],
       [1., 1., 1., 1.]])
In [48]:
df = 6.4 * np.ones_like(da)
df
Out[48]:
array([[6.4, 6.4, 6.4, 6.4],
       [6.4, 6.4, 6.4, 6.4],
       [6.4, 6.4, 6.4, 6.4]])
 

对角线独特的数组

  • np.eye(),np.identity(),np.diag()都能创建对角线元素比较特殊而其他部分的元素为0的数组
In [49]:
np.eye(4,dtype=int)
Out[49]:
array([[1, 0, 0, 0],
       [0, 1, 0, 0],
       [0, 0, 1, 0],
       [0, 0, 0, 1]])
In [50]:
np.eye(4,dtype=int,k=1)
Out[50]:
array([[0, 1, 0, 0],
       [0, 0, 1, 0],
       [0, 0, 0, 1],
       [0, 0, 0, 0]])
In [51]:
np.eye(4,dtype=int,k=-1)
Out[51]:
array([[0, 0, 0, 0],
       [1, 0, 0, 0],
       [0, 1, 0, 0],
       [0, 0, 1, 0]])
In [52]:
np.identity(4)
Out[52]:
array([[1., 0., 0., 0.],
       [0., 1., 0., 0.],
       [0., 0., 1., 0.],
       [0., 0., 0., 1.]])
In [53]:
np.diag([1,2,3,4])
Out[53]:
array([[1, 0, 0, 0],
       [0, 2, 0, 0],
       [0, 0, 3, 0],
       [0, 0, 0, 4]])
In [54]:
np.diag([1,2,3,4],k=1)
Out[54]:
array([[0, 1, 0, 0, 0],
       [0, 0, 2, 0, 0],
       [0, 0, 0, 3, 0],
       [0, 0, 0, 0, 4],
       [0, 0, 0, 0, 0]])
In [55]:
de = np.arange(16).reshape((4,4))
de
Out[55]:
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15]])
In [56]:
np.diag(de)
Out[56]:
array([ 0,  5, 10, 15])
In [57]:
np.diag(de,k=-1)
Out[57]:
array([ 4,  9, 14])
 

元素是等差和等比的数组

In [58]:
# arange([start,] stop[, step,], dtype=None)
np.arange(1,100,3)
Out[58]:
array([ 1,  4,  7, 10, 13, 16, 19, 22, 25, 28, 31, 34, 37, 40, 43, 46, 49,
       52, 55, 58, 61, 64, 67, 70, 73, 76, 79, 82, 85, 88, 91, 94, 97])
In [59]:
np.arange?
In [60]:
# np.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)
np.linspace(1,10,4)
Out[60]:
array([ 1.,  4.,  7., 10.])
In [61]:
np.linspace?
In [62]:
np.logspace?
In [63]:
# np.logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None)
np.logspace(2,3,num=4)
Out[63]:
array([ 100.        ,  215.443469  ,  464.15888336, 1000.        ])
In [64]:
import math
math.log10(215.443469)
Out[64]:
2.333333333326906
In [65]:
math.log10(464.15888336)
Out[65]:
2.666666666665471
 

创建自定义类型的数组

In [66]:
my_type = np.dtype({"names":['book','version'],"formats":['S40',np.int]})
my_type
Out[66]:
dtype([('book', 'S40'), ('version', '<i8')])
In [67]:
my_books = np.array([("python",2),("java",1)],dtype=my_type)
my_books
Out[67]:
array([(b'python', 2), (b'java', 1)],
      dtype=[('book', 'S40'), ('version', '<i8')])
In [68]:
# 同my_type
my_type2 = np.dtype([('book','S40'),('version','<i8')])
In [69]:
my_books['book']
Out[69]:
array([b'python', b'java'], dtype='|S40')
In [70]:
my_books['book'][0]
Out[70]:
b'python'
In [71]:
my_books[0]
Out[71]:
(b'python', 2)
In [72]:
my_books[0]['book']
Out[72]:
b'python'
In [73]:
# 修改记录
my_books[0]['book'] = "learn python"
my_books
Out[73]:
array([(b'learn python', 2), (b'java', 1)],
      dtype=[('book', 'S40'), ('version', '<i8')])
 
  • 数组一旦确定,其轴的数量就不能变化
 

用from系列函数创建数组

In [74]:
#s = 'hello world'
np.frombuffer(b'hello world',dtype='S1',count=5,offset=6)
Out[74]:
array([b'w', b'o', b'r', b'l', b'd'], dtype='|S1')
In [75]:
np.frombuffer?
In [76]:
def foo(x):
    return x + 1
np.fromfunction(foo,(5,),dtype=np.int)
Out[76]:
array([1, 2, 3, 4, 5])
In [77]:
np.fromfunction(lambda i,j:(i+1)*(j+1),(9,9),dtype=np.int)
Out[77]:
array([[ 1,  2,  3,  4,  5,  6,  7,  8,  9],
       [ 2,  4,  6,  8, 10, 12, 14, 16, 18],
       [ 3,  6,  9, 12, 15, 18, 21, 24, 27],
       [ 4,  8, 12, 16, 20, 24, 28, 32, 36],
       [ 5, 10, 15, 20, 25, 30, 35, 40, 45],
       [ 6, 12, 18, 24, 30, 36, 42, 48, 54],
       [ 7, 14, 21, 28, 35, 42, 49, 56, 63],
       [ 8, 16, 24, 32, 40, 48, 56, 64, 72],
       [ 9, 18, 27, 36, 45, 54, 63, 72, 81]])
原文地址:https://www.cnblogs.com/prince5460/p/10404082.html