01 使用numpy处理数据、ndarry创建

== 传统处理数据,给每个人的成绩加10分 ==

scores=[89,33,11]
for i in scores:
    print(i+10)
type(scores)

99 43 21
list

=== 使用numpy处理数据 ===

1、 引入numpy的包

import numpy as np

2、 把Python序列转换为ndarray

nd_scores = np.array(scores)
nd_scores

[89 33 11]
numpy.ndarray
元组、列表都可以转ndarray

3、 numpy运算

nd_scores+10

array([99, 43, 21])
多维数组也可以完成运算

scores = [[[1,2],[2,1]],[[3,2],[2,3]],[[4,5],[5,4]]]
nd_scores = np.array(scores)
nd_scores+10

array([[[11, 12], [12, 11]], [[13, 12], [12, 13]], [[14, 15], [15, 14]]])

=== 创建全零数组 zeros(维度) ===

np.zeros([4,3,2])

array([[[ 0., 0.], [ 0., 0.], [ 0., 0.]],
[[ 0., 0.], [ 0., 0.], [ 0., 0.]],
[[ 0., 0.], [ 0., 0.], [ 0., 0.]],
[[ 0., 0.], [ 0., 0.], [ 0., 0.]]])

=== 全1数组 ones(维度) ===

np.ones(10)

array([ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.])

=== 空数组(效率高,但值不确定) ===

np.empty([10,10])

=== 随机数组 ===

1、 随机变量(0-1)之间

np.random.random([3,3])

2、 randint(start,end,维度) 随机变量(0~100)之间

np.random.randint(0,100,[3,3])

array([[62, 9, 64],
[72, 75, 82],
[87, 10, 37]])

3、 randn(维度1,维度2,维度3) 正态分布

np.random.randn(3,3)

array([[ 0.19903116, 1.42663184, -1.06911124],
[-0.40775623, -0.31115808, 0.28252054],
[-1.25061248, -0.4549277 , -0.40148327]])

=== 创建 从n-m的数组,指定步长 ===

arange(start,end,step)

np1 = np.arange(0,100,1)
np1

array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99])

=== 等差数列 ===

linspace(start,end,num=50)

np2 = np.linspace(0,10,5)
np2

array([ 0. , 2.5, 5. , 7.5, 10. ])

=== 等比数列 ===

logspace(start,end,num,base=10)
10的start次方,10的end次方,一共10个数,默认底数为10

np3 = np.logspace(0,9,10,base=2)
np3

array([ 1., 2., 4., 8., 16., 32., 64., 128., 256., 512.])

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容