与常规 Python 列表相比,NumPy 有何优势?

发布于 2024-07-24 02:17:27 字数 378 浏览 4 评论 0原文

与常规 Python 列表相比,NumPy 有何优势?

我有大约 100 个金融市场系列,我将创建一个 100x100x100 = 100 万个单元的立方体数组。 我将对每个 x 与每个 y 和 z 进行回归(3 变量),以用标准误差填充数组。

我听说对于“大型矩阵”,出于性能和可扩展性的原因,我应该使用 NumPy 而不是 Python 列表。 事实是,我知道 Python 列表,而且它们似乎对我有用。

如果我迁移到 NumPy 会有什么好处?

如果我有 1000 个系列(即立方体中有 10 亿个浮点单元)怎么办?

What are the advantages of NumPy over regular Python lists?

I have approximately 100 financial markets series, and I am going to create a cube array of 100x100x100 = 1 million cells. I will be regressing (3-variable) each x with each y and z, to fill the array with standard errors.

I have heard that for "large matrices" I should use NumPy as opposed to Python lists, for performance and scalability reasons. Thing is, I know Python lists and they seem to work for me.

What will the benefits be if I move to NumPy?

What if I had 1000 series (that is, 1 billion floating point cells in the cube)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

鸠魁 2024-07-31 02:17:27

NumPy 的数组比 Python 列表更紧凑——您在 Python 中描述的列表列表至少需要 20 MB 左右,而单元格中具有单精度浮点数的 NumPy 3D 数组将适合 4 MB。 使用 NumPy 读取和写入项目的访问速度也更快。

也许您对一百万个单元并不太关心,但对十亿个单元肯定会关心——这两种方法都不适合 32 位架构,但在 64 位构建中,NumPy 会占用 4 GB 左右的内存,仅 Python 就需要至少约 12 GB(大量指针,大小加倍)——这是一个昂贵得多的硬件!

差异主要是由于“间接性”——Python 列表是指向 Python 对象的指针数组,每个指针至少有 4 个字节,加上最小的 Python 对象也有 16 个字节(4 个用于类型指针,4 个用于引用计数,4值——内存分配器向上舍入为 16)。 NumPy 数组是统一值的数组——单精度数字每个占用 4 个字节,双精度数字每个占用 8 个字节。 不太灵活,但是您为标准 Python 列表的灵活性付出了巨大的代价!

NumPy's arrays are more compact than Python lists -- a list of lists as you describe, in Python, would take at least 20 MB or so, while a NumPy 3D array with single-precision floats in the cells would fit in 4 MB. Access in reading and writing items is also faster with NumPy.

Maybe you don't care that much for just a million cells, but you definitely would for a billion cells -- neither approach would fit in a 32-bit architecture, but with 64-bit builds NumPy would get away with 4 GB or so, Python alone would need at least about 12 GB (lots of pointers which double in size) -- a much costlier piece of hardware!

The difference is mostly due to "indirectness" -- a Python list is an array of pointers to Python objects, at least 4 bytes per pointer plus 16 bytes for even the smallest Python object (4 for type pointer, 4 for reference count, 4 for value -- and the memory allocators rounds up to 16). A NumPy array is an array of uniform values -- single-precision numbers takes 4 bytes each, double-precision ones, 8 bytes. Less flexible, but you pay substantially for the flexibility of standard Python lists!

蒲公英的约定 2024-07-31 02:17:27

NumPy 不仅更高效,而且更高效。 也比较方便。 您可以免费获得大量向量和矩阵运算,这有时可以避免不必要的工作。 而且它们也得到了有效的实施。

例如,您可以直接从文件将立方体读入数组:

x = numpy.fromfile(file=open("data"), dtype=float).reshape((100, 100, 100))

沿第二个维度求和:

s = x.sum(axis=1)

查找哪些单元格高于阈值:

(x > 0.5).nonzero()

沿第三个维度删除每个偶数索引切片:

x[:, :, ::2]

此外,许多有用的库都使用 NumPy 数组。 例如,统计分析和可视化库。

即使你没有性能问题,学习 NumPy 也是值得的。

NumPy is not just more efficient; it is also more convenient. You get a lot of vector and matrix operations for free, which sometimes allow one to avoid unnecessary work. And they are also efficiently implemented.

For example, you could read your cube directly from a file into an array:

x = numpy.fromfile(file=open("data"), dtype=float).reshape((100, 100, 100))

Sum along the second dimension:

s = x.sum(axis=1)

Find which cells are above a threshold:

(x > 0.5).nonzero()

Remove every even-indexed slice along the third dimension:

x[:, :, ::2]

Also, many useful libraries work with NumPy arrays. For example, statistical analysis and visualization libraries.

Even if you don't have performance problems, learning NumPy is worth the effort.

二手情话 2024-07-31 02:17:27

Alex提到了内存效率,Roberto提到了便利性,这些都是优点。 对于更多想法,我将提到速度功能

功能:您可以使用 NumPy、FFT、卷积、快速搜索、基本统计、线性代数、直方图等内置很多功能。实际上,谁可以没有 FFT?

速度:这是对列表和 NumPy 数组进行求和的测试,显示 NumPy 数组上的求和速度快了 10 倍(在此测试中 - 里程可能会有所不同)。

from numpy import arange
from timeit import Timer

Nelements = 10000
Ntimeits = 10000

x = arange(Nelements)
y = range(Nelements)

t_numpy = Timer("x.sum()", "from __main__ import x")
t_list = Timer("sum(y)", "from __main__ import y")
print("numpy: %.3e" % (t_numpy.timeit(Ntimeits)/Ntimeits,))
print("list:  %.3e" % (t_list.timeit(Ntimeits)/Ntimeits,))

