我最近转向Python 3.5并注意到新的矩阵乘法运算符(@)有时与numpy点运算符的行为不同.例如,对于3d数组:
import numpy as np
a = np.random.rand(8,13,13)
b = np.random.rand(8,13,13)
c = a @ b # Python 3.5+
d = np.dot(a, b)
Run Code Online (Sandbox Code Playgroud)
的@运算符返回形状的阵列:
c.shape
(8, 13, 13)
Run Code Online (Sandbox Code Playgroud)
而np.dot()函数返回:
d.shape
(8, 13, 8, 13)
Run Code Online (Sandbox Code Playgroud)
如何用numpy dot重现相同的结果?还有其他重大差异吗?
我试图使用cygwin(mingw)在Windows 10上使用Python 3.5运行一些代码.确切地说,我使用的是PyDSTool模块,我称之为dopri积分器.问题是,我distutils无法识别Microsoft Visual Studio 2015.有没有办法避免这种情况(没有回到旧版本的Python,Windows,Visual Studio).下面可以看到完整的错误.
ValueError Traceback (most recent call last)
<ipython-input-16-bfeb915bfd7b> in <module>()
60 print("\n")
61
---> 62 testODE = Dopri_ODEsystem(DSargs)
63
64 print('Integrating...')
C:\Anaconda3\lib\site-packages\PyDSTool\Generator\Dopri_ODEsystem.py in __init__(self, kw)
371 print("stages using the makeLibSource and compileLib methods.")
372 else:
--> 373 self.makeLib()
374
375 @property
C:\Anaconda3\lib\site-packages\PyDSTool\Generator\mixins.py in makeLib(self, libsources, libdirs, include)
98 self.forceLibRefresh()
99 self.makeLibSource(include)
--> 100 self.compileLib(libsources, libdirs)
101
102 @property
C:\Anaconda3\lib\site-packages\PyDSTool\Generator\mixins.py in compileLib(self, libsources, libdirs)
78 precompiled libraries."""
79
---> 80 self._builder.build(libsources, libdirs, self._compiler) …Run Code Online (Sandbox Code Playgroud) 我想在新的1D数组/列表中查找和替换多个值.
在列表的示例中
a=[2, 3, 2, 5, 4, 4, 1, 2]
Run Code Online (Sandbox Code Playgroud)
我想替换
val_old=[1, 2, 3, 4, 5]
Run Code Online (Sandbox Code Playgroud)
同
val_new=[2, 3, 4, 5, 1]
Run Code Online (Sandbox Code Playgroud)
因此新阵列是:
a_new=[3, 4, 3, 1, 5, 5, 2, 3]
Run Code Online (Sandbox Code Playgroud)
最快的方法是什么(对于非常大的列表,即50000值来查找和替换)?
评论 中 的 anwsers
感谢大家的快速回复!我用以下方法检查了建议的解决方案:
N = 10**4
N_val = 0.5*N
a = np.random.randint(0, N_val, size=N)
val_old = np.arange(N_val, dtype=np.int)
val_new = np.arange(N_val, dtype=np.int)
np.random.shuffle(val_new)
a1 = list(a)
val_old1 = list(val_old)
val_new1 = list(val_new)
def Ashwini_Chaudhary(a, val_old, val_new):
arr = np.empty(a.max()+1, dtype=val_new.dtype)
arr[val_old] = val_new
return arr[a]
def …Run Code Online (Sandbox Code Playgroud) 我不知道如何从屏幕坐标到世界坐标.我正在使用VisPy,我想在3D中实现光线跟踪和拾取能力.
我根据立方体示例准备了一些代码.下面的代码通过更改z值并在''on_mouse_press''方法中打印3D坐标来通过屏幕发送粗糙的光线.但结果不正确.如果我点击立方体的右上角,沿着光线的某个地方应该打印(3,3,3),但事实并非如此.任何人都可以帮我吗?
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vispy: gallery 50
"""
This example shows how to display 3D objects.
You should see a colored outlined spinning cube.
"""
import numpy as np
from vispy import app, gloo
from vispy.util.transforms import perspective, translate, rotate
vert = """
// Uniforms
// ------------------------------------
uniform mat4 u_model;
uniform mat4 u_view;
uniform mat4 u_projection;
uniform vec4 u_color;
// Attributes
// ------------------------------------
attribute vec3 a_position;
attribute vec4 a_color;
attribute vec3 a_normal;
// Varying …Run Code Online (Sandbox Code Playgroud) 我想替换pandas中的行值.
例如:
import pandas as pd
import numpy as np
a = np.array(([100, 100, 101, 101, 102, 102],
np.arange(6)))
pd.DataFrame(a.T)
Run Code Online (Sandbox Code Playgroud)
结果:
array([[100, 0],
[100, 1],
[101, 2],
[101, 3],
[102, 4],
[102, 5]])
Run Code Online (Sandbox Code Playgroud)
在这里,我想用值来代替行[101, 3]用[200, 10],因此其结果应该是:
array([[100, 0],
[100, 1],
[101, 2],
[200, 10],
[102, 4],
[102, 5]])
Run Code Online (Sandbox Code Playgroud)
更新
在更一般的情况下,我想替换多行.
因此,新旧行值由nx2大小的矩阵表示(n是要替换的行值的数量).例如:
old_vals = np.array(([[101, 3]],
[[100, 0]],
[[102, 5]]))
new_vals = np.array(([[200, 10]],
[[300, 20]],
[[400, 30]]))
Run Code Online (Sandbox Code Playgroud)
结果是:
array([[300, 20],
[100, 1],
[101, 2],
[200, 10], …Run Code Online (Sandbox Code Playgroud) 我需要在最小二乘意义上解决大量的线性系统.我有在理解的计算效率的差异麻烦numpy.linalg.lstsq(a, b),np.dot(np.linalg.pinv(a), b)和数学实施.
我使用以下矩阵:
h=np.random.random((50000,100))
a=h[:,:-1].copy()
b=-h[:,-1].copy()
Run Code Online (Sandbox Code Playgroud)
并且算法的结果是:
# mathematical implementation
%%timeit
np.dot(np.dot(np.linalg.inv(np.dot(a.T,a)),a.T),b)
Run Code Online (Sandbox Code Playgroud)
10个循环,最佳3:36.3 ms每个循环
# numpy.linalg.lstsq implementation
%%timeit
np.linalg.lstsq(a, b)[0]
Run Code Online (Sandbox Code Playgroud)
10个循环,最佳3:每循环103毫秒
%%timeit
np.dot(np.linalg.pinv(a), b)
Run Code Online (Sandbox Code Playgroud)
1个循环,最佳3:216 ms每个循环
为什么会有区别?
我正在尝试读取57MB的文件pandas.csv_read.该文件包含一个标题(5行),afterwads整数值和结束浮点值:
info
2681087 53329 1287215 1287215 53328
RSA 53328 53328 1287215 0
(I14) (I14) (d25.15) (d25.15)
F 1 5332
1
33
61
92
128
...
165
205
239
272
0.112474585277959E+09
0.126110931411177E+09
0.515995872032845E+09
0.126110931411175E+09
-0.194634413074014E+09
0.112474585277950E+09
...
Run Code Online (Sandbox Code Playgroud)
当我读取txt文件时:
import pandas as pd
pd.read_csv(file, skiprows=5+n_int_values, header=None, engine='c',
dtype=np.float, low_memory=False)
Run Code Online (Sandbox Code Playgroud)
结果是错误:
---------------------------------------------------------------------------
CParserError Traceback (most recent call last)
<ipython-input-118-699921ac7a12> in <module>()
----> 1 a=pd.read_csv(loc, skiprows=5+n_coloums+n_rows, header=None, engine='c', low_memory=False, error_bad_lines=False)
C:\Anaconda\lib\site-packages\pandas\io\parsers.pyc in parser_f(filepath_or_buffer, sep, dialect, compression, doublequote, escapechar, quotechar, quoting, skipinitialspace, lineterminator, …Run Code Online (Sandbox Code Playgroud) 我需要一个很好的解释(参考)来解释(for)循环中的NumPy切片.我有三个案子.
def example1(array):
for row in array:
row = row + 1
return array
def example2(array):
for row in array:
row += 1
return array
def example3(array):
for row in array:
row[:] = row + 1
return array
Run Code Online (Sandbox Code Playgroud)
一个简单的案例:
ex1 = np.arange(9).reshape(3, 3)
ex2 = ex1.copy()
ex3 = ex1.copy()
Run Code Online (Sandbox Code Playgroud)
收益:
>>> example1(ex1)
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
>>> example2(ex2)
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
>>> example3(ex3)
array([[1, 2, 3],
[4, 5, 6], …Run Code Online (Sandbox Code Playgroud) 我想在一个NumPy数组中插入多个行和列.
如果我有一个长方形数组n_a,例如:n_a = 3
a = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
Run Code Online (Sandbox Code Playgroud)
我想得到一个大小的新数组n_b,其中包含数组a和zeros(或任何其他1D长度数组n_b)在某些行和列上的索引,例如
index = [1, 3]
Run Code Online (Sandbox Code Playgroud)
所以n_b = n_a + len(index).然后新的数组是:
b = np.array([[1, 0, 2, 0, 3],
[0, 0, 0, 0, 0],
[4, 0, 5, 0, 6],
[0, 0, 0, 0, 0],
[7, 0, 8, 0, 9]])
Run Code Online (Sandbox Code Playgroud)
我的问题是,如何有效地做到这一点,假设更大的数组n_a远大于len(index).
编辑
结果:
import numpy as np …Run Code Online (Sandbox Code Playgroud) 我有一个 python 脚本,它应该并行运行多个作业。我将最大进程设置为 20,但我需要脚本在发送作业之间休眠 5 秒。这是我的示例代码:
#!/usr/bin/env python
import multiprocessing
import subprocess
def prcss(cmd):
sbc = subprocess.call
com = sbc(cmd, shell='True')
return (com)
if __name__=='__main__':
s = 'sleep 5'
cmd= []
for j in range(1,21):
for i in range(10):
sis = "nohup ~/mycodes/code > str(j)"+"/"+"out"+str(i)+".dat"
cmd.append(sis)
cmd.append(s)
pool=multiprocessing.Pool(processes=20)
pool.map(prcss,cmd)
Run Code Online (Sandbox Code Playgroud)
尽管我在“sis”命令之间有睡眠 5 个时间,但当我运行脚本时,所有作业都会立即启动。我需要在“sis”命令之间休息一下,因为每个作业的输出取决于计算机时钟。因此,如果我运行 20 个作业,它们都以相同的系统时钟启动,因此它们都将具有相同的输出。
知道如何让我的脚本在“sis”命令之间休眠吗?
阿贝丁