NumPy属性及创建


numpy的初步学习,认识numpy和数组的创建。

一、NumPy是什么?

Numpy(Numerical Python)是一个开源的Python科学计数的基础库,他基于矩阵运算,用于大型多维数组执行数值计算,矩阵积计算。基于numpy的算法的计算速度比纯Python快10到100多倍,且占用的内存更少。

二、n维数组对象ndarray

1.创建数组

打开pycharm新建项目和文件后,开始numpy的熟练学习。

首先调用numpy模块:

import numpy as np

1.1 创建一个数组:

array = np.array([[1, 2, 3],
                  [4, 5, 6]])
print(array)                  
print('*'*20)                  
a = np.array([1, 2, 3]) #ndim=1、shape=(3,)
print(a)
print('*'*20) 
b = np.array([[1, 2, 3]]) #ndim=2、shape=(1, 3)
print(b)

out:

[[1 2 3]
 [4 5 6]]
********************
[1 2 3]
********************
[[1 2 3]]

1.2 创建特定数组:

c = np.zeros((3, 2))  # 全0
print(c)
d = np.ones((2, 3))   # 全1
print(d)
e = np.empty((1, 3))  # 接近为0
print(e)

out:

[[0. 0.]
 [0. 0.]
 [0. 0.]]
[[1. 1. 1.]
 [1. 1. 1.]]
[[8.73555232e+183 3.37248732e+063 1.27873980e-152]]
[10 12 14 16 18]

1.3 创建特定步长数组:

f = np.arange(10, 20, 2)  # 一维的,10-20内,步长为2
print(f)
print('dim:', f.ndim)
print('*'*20)
g = np.arange(12).reshape(3, 4)  # 34列的011,有reshape就修改了形状,成了二维
                                # (12,)是一维的;(2,23)是三维的
                                # 将多维转化为1维:.flatten()  
print(g)
print('dim:', g.ndim)
print('*'*20)
g1 = np.arange(12)
print(g1)
print('dim:', g1.ndim)
print('*'*20)
g2 = np.arange(12).reshape(1, 12)
print(g2)
print('dim:', g2.ndim)

out:

[10 12 14 16 18]
dim: 1
********************
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]
dim: 2
********************
[ 0  1  2  3  4  5  6  7  8  9 10 11]
dim: 1
********************
[[ 0  1  2  3  4  5  6  7  8  9 10 11]]
dim: 2

2.数组属性

数组常用属性:
.ndim、.shape、.size、.dtype、.itemsize

print('number of dim:', array.ndim) # 秩,数据的维度
print('shape:', array.shape) # ndarray对象的尺度,n行m列。
print('size:', array.size) # ndarray对象元素的个数
print('dtype:', array.dtype) # ndarray对象元素的类型
print('itemsize:', array.itemsize)  # 每个元素的大小(单位为字节)

out:

number of dim: 2
shape: (2, 3)
size: 6
dtype: int32
itemsize: 4

3.数据类型变化

3.1 ‘dtype’表示的类型有:float32/int64/int32/float64/float16/bool;可以通过dtype查看和在初始数据时设置存放的数据类型:

array = np.array([[1, 2, 3],
                  [4, 5, 6]], dtype=np.int64)
print(array.dtype)

out:

int64

3.2 ‘astype’数据类型转换

h = np.array([1, 0, 1, 0, 1], dtype=np.bool)
print(h)
print(h.dtype)
print('*'*50)
hh = h.astype(np.int8)
print(hh)
print(hh.dtype)

out:

[ True False  True False  True]
bool
**************************************************
[1 0 1 0 1]
int8

3.3 ‘random’随机数 ;及‘round’元素位数变化
用random时需要在顶部调用random模块:

import random
t = np.array([random.random() for i in range(10)])
print(t)
t1 = np.round(t, 2)  # 取两位小数
print(t1)

out:

[0.51020288 0.41456032 0.31339889 0.08749015]
[0.51  0.415 0.313 0.087]

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值