# Numpy使用4

## 通用函数

```In [87]: arr
Out[87]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

In [88]: np.sq
np.sqrt     np.square   np.squeeze

In [88]: np.sqrt(arr)
Out[88]:
array([ 0.        ,  1.        ,  1.41421356,  1.73205081,  2.        ,
2.23606798,  2.44948974,  2.64575131,  2.82842712,  3.        ])

In [92]: y = np.random.randn(10)

In [93]: x = np.random.randn(10)

In [94]: x
Out[94]:
array([-1.21694813,  1.78409159, -1.65434122, -0.15399479,  1.60253837,
0.74424786, -0.67561382, -0.40101547,  0.98082673, -2.02494822])

In [95]: y
Out[95]:
array([-0.00402273, -0.06694182, -2.65686769, -0.39958789, -0.77770152,
0.13560955,  0.80155845, -0.65633865, -0.10009588,  2.00409772])

In [96]: np.maxi
np.maximum         np.maximum_sctype

In [96]: np.maximum(x,y)
Out[96]:
array([-0.00402273,  1.78409159, -1.65434122, -0.15399479,  1.60253837,
0.74424786,  0.80155845, -0.40101547,  0.98082673,  2.00409772])```

## 利用numpy进行数据处理

```In [97]: arr = np.random.randn(4,4)

In [98]: arr
Out[98]:
array([[-1.91177362,  0.82087817,  0.74335108,  1.80535455],
[-1.04152013, -1.55160244,  0.58826121,  0.0138859 ],
[ 0.86341095,  2.0301454 ,  0.75151171, -0.38441971],
[-0.95949818,  0.39064892,  0.17747275, -0.00499914]])

In [99]: np.where(arr>0, 2, -2) ## 矢量化版本的if condition
Out[99]:
array([[-2,  2,  2,  2],
[-2, -2,  2,  2],
[ 2,  2,  2, -2],
[-2,  2,  2, -2]])```

(1)数学与统计

```In [101]: arr = np.random.randn(4,4)

In [102]: arr
Out[102]:
array([[ 1.22742206, -0.49602643,  0.06893939, -0.5974265 ],
[ 1.33043955, -0.24695017,  1.39751381, -0.23691971],
[-1.25554674,  0.37242292, -0.14985591, -0.11907288],
[ 0.06103707, -1.28255389, -0.67935123, -1.35710905]])

In [103]: arr.mean()
Out[103]: -0.1226898557091208

In [104]: arr.mean(axis=0)
Out[104]: array([ 0.34083799, -0.41327689,  0.15931151, -0.57763203])

In [105]: arr.mean(axis=1)
Out[105]: array([ 0.05072713,  0.56102087, -0.28801315, -0.81449428])

In [106]: arr.sum()
Out[106]: -1.9630376913459329

In [107]: arr.sum(axis=0)
Out[107]: array([ 1.36335194, -1.65310755,  0.63724605, -2.31052813])```

(2)数组的集合运算

```In [108]: values = np.array([2,3,1,6,7,4])

In [109]: values1 = np.array([2,6,8])

In [110]: np.in1d(values, values1) ## 判断values的元素是否在values1中
Out[110]: array([ True, False, False,  True, False, False], dtype=bool)```

(3)文件的输入输出

```In [112]: test_write = np.arange(10)

In [113]: np.save('test',test_write)  ## 会在当前目录下创建名叫"test.npy"的二进制文件

Out[115]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])```

89 篇文章41 人订阅

0 条评论

## 相关文章

3296

3499

3497

3498

36810

3335

1002

### LeetCode55. 跳跃游戏

首先创建一个index数组，存储当前位置最大可达的数组下标，就以样例1来举例，输入是[2,3,1,1,4],那么对应的这个index数组就是[2,4,3...

1502

### Eclipse油藏模型解析程序

2010年的时候，三维可视化项目中要读取eclipse建模软件产生的三维模型网格数据，经过连续多天的奋战，终于搞明白eclipse数模软件输出的egrid、in...

2937

2926