詹惠儿

2018-12-18   阅读量: 488

数据分析师 Python编程

numpy如何创建数组?

扫码加入数据分析学习群

数组创建:有多种方法可以在NumPy中创建数组。

  • 例如,您可以使用数组函数从常规Python 列表或元组创建数组。结果数组的类型是从序列中元素的类型推导出来的。
  • 通常,数组的元素最初是未知的,但其大小是已知的。因此,NumPy提供了几个函数来创建具有初始占位符内容的数组。这些最小化了增长阵列的必要性,这是一项昂贵的操作
    例如: np.zeros,np.ones,np.full,np.empty等。
  • 为了创建数字序列,NumPy提供了一个类似于返回数组而不是列表的范围的函数。
  • arange:在给定的时间间隔内返回均匀间隔的值。长是指定的。
  • linspace:在给定的时间间隔内返回均匀间隔的值。NUM没有。返回元素。
  • 重塑数组:我们可以使用重塑方法来重塑数组。考虑一个具有形状的数组(a1,a2,a3,...,aN)。我们可以重塑并将其转换为另一个具有形状的数组(b1,b2,b3,...,bM)。唯一需要的条件是:
    a1 x a2 x a3 ... x aN = b1 x b2 x b3 ... x bM。(即阵列的原始大小保持不变。)
  • 展平数组:我们可以使用展平方法将数据的副本折叠到一个维度。它接受订单参数。默认值为“C”(对于行主要顺序)。对列主要订单使用“F”。

注意:创建数组时可以显式定义数组类型。

# Python program to demonstrate

# array creation techniques

import numpy as np

# Creating array from list with type float

a = np.array([[1, 2, 4], [5, 8, 7]], dtype = 'float')

print ("Array created using passed list:\n", a)

# Creating array from tuple

b = np.array((1 , 3, 2))

print ("\nArray created using passed tuple:\n", b)

# Creating a 3X4 array with all zeros

c = np.zeros((3, 4))

print ("\nAn array initialized with all zeros:\n", c)

# Create a constant value array of complex type

d = np.full((3, 3), 6, dtype = 'complex')

print ("\nAn array initialized with all 6s."

"Array type is complex:\n", d)

# Create an array with random values

e = np.random.random((2, 2))

print ("\nA random array:\n", e)

# Create a sequence of integers

# from 0 to 30 with steps of 5

f = np.arange(0, 30, 5)

print ("\nA sequential array with steps of 5:\n", f)

# Create a sequence of 10 values in range 0 to 5

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

print ("\nA sequential array with 10 values between"

"0 and 5:\n", g)

# Reshaping 3X4 array to 2X2X3 array

arr = np.array([[1, 2, 3, 4],

[5, 2, 4, 2],

[1, 2, 0, 1]])

newarr = arr.reshape(2, 2, 3)

print ("\nOriginal array:\n", arr)

print ("Reshaped array:\n", newarr)

# Flatten array

arr = np.array([[1, 2, 3], [4, 5, 6]])

flarr = arr.flatten()

print ("\nOriginal array:\n", arr)

print ("Fattened array:\n", flarr)

添加CDA认证专家【维克多阿涛】,微信号:【cdashijiazhuang】,提供数据分析指导及CDA考试秘籍。已助千人通过CDA数字化人才认证。欢迎交流,共同成长!
0.0000 0 2 关注作者 收藏

评论(0)


暂无数据

推荐课程

推荐帖子