NumPy 数组对象

来源:互联网 发布:java搭建运行环境 编辑:程序博客网 时间:2024/06/05 05:58

NumPy 数组对象

       NumPy数组一般是同质的(但有一种特殊的数组类型例外,它是异质的),即数组中的所有元素类型必须是一致的。这样有一个好处:如果我们知道数组中的元素均为同一类型,该数组所需的存储空间就很容易确定下来。NumPy数组的下标也是从0开始的。

example 1

## Created by strong on 12/12/17#import numpy as np# Beginning with NumPy fundamentals## Demonstrates the dtype and shape attributes# of ndarray.## Run from the commandline with##  python arrayattributes.pya = np.arange(5)print "In: a = arange(5)"print "In: a.dtype"print a.dtype#Out: dtype('int64')printprint "In: a.shape"print a.shape#Out: (5,)printprint "In: a"print a#Out[4]: array([0, 1, 2, 3, 4])print

=>

/usr/bin/python2.7 /home/strong/PycharmProjects/crash_course/numpy_function/numpy_dtype_shape.pyIn: a = arange(5)In: a.dtypeint64In: a.shape(5,)In: a[0 1 2 3 4]Process finished with exit code 0


example 2

strong@foreverstrong:~$ pythonPython 2.7.12 (default, Nov 20 2017, 18:23:56) [GCC 5.4.0 20160609] on linux2Type "help", "copyright", "credits" or "license" for more information.>>> import numpy as np>>> a = np.arange(5)>>> a.dtypedtype('int64')>>> a.shape(5,)>>> aarray([0, 1, 2, 3, 4])>>> exit()strong@foreverstrong:~$

        这是一个包含5个元素的向量,取值分别为0~4的整数。数组的shape属性返回一个元组(tuple),元组中的元素即为NumPy数组每一个维度上的大小。上面例子中的数组是一维的,因此元组中只有一个元素。


references

[1] (印尼) Ivan Idris (伊德里斯) 著, 张驭宇 译. Python数据分析基础教程:NumPy学习指南 (第2版) [M]. 北京:人民邮电出版社, 2014. 1-226