GVKun编程网logo

使用 NumPy 替换 Python 中的嵌套循环(numpy替换元素)

1

在本文中,您将会了解到关于使用NumPy替换Python中的嵌套循环的新资讯,同时我们还将为您解释numpy替换元素的相关在本文中,我们将带你探索使用NumPy替换Python中的嵌套循环的奥秘,分析

在本文中,您将会了解到关于使用 NumPy 替换 Python 中的嵌套循环的新资讯,同时我们还将为您解释numpy替换元素的相关在本文中,我们将带你探索使用 NumPy 替换 Python 中的嵌套循环的奥秘,分析numpy替换元素的特点,并给出一些关于"import numpy as np" ImportError: No module named numpy、add.Constrs Gurobi 中的嵌套循环、Ansible 中的嵌套循环?、Difference between import numpy and import numpy as np的实用技巧。

本文目录一览:

使用 NumPy 替换 Python 中的嵌套循环(numpy替换元素)

使用 NumPy 替换 Python 中的嵌套循环(numpy替换元素)

如何解决使用 NumPy 替换 Python 中的嵌套循环

所以我有这 6 个嵌套循环,它们的目的只是在不同的索引上将数组 XY 相乘和相加得到数组 Z

import numpy as np

dim_a = 5
dim_b = 9
Z = np.zeros((dim_a,dim_b,dim_a))
X = np.arange(2025).reshape(dim_a,dim_a)
Y = np.arange(2025).reshape(dim_a,dim_a)

for i in range(0,dim_a):
    for j in range(0,dim_a):
        for a in range(0,dim_b):
            for b in range(0,dim_b):
                for m in range(0,dim_a):
                    for e in range(0,dim_b):
                        Z[i,a,b,j] += X[m,e,j] * Y[m,i] * 2

有没有办法用 NumPy 只用几行代码来编写它?这些嵌套循环的计算工作量是巨大的。我有一种感觉,NumPy 可以显着优化它。

解决方法

你当然可以用np.einsum

Z[i,a,b,j] += X[m,e,j] * Y[m,i] * 2

翻译为

Z = np.einsum(''mebj,meai->iabj'',X,Y) * 2

"import numpy as np" ImportError: No module named numpy

问题:没有安装 numpy

解决方法:

下载文件,安装

numpy-1.8.2-win32-superpack-python2.7

安装运行 import numpy,出现

Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    import numpy
  File "C:\Python27\lib\site-packages\numpy\__init__.py", line 153, in <module>
    from . import add_newdocs
  File "C:\Python27\lib\site-packages\numpy\add_newdocs.py", line 13, in <module>
    from numpy.lib import add_newdoc
  File "C:\Python27\lib\site-packages\numpy\lib\__init__.py", line 8, in <module>
    from .type_check import *
  File "C:\Python27\lib\site-packages\numpy\lib\type_check.py", line 11, in <module>
    import numpy.core.numeric as _nx
  File "C:\Python27\lib\site-packages\numpy\core\__init__.py", line 6, in <module>
    from . import multiarray
ImportError: DLL load failed: %1 不是有效的 Win32 应用程序。

原因是:python 装的是 64 位的,numpy 装的是 32 位的

重新安装 numpy 为:numpy-1.8.0-win64-py2.7

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

add.Constrs Gurobi 中的嵌套循环

add.Constrs Gurobi 中的嵌套循环

如何解决add.Constrs Gurobi 中的嵌套循环

我正在尝试在取货节点和交付节点之间添加一些时间约束,并且我想对这样一个事实进行建模,即交付节点的时间高于与其关联的取货节点的时间。

这是我的代码:

for i in df_d.id:
m.addConstrs((B[i] >= B[j] for j in df_d.loc[df_d.id == i,"associati"]),name="temporal")

我收到此错误:

结果:

for i in df_d.id:
    for j in df_d.loc[df_d.id == i,"associati"]:
         print(j)

类似于:

所以问题是,当我将 j 传递给 B[j] 时,它是一个列表而不是 int,我需要遍历该列表。

解决方法

Model.addConstrs() 的想法是将生成器表达式(循环)合并到表达式中,所以我将其重写为:

