大数据Python基础之ndarray数据结构学习

1.数据对象ndarray要求所有元素的数据类型必须一致,可以为ndarray指定类型

import numpy as np
arr = np.array([2, 5.0, "6"], dtype = np.float64)
print arr

输出:
[ 2. 5. 6.]
2.生成ndarray数组对象

import numpy as np
print np.array([1, 2, 3])
print np.zeros((2, 2))
print np.ones((2, 2))
print np.arange(6)
print np.zeros(10).reshape((2, 5))

输出:
[1 2 3]
[[ 0. 0.]
[ 0. 0.]]
[[ 1. 1.]
[ 1. 1.]]
[0 1 2 3 4 5]
[[ 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0.]]
3.ndarray的基本属性
ndim的属性,表示数组的维度
shape属性,表示每一个维度的数量(元组)
dtype属性,描述数组元素的数据类型
Itemsize属性,表示单个元素的大小(字节)
size属性:表示数据量的大小

import numpy as np
arr = np.zeros(15).reshape((3, 5))
print np.ndim(arr)
print np.shape(arr)
print arr.dtype
print arr.itemsize
print np.size(arr)

输出:
2
(3, 5)
float64
8
15
4.ndarray的基本方法
reshape(shape),返回一个新数组,原数组不变
flatten(),降为一维数组,原数组不变
resize(shape),修改原数组
tolist(),将数组转换为列表

import numpy as np
arr = np.zeros(10).reshape((2, 5))
print arr.flatten()
print arr
arr.resize(1, 10)
print(arr)
print arr.tolist()

输出:
[ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[[ 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0.]]
[[ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]]
[[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]]
5.数组的切片
不同于Python的列表,数组的切片是原数组的视图而非拷贝,任何对视图的修改都会反映到原数组上(原因:大数据的效率)。需要拷贝时,应显示复制数组,如arr[5:8].copy()

import numpy as np
arr2d = np.arange(20).reshape([4, 5])
print arr2d
print arr2d[::-2, ::-2]
print arr2d[:2:-2, 1::-2]

输出:
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]
[15 16 17 18 19]]
[[19 17 15]
[ 9 7 5]]
[[16]]

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值