在我的系统上(当我运行备份时)给出:

numpy: 3.004e-05
list:  5.363e-04

Alex mentioned memory efficiency, and Roberto mentions convenience, and these are both good points. For a few more ideas, I'll mention speed and functionality.

Functionality: You get a lot built in with NumPy, FFTs, convolutions, fast searching, basic statistics, linear algebra, histograms, etc. And really, who can live without FFTs?

Speed: Here's a test on doing a sum over a list and a NumPy array, showing that the sum on the NumPy array is 10x faster (in this test -- mileage may vary).

from numpy import arange
from timeit import Timer

Nelements = 10000
Ntimeits = 10000

x = arange(Nelements)
y = range(Nelements)

t_numpy = Timer("x.sum()", "from __main__ import x")
t_list = Timer("sum(y)", "from __main__ import y")
print("numpy: %.3e" % (t_numpy.timeit(Ntimeits)/Ntimeits,))
print("list:  %.3e" % (t_list.timeit(Ntimeits)/Ntimeits,))

which on my systems (while I'm running a backup) gives:

numpy: 3.004e-05
list:  5.363e-04
滥情空心 2024-07-31 02:17:27

这是来自 scipy.org 网站

NumPy 数组相对于(嵌套)Python 列表有什么优势?

Python 的列表是高效的通用容器。 他们支持
(相当)高效的插入、删除、附加和串联,
Python 的列表推导式使它们易于构建和
操纵。 然而,它们有一定的局限性:它们不支持
“向量化”运算,例如元素加法和乘法,
它们可以包含不同类型的对象这一事实意味着
Python 必须存储每个元素的类型信息,并且必须
对每个元素进行操作时执行类型分派代码。 这
也意味着很少的列表操作可以通过
高效的 C 循环 – 每次迭代都需要类型检查和其他
Python API 簿记。

Here's a nice answer from the FAQ on the scipy.org website:

What advantages do NumPy arrays offer over (nested) Python lists?

Python’s lists are efficient general-purpose containers. They support
(fairly) efficient insertion, deletion, appending, and concatenation,
and Python’s list comprehensions make them easy to construct and
manipulate. However, they have certain limitations: they don’t support
“vectorized” operations like elementwise addition and multiplication,
and the fact that they can contain objects of differing types mean
that Python must store type information for every element, and must
execute type dispatching code when operating on each element. This
also means that very few list operations can be carried out by
efficient C loops – each iteration would require type checks and other
Python API bookkeeping.

昔日梦未散 2024-07-31 02:17:27

所有内容都强调了 numpy 数组和 python 列表之间的几乎所有主要差异,我将在这里简要介绍它们:

  1. Numpy 数组在创建时具有固定大小,这与 python 列表(可以动态增长)不同。 更改 ndarray 的大小将创建一个新数组并删除原始数组。

  2. Numpy 数组中的元素都必须具有相同的数据类型(我们也可以具有异构类型,但这不允许您进行数学运算),因此在内存中的大小相同

  3. Numpy 数组促进了对大量数据的数学和其他类型运算的进步。 通常,与使用序列中内置的 Python 相比,此类操作的执行效率更高,代码更少

All have highlighted almost all major differences between numpy array and python list, I will just brief them out here:

  1. Numpy arrays have a fixed size at creation, unlike python lists (which can grow dynamically). Changing the size of ndarray will create a new array and delete the original.

  2. The elements in a Numpy array are all required to be of the same data type (we can have the heterogeneous type as well but that will not gonna permit you mathematical operations) and thus will be the same size in memory

  3. Numpy arrays are facilitated advances mathematical and other types of operations on large numbers of data. Typically such operations are executed more efficiently and with less code than is possible using pythons build in sequences

对你再特殊 2024-07-31 02:17:27

Python 中标准的可变多元素容器是列表。 由于Python的动态类型,我们甚至可以创建异构列表。 为了允许这些灵活的类型,列表中的每个项目必须包含自己的类型信息、引用计数和其他信息。 也就是说,每一项都是一个完整的Python对象。
在所有变量都属于同一类型的特殊情况下,大部分信息都是多余的; 将数据存储在固定类型数组(NumPy 样式)中会更有效。
固定类型的 NumPy 样式数组缺乏这种灵活性,但存储和操作数据的效率要高得多。

The standard mutable multielement container in Python is the list. Because of Python's dynamic typing, we can even create heterogeneous list. To allow these flexible types, each item in the list must contain its own type info, reference count, and other information. That is, each item is a complete Python object.
In the special case that all variables are of the same type, much of this information is redundant; it can be much more efficient to store data in a fixed-type array (NumPy-style).
Fixed-type NumPy-style arrays lack this flexibility, but are much more efficient for storing and manipulating data.

白鸥掠海 2024-07-31 02:17:27
  • NumPy 不是另一种编程语言,而是 Python 扩展模块。 它提供了对同质数据数组的快速高效的操作。
    Numpy 具有固定的创建大小。
  • 在 Python 中:列表用方括号书写。
    这些列表可以是同构的,也可以是异质的。
  • 与 Python 列表相比,使用 Numpy 数组的主要优点:
    1. 消耗的内存更少。
    2. 与 python List 相比速度更快。
    3. 使用方便。
  • NumPy is not another programming language but a Python extension module. It provides fast and efficient operations on arrays of homogeneous data.
    Numpy has fixed size of creation.
  • In Python :lists are written with square brackets.
    These lists can be homogeneous or heterogeneous
  • The main advantages of using Numpy Arrays Over Python Lists:
    1. It consumes less memory.
    2. Fast as compared to the python List.
    3. Convenient to use.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文