Python Numpy常用操作

1  np.split():

Parameters:

ary : ndarray

Array to be divided into sub-arrays.

indices_or_sections : int or 1-D array

If indices_or_sections is an integer, N, the array will be divided into N equal arrays along axis. If such a split is not possible, an error is raised.

If indices_or_sections is a 1-D array of sorted integers, the entries indicate where along axis the array is split. For example, [2, 3] would, for axis=0, result in

  • ary[:2]
  • ary[2:3]
  • ary[3:]

If an index exceeds the dimension of the array along axis, an empty sub-array is returned correspondingly.

axis : int, optional

The axis along which to split, default is 0.

Returns:

sub-arrays : list of ndarrays

A list of sub-arrays.

Raises:

ValueError

扫描二维码关注公众号,回复: 2755851 查看本文章

If indices_or_sections is given as an integer, but a split does not result in equal division.

例子:

1 当数据划分均等的时候:

>>> x = np.arange(9.0)
>>> np.split(x, 3)
输出:[array([ 0.,  1.,  2.]), array([ 3.,  4.,  5.]), array([ 6.,  7.,  8.])]
 
>>> x = np.arange(8.0)
>>> np.split(x, [3, 5, 6, 10])
输出:[array([ 0.,  1.,  2.]),
 array([ 3.,  4.]),
 array([ 5.]),
 array([ 6.,  7.]),
 array([], dtype=float64)]
 2 当数据划分不均等的时候,报错;

import numpy as np
x = np.arange(7.0)
print(np.split(x, 2))

'array split does not result in an equal division')
ValueError: array split does not result in an equal division
此时使用 np.arry_split()

>>> x = np.arange(8.0)
>>> np.array_split(x, 3)
    [array([ 0.,  1.,  2.]), array([ 3.,  4.,  5.]), array([ 6.,  7.])]
 
>>> x = np.arange(7.0)
>>> np.array_split(x, 3)
    [array([ 0.,  1.,  2.]), array([ 3.,  4.]), array([ 5.,  6.])]

成功。

2  np.random.seed
  
seed( ) 用于指定随机数生成时所用算法开始的整数值,如果使用相同的seed( )值,则每次生成的随即数都相同,如果不设置这个值,则系统根据时间来自己选择这个值,此时每次生成的随机数因时间差异而不同。
如下测试:

from numpy import *

num=0

while(num<5):

   random.seed(5)

   print(random.random())

   num+=1

结果:

再次修改以上代码:

from numpy import *

num=0

random.seed(5)

while(num<5):

    print(random.random())

    num+=1

结果:

可以看出:random.seed(something)只能是一次有效。这个用的时候要注意。

猜你喜欢

转载自blog.csdn.net/qq_29750461/article/details/81660181