我很感激在寻找和理解pythonic方法的一些帮助,以优化嵌套for循环中的以下数组操作:
def _func(a, b, radius):
"Return 0 if a>b, otherwise return 1"
if distance.euclidean(a, b) < radius:
return 1
else:
return 0
def _make_mask(volume, roi, radius):
mask = numpy.zeros(volume.shape)
for x in range(volume.shape[0]):
for y in range(volume.shape[1]):
for z in range(volume.shape[2]):
mask[x, y, z] = _func((x, y, z), roi, radius)
return mask
Run Code Online (Sandbox Code Playgroud)
其中volume.shape
(182,218,200)和roi.shape
(3,)都是ndarray
类型; 而且radius
是一个int
我有一个raws
我想在 ipython notebook 中绘制的数组列表。这是我试图开始工作的代码:
fig, axes = subplots(len(raws),1, sharex=True, tight_layout=True, figsize=(12, 6), dpi=72)
for r in range(len(raws)):
axes[r].plot(raws)
Run Code Online (Sandbox Code Playgroud)
我已经迷失了几个小时,如果不是几天试图弄清楚如何索引列表raws
,这样我就可以在它自己的轴上绘制每个 mxn 数组,其中 n 是时间点的数量,即 x 轴和 m 是在每个点采样的时间序列函数的数量。
当我编码时:
for r in range(len(raws)):
axes[r].plot(raws[r])
Run Code Online (Sandbox Code Playgroud)
我得到一个 ValueError: setting an array element with a sequence。
供您参考:
len(raws) = 2
type(raws) = 'list'
np.shape(raws[0][0]) = (306, 10001)
raws =
[(array([[ -4.13211217e-12, -4.13287303e-12, -4.01705259e-12, ...,
1.36386023e-12, 1.65182851e-12, 2.00368966e-12],
[ 1.08914129e-12, 1.47828466e-12, 1.82257607e-12, ...,
-2.70151520e-12, -2.48631967e-12, -2.28625548e-12],
[ -7.80962369e-14, -1.27119591e-13, -1.73610315e-13, ..., …
Run Code Online (Sandbox Code Playgroud) 我正在使用pylab生成大量数据,我希望将其保存到磁盘并在脚本完成后进行检查.然而,我的特定python脚本显示生成的每一个数字,在数字运算和无数响应的数字窗口之间的某个地方打开了我的系统变得没有反应或最迟缓.有没有办法防止pylab图形窗口在脚本中弹出?提前致谢.
以下是用于生成多个数字的代码片段
...
import pylab as pl
...
# Create the figure (Letter format)
for r, f in enumerate(fif_queue):
fig, ax = pl.subplots(1, 1, figsize=(8, 5.5), dpi=72)
figname = (f[:-4] + '-RAWplot.pdf')
ax.plot(raws[r][0])
ax.axis('tight')
ax.set_xticklabels(['%.0f' % i for x, i in enumerate(np.linspace(start,stop,10))])
ax.set_xlabel('time (s)')
ax.set_ylabel('MEG data (T)')
ax.grid()
fig.savefig(figname, format='pdf')
pl.close('all')
Run Code Online (Sandbox Code Playgroud)