m.addConstrs((B[i] >= B[j] for i in df_d.id
                           for j in df_d.loc[df_d.id == i,"associati"]),name="temporal")

如果失败,则调查您的数据框 df_d。

,

这似乎有效:

m.addConstrs((B[j] >= B[i]  for index_i,i in df_p.id.items()          
                            for j in df_p.loc[index_i,name="temporal")

Ansible 中的嵌套循环?

Ansible 中的嵌套循环?

如何解决Ansible 中的嵌套循环?

以下是仅适用于一个变量/值的剧本。我希望它能够处理多个值,这意味着在下面的 "when:..." 语句中,"val_name" 将是一个包含多个卷和嵌套循环的数组应该在卷上循环。当前剧本中已经有一个循环 我该怎么做?

  1. ---
  2. - hosts: localhost
  3. collections:
  4. - netapp.ontap
  5. name: create export-policy-rule task
  6. gather_facts: no
  7. vars_files:
  8. - variables.yml
  9. vars:
  10. vol_name: volume_name_1
  11. vserver: initialization
  12. export_policy: initialization
  13. tasks:
  14. - name: Info
  15. na_ontap_info:
  16. use_rest: Always
  17. state: info
  18. hostname: "{{ hostname }}"
  19. username: "{{ username }}"
  20. password: "{{ password }}"
  21. https: true
  22. validate_certs: false
  23. gather_subset:
  24. - volume_info
  25. register: my_ontap
  26. - set_fact:
  27. vserver: "{{ my_ontap.ontap_info.volume_info[item].volume_id_attributes.owning_vserver_name }}"
  28. export_policy: "{{ my_ontap.ontap_info.volume_info[item].volume_export_attributes.policy }}"
  29. with_items: "{{ my_ontap.ontap_info.volume_info }}"
  30. when: my_ontap.ontap_info.volume_info[item] is search ("{{ vol_name }}")
  31. - name: create the rule
  32. na_ontap_export_policy_rule:
  33. state: present
  34. policy_name: "{{ export_policy }}"
  35. vserver: "{{ vserver }}"
  36. client_match: 1.1.1.0/24,1.1.2.0/24
  37. ro_rule: sys
  38. rw_rule: sys
  39. protocol: nfs
  40. super_user_security: sys
  41. allow_suid: true
  42. hostname: "{{ hostname }}"
  43. username: "{{ username }}"
  44. password: "{{ password }}"
  45. https: true
  46. validate_certs: false
  47. - debug:
  48. msg:
  49. - "{{ vserver }}"
  50. - "{{ export_policy }}"

Difference between import numpy and import numpy as np

Difference between import numpy and import numpy as np

Difference between import numpy and import numpy as np

up vote 18 down vote favorite

5

I understand that when possible one should use

import numpy as np

This helps keep away any conflict due to namespaces. But I have noticed that while the command below works

import numpy.f2py as myf2py

the following does not

import numpy as np
np.f2py #throws no module named f2py

Can someone please explain this?

python numpy

shareimprove this question

edited Mar 24 ''14 at 23:20

mu 無

24.7k104471

asked Mar 24 ''14 at 23:19

user1318806

3001311

 
1  

@roippi have you tried exit your python and enter it and just do import numpy then numpy.f2py ? It throws an error in my case too – aha Mar 24 ''14 at 23:24

1  

Importing a module doesn''t import sub-modules. You need to explicitly import the numpy.f2py module regardless of whether or not/how numpy itself has been imported. – alecb Mar 24 ''14 at 23:39

add a comment

4 Answers

active oldest votes

 

up vote 13 down vote

numpy is the top package name, and doing import numpy doesn''t import submodule numpy.f2py.

When you do import numpy it creats a link that points to numpy, but numpy is not further linked to f2py. The link is established when you do import numpy.f2py

In your above code:

import numpy as np # np is an alias pointing to numpy, but at this point numpy is not linked to numpy.f2py
import numpy.f2py as myf2py # this command makes numpy link to numpy.f2py. myf2py is another alias pointing to numpy.f2py as well

Here is the difference between import numpy.f2py and import numpy.f2py as myf2py:

  • import numpy.f2py
    • put numpy into local symbol table(pointing to numpy), and numpy is linked to numpy.f2py
    • both numpy and numpy.f2py are accessible
  • import numpy.f2py as myf2py
    • put my2py into local symbol table(pointing to numpy.f2py)
    • Its parent numpy is not added into local symbol table. Therefore you can not access numpy directly

shareimprove this answer

edited Mar 25 ''14 at 0:31

answered Mar 24 ''14 at 23:33

aha

1,2291718

 

add a comment

 

up vote 7 down vote

The import as syntax was introduced in PEP 221 and is well documented there.

When you import a module via

import numpy

the numpy package is bound to the local variable numpy. The import as syntax simply allows you to bind the import to the local variable name of your choice (usually to avoid name collisions, shorten verbose module names, or standardize access to modules with compatible APIs).

Thus,

import numpy as np

is equivalent to,

import numpy
np = numpy
del numpy

When trying to understand this mechanism, it''s worth remembering that import numpy actually means import numpy as numpy.

When importing a submodule, you must refer to the full parent module name, since the importing mechanics happen at a higher level than the local variable scope. i.e.

import numpy as np
import numpy.f2py   # OK
import np.f2py      # ImportError

I also take issue with your assertion that "where possible one should [import numpy as np]". This is done for historical reasons, mostly because people get tired very quickly of prefixing every operation with numpy. It has never prevented a name collision for me (laziness of programmers actually suggests there''s a higher probability of causing a collision with np)

Finally, to round out my exposé, here are 2 interesting uses of the import as mechanism that you should be aware of:

1. long subimports

import scipy.ndimage.interpolation as warp
warp.affine_transform(I, ...)

2. compatible APIs

try:
    import pyfftw.interfaces.numpy_fft as fft
except:
    import numpy.fft as fft
# call fft.ifft(If) with fftw or the numpy fallback under a common name

shareimprove this answer

answered Mar 25 ''14 at 0:59

hbristow

68345

 

add a comment

 

up vote 1 down vote

numpy.f2py is actually a submodule of numpy, and therefore has to be imported separately from numpy. As aha said before:

When you do import numpy it creats a link that points to numpy, but numpy is not further linked to f2py. The link is established when you do import numpy.f2py

when you call the statement import numpy as np, you are shortening the phrase "numpy" to "np" to make your code easier to read. It also helps to avoid namespace issues. (tkinter and ttk are a good example of what can happen when you do have that issue. The UIs look extremely different.)

shareimprove this answer

answered Mar 24 ''14 at 23:47

bspymaster

760923

 

add a comment

 

up vote 1 down vote

This is a language feature. f2py is a subpackage of the module numpy and must be loaded separately.

This feature allows:

  • you to load from numpy only the packages you need, speeding up execution.
  • the developers of f2py to have namespace separation from the developers of another subpackage.

Notice however that import numpy.f2py or its variant import numpy.f2py as myf2py are still loading the parent module numpy.

Said that, when you run

import numpy as np
np.f2py

You receive an AttributeError because f2py is not an attribute of numpy, because the __init__() of the package numpy did not declare in its scope anything about the subpackage f2py.

shareimprove this answer

answered Mar 24 ''14 at 23:57

gg349

7,67321739

 
    

when you do import numpy.f2py as myf2py, how do you access its parent numpy? it seems import numpy.f2py allows you to access its parent numpy, but import numpy.f2py as myf2py doesn''t – aha Mar 25 ''14 at 0:00

    

You don''t access it because you decided you didn''t want to use anything from numpy, and you only care of using the subpackage. It is similar to using from foo import bar: the name foo will not be accessible. See the comment after the first example of the docs, LINK – gg349 Mar 25 ''14 at 0:05

add a comment

今天关于使用 NumPy 替换 Python 中的嵌套循环numpy替换元素的分享就到这里,希望大家有所收获,若想了解更多关于"import numpy as np" ImportError: No module named numpy、add.Constrs Gurobi 中的嵌套循环、Ansible 中的嵌套循环?、Difference between import numpy and import numpy as np等相关知识,可以在本站进行查询。

本文标签: