GuoXin Li's Blog

Numpy generate array

字数统计: 444阅读时长: 2 min
2018/09/14 151 Share

Create array

1
2
3
4
5
a = np.array([[1,2,3,4],[5,6,7,8]])
print(a)
'''array([[1, 2, 3, 4],
[5, 6, 7, 8]])
'''
  • ndarray.ndim: show the dimensionality of array
1
2
a.ndim
# 2
  • ndarray.shape: show the length of array in every direction
1
2
a.shape
# (2,4)
  • ndarray.size: show the size of array(the value = the product of every item in shape)
1
2
a.size
# 8
  • ndarray.dtype: assign the data type
1
2
a.dtype
# dtype('int64')
  • ndarray.itemsize: calculate the size of every item in the memory. e.g. a float64 type of data occupies 8 bit in computer memory.

  • ndarray.data: show the address of this array in memory.

Create array with assigned data

  • int
1
2
3
a = np.array([1,2,3,4],dtype = np.int)    #(int8,int16,int64......)
print(a)
#int 64 (defult )
  • float
1
2
3
a = np.array([1,2,3,4],dtype = np.float)#(float32......)
print(a)
#float 64(defult)

Create the specific array

1
2
3
4
5
6
a = np.array([1,2,3,4],[5,6,7,8])
print(a)
'''
[[1,2,3,4]
[5,6,7,8]]
'''

Create the zero array

  • all zero
1
2
3
4
5
6
7
a = np.zeros((3,4)) #3 row 4 line
print(a)
'''
array([[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.]])
'''
  • create array and assign data type
1
2
3
4
5
6
a = np.ones((3,4),dtype = np.int)
'''
array([[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1]])
'''
  • create all empty array(every value is close to zero)
1
2
3
4
5
6
a = np.empty((3,4))    #the value is close to zero, 3 row 4 line
'''
array([[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.]])
'''

The “arange() “ function

arange() has three parameter, arange( , , * )

  • first
1
2
np.arange(6)
# array([0,1,2,3,4,5])
  • second
1
2
np.arange(0,6)    #the former is the initial value, the latter is the end value
# array([0,1,2,3,4,5,])
  • third
1
2
np.arange(1,3,0.5)# the third parameter is the interval value.
#array([0. , 0.5, 1. , 1.5, 2. , 2.5])

The “linspace()“ function

linspace() can generate an well-proportion array in assigned interval range.

1
2
3
4
5
6
7
8
np.linspace(0,10,20)
'''
array([ 0. , 0.52631579, 1.05263158, 1.57894737, 2.10526316,
2.63157895, 3.15789474, 3.68421053, 4.21052632, 4.73684211,
5.26315789, 5.78947368, 6.31578947, 6.84210526, 7.36842105,
7.89473684, 8.42105263, 8.94736842, 9.47368421, 10. ])

'''

rand() function generate array in range of [ 0,1 )

1
2
3
4
5
6
7
8
9
10
11
np.random.rand(2,3,3)
'''
array([[[0.98995132, 0.51327869, 0.35285681],
[0.64515764, 0.17032915, 0.17255685],
[0.51559337, 0.98184312, 0.32625729]],

[[0.5182059 , 0.09902392, 0.96491655],
[0.18805998, 0.74772964, 0.91896079],
[0.39425633, 0.84583609, 0.77468997]]])

'''
Powered By Valine
v1.5.2
CATALOG
  1. 1. Create array
  2. 2. Create array with assigned data
  3. 3. Create the specific array
  4. 4. Create the zero array
  5. 5. The “arange() “ function
  6. 6. The “linspace()“ function
  7. 7. rand() function generate array in range of [ 0,1 )