如果您对Pythonnumpy模块-deg2rad()实例源码和python中numpy模块感兴趣,那么这篇文章一定是您不可错过的。我们将详细讲解Pythonnumpy模块-deg2rad()实例源码
如果您对Python numpy 模块-deg2rad() 实例源码和python中numpy模块感兴趣,那么这篇文章一定是您不可错过的。我们将详细讲解Python numpy 模块-deg2rad() 实例源码的各种细节,并对python中numpy模块进行深入的分析,此外还有关于Jupyter 中的 Numpy 在打印时出错(Python 版本 3.8.8):TypeError: 'numpy.ndarray' object is not callable、numpy.random.random & numpy.ndarray.astype & numpy.arange、numpy.ravel()/numpy.flatten()/numpy.squeeze()、Numpy:数组创建 numpy.arrray() , numpy.arange()、np.linspace ()、数组基本属性的实用技巧。
本文目录一览:- Python numpy 模块-deg2rad() 实例源码(python中numpy模块)
- Jupyter 中的 Numpy 在打印时出错(Python 版本 3.8.8):TypeError: 'numpy.ndarray' object is not callable
- numpy.random.random & numpy.ndarray.astype & numpy.arange
- numpy.ravel()/numpy.flatten()/numpy.squeeze()
- Numpy:数组创建 numpy.arrray() , numpy.arange()、np.linspace ()、数组基本属性
Python numpy 模块-deg2rad() 实例源码(python中numpy模块)
Python numpy 模块,deg2rad() 实例源码
我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用numpy.deg2rad()。
- def augment(
- rotation_fn=lambda: np.random.random_integers(0, 360),
- translation_fn=lambda: (np.random.random_integers(-20, 20), np.random.random_integers(-20, 20)),
- scale_factor_fn=random_zoom_range(),
- shear_fn=lambda: np.random.random_integers(-10, 10)
- ):
- def call(x):
- rotation = rotation_fn()
- translation = translation_fn()
- scale = scale_factor_fn()
- shear = shear_fn()
- tf_augment = AffineTransform(scale=scale, rotation=np.deg2rad(rotation), translation=translation, shear=np.deg2rad(shear))
- tf = tf_center + tf_augment + tf_uncenter
- x = warp(x, tf, order=1, preserve_range=True, mode=''symmetric'')
- return x
- return call
- def affine_skew(self, tilt, phi, img, mask=None):
- h, w = img.shape[:2]
- if mask is None:
- mask = np.zeros((h, w), np.uint8)
- mask[:] = 255
- A = np.float32([[1, 0, 0], [0, 1, 0]])
- if phi != 0.0:
- phi = np.deg2rad(phi)
- s, c = np.sin(phi), np.cos(phi)
- A = np.float32([[c, -s], [s, c]])
- corners = [[0, [w, h], h]]
- tcorners = np.int32(np.dot(corners, A.T))
- x, y, w, h = cv2.boundingRect(tcorners.reshape(1, -1, 2))
- A = np.hstack([A, [[-x], [-y]]])
- img = cv2.warpAffine(img, A, (w, h), flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_REPLICATE)
- if tilt != 1.0:
- s = 0.8*np.sqrt(tilt * tilt - 1)
- img = cv2.GaussianBlur(img, (0, 0), sigmaX=s, sigmaY=0.01)
- img = cv2.resize(img, fx=1.0 / tilt, fy=1.0, interpolation=cv2.INTER_NEAREST)
- A[0] /= tilt
- if phi != 0.0 or tilt != 1.0:
- h, w = img.shape[:2]
- mask = cv2.warpAffine(mask, flags=cv2.INTER_NEAREST)
- Ai = cv2.invertAffineTransform(A)
- return img, mask, Ai
- def mass_streamfun(self):
- from scipy import integrate
- data = self._obj
- # lonlen = len(data.lon)
- if ''lon'' in data.dims:
- data = data.fillna(0).mean(''lon'')
- levax = data.get_axis_num(''lev'')
- stream = integrate.cumtrapz(data * np.cos(np.deg2rad(data.lat)), x=data.lev * 1e2, initial=0., axis=levax)
- stream = stream * 2 * np.pi / cc.g * cc.rearth * 1e-9
- stream = xr.DataArray(stream, coords=data.coords, dims=data.dims)
- stream = stream.rename(''ovt'')
- stream.attrs[''long name''] = ''atmosphere overturning circulation''
- stream.attrs[''unit''] = ''Sv (1e9 kg/s)''
- return stream
- def draw_laser_frustum(pose, zmin=0.0, zmax=10, fov=np.deg2rad(60)):
- N = 30
- curve = np.vstack([(
- RigidTransform.from_rpyxyz(0, rad, 0) * np.array([[zmax, 0]]))
- for rad in np.linspace(-fov/2, fov/2, N)])
- curve_w = pose * curve
- faces, edges = [], []
- for cpt1, cpt2 in zip(curve_w[:-1], curve_w[1:]):
- faces.extend([pose.translation, cpt1, cpt2])
- edges.extend([cpt1, cpt2])
- # Connect the last pt in the curve w/ the current pose,
- # then connect the the first pt in the curve w/ the curr. pose
- edges.extend([edges[-1], pose.translation])
- edges.extend([edges[0], pose.translation])
- faces = np.vstack(faces)
- edges = np.vstack(edges)
- return (faces, edges)
- def __init__(self, theta=np.deg2rad(20), displacement=0.25, lookup_history=10,
- get_sample=lambda item: item.pose,
- on_sampled_cb=lambda index, item: None, verbose=False):
- PoseSampler.__init__(self, displacement=displacement, theta=theta,
- lookup_history=lookup_history,
- get_sample=get_sample,
- on_sampled_cb=on_sampled_cb, verbose=verbose)
- # class KeyframeVolumeSampler(FrustumVolumeIntersectionPoseSampler):
- # def __init__(self,IoU=0.5,depth=20,fov=np.deg2rad(60),lookup_history=10,
- # get_sample=lambda item: item.pose,
- # on_sampled_cb=lambda index,item: None,verbose=False):
- # FrustumVolumeIntersectionPoseSampler.__init__(self,IoU=IoU,depth=depth,fov=fov,
- # lookup_history=lookup_history,
- # get_sample=get_sample,
- # on_sampled_cb=on_sampled_cb,verbose=verbose)
- def tsukuba_load_poses(fn):
- """
- Retrieve poses
- X Y Z R P Y - > X -Y -Z R -P -Y
- np.deg2rad(p[3]),-np.deg2rad(p[4]),-np.deg2rad(p[5]),
- p[0]*.01,-p[1]*.01,-p[2]*.01,axes=''sxyz'') for p in P ]
- """
- P = np.loadtxt(os.path.expanduser(fn), dtype=np.float64, delimiter='','')
- return [ RigidTransform.from_rpyxyz(np.pi, 0) * \\
- RigidTransform.from_rpyxyz(
- np.deg2rad(p[3]),np.deg2rad(p[4]),np.deg2rad(p[5]),
- p[0]*.01,p[1]*.01,p[2]*.01, axes=''sxyz'') * \\
- RigidTransform.from_rpyxyz(np.pi, 0) for p in P ]
- # return [ RigidTransform.from_rpyxyz(
- # np.deg2rad(p[3]),
- # p[0]*.01,axes=''sxyz'') for p in P ]
- def ct2lg(dX, dY, dZ, lat, lon):
- n = dX.size
- R = np.zeros((3, 3, n))
- R[0, :] = -np.multiply(np.sin(np.deg2rad(lat)), np.cos(np.deg2rad(lon)))
- R[0, np.sin(np.deg2rad(lon)))
- R[0, 2, :] = np.cos(np.deg2rad(lat))
- R[1, :] = -np.sin(np.deg2rad(lon))
- R[1, :] = np.cos(np.deg2rad(lon))
- R[1, :] = np.zeros((1, n))
- R[2, :] = np.multiply(np.cos(np.deg2rad(lat)), np.cos(np.deg2rad(lon)))
- R[2, np.sin(np.deg2rad(lon)))
- R[2, :] = np.sin(np.deg2rad(lat))
- dxdydz = np.column_stack((np.column_stack((dX, dY)), dZ))
- RR = np.reshape(R[0, :, :], (3, n))
- dx = np.sum(np.multiply(RR, dxdydz.transpose()), axis=0)
- RR = np.reshape(R[1, n))
- dy = np.sum(np.multiply(RR, axis=0)
- RR = np.reshape(R[2, n))
- dz = np.sum(np.multiply(RR, axis=0)
- return dx, dy, dz
- def ct2lg(self, dX, lon):
- n = dX.size
- R = numpy.zeros((3, n))
- R[0, :] = -numpy.multiply(numpy.sin(numpy.deg2rad(lat)), numpy.cos(numpy.deg2rad(lon)))
- R[0, numpy.sin(numpy.deg2rad(lon)))
- R[0, :] = numpy.cos(numpy.deg2rad(lat))
- R[1, :] = -numpy.sin(numpy.deg2rad(lon))
- R[1, :] = numpy.cos(numpy.deg2rad(lon))
- R[1, :] = numpy.zeros((1, n))
- R[2, :] = numpy.multiply(numpy.cos(numpy.deg2rad(lat)), numpy.cos(numpy.deg2rad(lon)))
- R[2, numpy.sin(numpy.deg2rad(lon)))
- R[2, :] = numpy.sin(numpy.deg2rad(lat))
- dxdydz = numpy.column_stack((numpy.column_stack((dX, dZ))
- RR = numpy.reshape(R[0, n))
- dx = numpy.sum(numpy.multiply(RR, axis=0)
- RR = numpy.reshape(R[1, n))
- dy = numpy.sum(numpy.multiply(RR, axis=0)
- RR = numpy.reshape(R[2, n))
- dz = numpy.sum(numpy.multiply(RR, axis=0)
- return dx, dz
- def ct2lg(dX, dz
- def ct2lg(self, dz
- def ct2lg(self, dz
- def augment_deterministic(
- rotation=0,
- translation=0,
- scale_factor=1,
- shear=0
- ):
- def call(x):
- scale = scale_factor, scale_factor
- rotation_tmp = rotation
- tf_augment = AffineTransform(
- scale=scale,
- rotation=np.deg2rad(rotation_tmp),
- translation=translation,
- shear=np.deg2rad(shear)
- )
- tf = tf_center + tf_augment + tf_uncenter
- x = warp(x, mode=''symmetric'')
- return x
- return call
- def effect(self, point):
- res = []
- # print(self.centers)
- for center in self.centers:
- center_x, center_y = center
- src_x, src_y = point.pos
- # Check angle
- angle = np.arctan((center_x - src_x) / (center_y - src_y))
- if np.abs(angle) > self.angle / 2:
- continue
- angle = np.deg2rad(90) + angle
- u_len = np.sqrt((center_x - src_x) ** 2 + (center_y - src_y) ** 2)
- reverse_v = (self.r_index - 1) / self.radius - self.r_index / u_len
- v_len = 1 / reverse_v
- if v_len > 0:
- p_type = ''real''
- else:
- p_type = ''fake''
- target = line_end(point.pos, angle, u_len + v_len)
- p = Point(target, p_type, 1)
- # point.passed.append(self)
- res.append(p)
- return tuple(res)
- def setRotation(self, rot, smallangle=True):
- ''''''
- Rotation angle in degrees
- ''''''
- rad = np.deg2rad(rot)
- if smallangle:
- # bring rad close to zero.
- rad = np.fmod(rad, 2.*pi)
- if rad > pi:
- rad -= 2.*pi
- if rad < -pi:
- rad += 2.*pi
- self.T = [ 0., -rad, 0. ]
- else:
- cr = np.cos(rad)
- sr = np.sin(rad)
- self.T = [ cr - 1, -sr, sr, cr - 1 ]
- def plot(self, values, *args, **kw):
- """Plot a concept''s cause-effect repertoire on the radarchart.
- Examples:
- >>> full_rep = np.hstack([cause_rep,effect_rep])
- >>> radar.plot(full_rep,''-'',lw=2,label=mechanism_label)
- Args:
- values (np.ndarray): A flat array of state probabilitites,given in
- the same order as the `titles` argument to the ConstellationRadar
- constructor.
- Also takes standard matplotlib linespec arguments,such as color,style,
- linewidth,etc.
- """
- angle = np.deg2rad(np.r_[self.angles, self.angles[0]])
- values = np.r_[values, values[0]]
- self.ax.plot(angle, **kw)
- def _rotate_interp(array, alpha, center, mode=''constant'', cval=0):
- ''''''
- Rotation around a provided center
- This is the only way to be sure where exactly is the center of rotation.
- ''''''
- dtype = array.dtype
- dims = array.shape
- alpha_rad = -np.deg2rad(alpha)
- x, y = np.meshgrid(np.arange(dims[1], dtype=dtype), np.arange(dims[0], dtype=dtype))
- xp = (x-center[0])*np.cos(alpha_rad) + (y-center[1])*np.sin(alpha_rad) + center[0]
- yp = -(x-center[0])*np.sin(alpha_rad) + (y-center[1])*np.cos(alpha_rad) + center[1]
- rotated = ndimage.map_coordinates(img, [yp, xp], mode=mode, cval=cval, order=3)
- return rotated
- def calc_coord(self, transCoord, p, d, a, e, i, w):
- # cx,cy,cz ?? ??
- # p,?? d,?? ??
- # a ??,e ???
- # i ?? ???
- unitAng = 360/p
- ang = (unitAng * d) % 360
- theta = np.deg2rad(ang)
- b = a * np.sqrt(1 - np.power(e, 2))
- x = transCoord[0] + a * np.cos(theta)
- y = transCoord[1] + b * np.sin(theta)
- z = 0.0
- #rotate
- w = np.deg2rad(w)
- x1, y1 = x, y
- #x = transCoord[0] + (x1 * np.cos(w) - y1 * np.sin(w))
- #y = transCoord[1] + (x1 * np.sin(w) + y1 * np.cos(w))
- coord = [x, z]
- return coord
- def mt_diff( mt1, mt2):
- fps = np.deg2rad([mt1.get_fps(), mt2.get_fps()])
- diff = [999999999, 999999999]
- for i in range(2):
- for j in range(2):
- test = haversine(lon1=fps[0][i][0], phi1=fps[0][i][1], lon2=fps[1][j][0], phi2=fps[1][j][1], radius=1.)
- while test>np.pi/2:
- test -= np.pi/2
- if test < diff[i]:
- diff[i] = test
- return np.rad2deg(np.mean(diff))
- def __init__(self, f0=997, fs=96000, duration=None, gaindb=0, nofsamples=0,
- phasedeg=0, harmonics=7,):
- """Construct a square wave by adding odd harmonics with decreasing
- amplitude,i.e. Fourier Series.
- """
- Sinetone.__init__(self, f0=f0, phasedeg=phasedeg, fs=fs, nofsamples=nofsamples,
- duration=duration, gaindb=0)
- assert harmonics >= 0
- self.harmonics = harmonics
- self._logger.debug("fundamental f0: %.1f" %f0)
- for n in range(3, 2*(self.harmonics+1), 2):
- if n <= 15:
- self._logger.debug("adding harmonic n: %2i with amplitude 1/%i" %(n, n))
- if n == 17:
- self._logger.debug("adding %i more harmonics..." %(self.harmonics-(n-3)//2))
- #self.samples[:,0] += np.sin(2*np.pi*(n*f0)*self.get_time()+np.deg2rad(phasedeg*n))/n
- self.samples[:,0] += (1/n)*self._sine_gen(n*f0, n*phasedeg)
- self.gain(gaindb)
- def construct_K(image_size, focal_len=None, fov_degrees=None, fov_radians=None):
- """ create calibration matrix K using the image size and focal length or field of view angle
- Assumes 0 skew and principal point at center of image
- Note that image_size = (width,height)
- Note that fov is assumed to be measured horizontally
- """
- if not np.sum([focal_len is not None, fov_degrees is not None, fov_radians is not None]) == 1:
- raise Exception(''Specify exactly one of [focal_len,fov_degrees,fov_radians]'')
- if fov_degrees is not None:
- fov_radians = np.deg2rad(fov_degrees)
- if fov_radians is not None:
- focal_len = image_size[0] / (2.0 * np.tan(fov_radians/2.0))
- K = np.array([[focal_len, image_size[0]/2.0], focal_len, image_size[1]/2.0], 1]])
- return K
- def gaussian(height, center_x, center_y, width_x, width_y, rotation):
- """Returns a gaussian function with the given parameters"""
- width_x = float(width_x)
- width_y = float(width_y)
- rotation = np.deg2rad(rotation)
- center_x = center_x * np.cos(rotation) - center_y * np.sin(rotation)
- center_y = center_x * np.sin(rotation) + center_y * np.cos(rotation)
- def rotgauss(x,y):
- xp = x * np.cos(rotation) - y * np.sin(rotation)
- yp = x * np.sin(rotation) + y * np.cos(rotation)
- g = height*np.exp(
- -(((center_x-xp)/width_x)**2+
- ((center_y-yp)/width_y)**2)/2.)
- return g
- return rotgauss
- def _add_table(self, name):
- p = PoseStamped()
- p.header.frame_id = self._robot.get_planning_frame()
- p.header.stamp = rospy.Time.Now()
- p.pose.position.x = 0.2
- p.pose.position.y = 0.0
- p.pose.position.z = 0.1
- q = quaternion_from_euler(0.0, 0.0, numpy.deg2rad(90.0))
- p.pose.orientation = Quaternion(*q)
- # Table size from ~/.gazebo/models/table/model.sdf,using the values
- # for the surface link.
- self._scene.add_Box(name, (0.005, 0.005, 0.005))
- return p.pose
- def traj_diff(t1, t2):
- """Compute trajectory difference.
- Parameters
- ----------
- t1,t2 : DataFrame
- Trajectories.
- Returns
- -------
- diff : DataFrame
- Trajectory difference. It can be interpreted as errors in `t1` relative
- to `t2`.
- """
- diff = t1 - t2
- diff[''lat''] *= np.deg2rad(earth.R0)
- diff[''lon''] *= np.deg2rad(earth.R0) * np.cos(0.5 *
- np.deg2rad(t1.lat + t2.lat))
- diff[''h''] %= 360
- diff.h[diff.h < -180] += 360
- diff.h[diff.h > 180] -= 360
- return diff.loc[t1.index.intersection(t2.index)]
- def reset(self):
- """Clear computed trajectory except the initial point."""
- lat, lon, VE, VN, h, r, stamp = self._init_values
- self.lat_arr[0] = np.deg2rad(lat)
- self.lon_arr[0] = np.deg2rad(lon)
- self.VE_arr[0] = VE
- self.VN_arr[0] = VN
- self.Cnb_arr[0] = dcm.from_hpr(h, r)
- self.traj = pd.DataFrame(index=pd.Index([stamp], name=''stamp''))
- self.traj[''lat''] = [lat]
- self.traj[''lon''] = [lon]
- self.traj[''VE''] = [VE]
- self.traj[''VN''] = [VN]
- self.traj[''h''] = [h]
- self.traj[''p''] = [p]
- self.traj[''r''] = [r]
- def equinox(date, eop_correction=True, terms=106, kinematic=True):
- """Equinox equation in degrees
- """
- epsilon_bar, delta_psi, delta_eps = _nutation(date, eop_correction, terms)
- equin = delta_psi * 3600. * np.cos(np.deg2rad(epsilon_bar))
- if date.d >= 50506 and kinematic:
- # Starting 1992-02-27,we apply the effect of the moon
- ttt = date.change_scale(''TT'').julian_century
- om_m = 125.04455501 - (5 * 360. + 134.1361851) * ttt\\
- + 0.0020756 * ttt ** 2 + 2.139e-6 * ttt ** 3
- equin += 0.00264 * np.sin(np.deg2rad(om_m)) + 6.3e-5 * np.sin(np.deg2rad(2 * om_m))
- # print("esquinox = {}\\n".format(equin / 3600))
- return equin / 3600.
- def test_read():
- tle = Tle(ref)
- assert tle.name == "ISS (ZARYA)"
- assert tle.norad_id == 25544
- assert tle.cospar_id == "1998-067A"
- assert tle.epoch == Date(2008, 9, 20, 12, 25, 40, 104192)
- assert tle.ndot == -2.182e-5
- assert tle.ndotdot == 0.
- assert tle.bstar == -0.11606e-4
- assert tle.i == np.deg2rad(51.6416)
- assert tle.? == np.deg2rad(247.4627)
- assert tle.e == 6.703e-4
- assert tle.? == np.deg2rad(130.5360)
- assert tle.M == np.deg2rad(325.0288)
- assert tle.n == 15.72125391 * 2 * np.pi / 86400.
- tle = Tle(ref.splitlines()[1:])
- assert tle.name == ""
- with raises(ValueError):
- ref2 = ref[:-1] + "8"
- Tle(ref2)
- def gaussian(height,y):
- xp = x * np.cos(rotation) - y * np.sin(rotation)
- yp = x * np.sin(rotation) + y * np.cos(rotation)
- g = height*np.exp(
- -(((center_x-xp)/width_x)**2+
- ((center_y-yp)/width_y)**2)/2.)
- return g
- return rotgauss
- def gaussian_pdf(height, rotation):
- """Returns a pdf function with the given parameters"""
- width_x = float(width_x)
- width_y = float(width_y)
- rotation = np.deg2rad(rotation)
- center_x = center_x * np.cos(rotation) - center_y * np.sin(rotation)
- center_y = center_x * np.sin(rotation) + center_y * np.cos(rotation)
- def rotgauss(x,y):
- xp = x * np.cos(rotation) - y * np.sin(rotation)
- yp = x * np.sin(rotation) + y * np.cos(rotation)
- g = height*np.exp(
- -(((center_x-xp)/width_x)**2+
- ((center_y-yp)/width_y)**2)/2.)
- return g
- return rotgauss
- # doesn''t allow for flattening or mean shifting,otherwise occasionally
- # we get gaussians that are in the wrong place or drastically the wrong shape
- def get_area_extent(self, size, offsets, factors, platform_height):
- """Get the area extent of the file."""
- nlines, ncols = size
- h = platform_height
- # count starts at 1
- cols = 1 - 0.5
- lines = 1 - 0.5
- ll_x, ll_y = self.get_xy_from_linecol(lines, cols, factors)
- cols += ncols
- lines += nlines
- ur_x, ur_y = self.get_xy_from_linecol(lines, factors)
- return (np.deg2rad(ll_x) * h, np.deg2rad(ll_y) * h,
- np.deg2rad(ur_x) * h, np.deg2rad(ur_y) * h)
- def test_get_geostationary_angle_extent(self):
- """Get max geostationary angles."""
- geos_area = mock.Magicmock()
- geos_area.proj_dict = {''a'': 6378169.00,
- ''b'': 6356583.80,
- ''h'': 35785831.00}
- expected = (0.15185342867090912, 0.15133555510297725)
- np.testing.assert_allclose(expected,
- hf.get_geostationary_angle_extent(geos_area))
- geos_area.proj_dict = {''a'': 1000.0,
- ''b'': 1000.0,
- ''h'': np.sqrt(2) * 1000.0 - 1000.0}
- expected = (np.deg2rad(45), np.deg2rad(45))
- np.testing.assert_allclose(expected,
- hf.get_geostationary_angle_extent(geos_area))
- def augmentate(self):
- angles = [45, 90, 135, 180, 225, 270, 315]
- scale = 1.0
- for img in self.images:
- print "image shape : ", img.shape
- w = img.shape[1]
- h = img.shape[0]
- img_vmirror = cv2.flip(img,1)
- skimage.io.imsave("testv"+".jpg", img_vmirror )
- for angle in angles:
- #rangle = np.deg2rad(angle)
- # nw = (abs(np.sin(rangle)*h) + abs(np.cos(rangle)*w))*scale
- # nh = (abs(np.cos(rangle)*h) + abs(np.sin(rangle)*w))*scale
- rot_mat = cv2.getRotationMatrix2D((w*0.5, h*0.5), scale)
- # rot_move = np.dot(rot_mat,np.array([(nw-w)*0.5,(nh-h)*0.5,0]))
- # rot_mat[0,2] += rot_move[0]
- # rot_mat[1,2] += rot_move[1]
- new_img = cv2.warpAffine(img, rot_mat, (int(math.ceil(w)), int(math.ceil(h))), flags=cv2.INTER_lanczos4)
- skimage.io.imsave("test"+str(angle)+".jpg", new_img)
- new_img_vmirror = cv2.flip(new_img, 1)
- skimage.io.imsave("testv"+str(angle)+".jpg", new_img_vmirror)
- # img_rmirror = cv2.flip(new_img,0)
- # skimage.io.imsave("testh"+str(angle)+".jpg",img_rmirror)
- def sphericalToXYZ(lat,lon,radius=1):
- ''''''
- Convert spherical coordinates to x,y,z
- @param lat: Latitude,scalar or array
- @param lon: Longitude,scalar or array
- @param radius: Sphere''s radius
- @return Numpy array of x,z coordinates
- ''''''
- phi = np.deg2rad(90.0 - lat)
- theta = np.deg2rad(lon % 360)
- x = radius * np.cos(theta)*np.sin(phi)
- y = radius * np.sin(theta)*np.sin(phi)
- z = radius * np.cos(phi)
- if np.isscalar(x) == False:
- return np.vstack([x,y,z]).T
- else:
- return np.array([x,z])
- def plot_chara(self, step,Rstar = 1):
- counter = 1000
- i = np.arange(counter)
- Rstar_tmp = self.Rstar_min + i / counter
- Rstar_tmp = Rstar_tmp[Rstar_tmp < 1]
- fai = self.chara_line(Rstar_tmp)
- for j in range(0, step):
- x1 = self.chara_x(Rstar_tmp * Rstar, fai - self.const + np.deg2rad(j))
- y1 = self.chara_y(Rstar_tmp * Rstar, fai - self.const + np.deg2rad(j))
- x2 = self.chara_x(Rstar_tmp * Rstar, - (fai - self.const - np.deg2rad(j)))
- y2 = self.chara_y(Rstar_tmp * Rstar, - (fai - self.const - np.deg2rad(j)))
- plt.plot(x1, y1, "r")
- plt.plot(x2, y2, "k")
- plt.xlim(-1, 1)
- plt.ylim(-1, 1)
- plt.gca().set_aspect(''equal'', adjustable=''Box'')
- plt.show()
- # top arc angle is 0
- # v1 must be smaller than v2
- def make_upper_straight_line(self):
- """ make upper straight line """
- targetx = self.lower_concave_in_x_end
- x = self.upper_convex_in_x_end
- y = self.upper_convex_in_y_end
- targety = np.tan(np.deg2rad(self.beta_in)) * targetx + y - np.tan(np.deg2rad(self.beta_in)) * x
- self.upper_straight_in_x = [targetx, x]
- self.upper_straight_in_y = [targety, y]
- self.shift = - abs(self.lower_concave_in_y_end - targety)
- targetx = self.lower_concave_out_x_end
- x = self.upper_convex_out_x_end
- y = self.upper_convex_out_y_end
- targety = np.tan(np.deg2rad(self.beta_out)) * targetx + y - np.tan(np.deg2rad(self.beta_out)) * x
- self.upper_straight_out_x = [targetx, x]
- self.upper_straight_out_y = [targety, y]
- def distort_affine_skimage(image, rotation=10.0, shear=5.0, random_state=None):
- if random_state is None:
- random_state = np.random.RandomState(None)
- rot = np.deg2rad(np.random.uniform(-rotation, rotation))
- sheer = np.deg2rad(np.random.uniform(-shear, shear))
- shape = image.shape
- shape_size = shape[:2]
- center = np.float32(shape_size) / 2. - 0.5
- pre = transform.SimilarityTransform(translation=-center)
- affine = transform.AffineTransform(rotation=rot, shear=sheer, translation=center)
- tform = pre + affine
- distorted_image = transform.warp(image, tform.params, mode=''reflect'')
- return distorted_image.astype(np.float32)
- def __init__(self, fig, variables, ranges, n_ordinate_levels=6):
- angles = np.arange(0, 360, 360./len(variables))
- axes = [fig.add_axes([0,0,1],polar=True,
- label = "axes{}".format(i))
- for i in range(len(variables))]
- l, text = axes[0].set_thetagrids(angles, labels = variables)
- [txt.set_rotation(angle-90) for txt, angle in zip(text, angles)]
- for ax in axes[1:]:
- ax.patch.set_visible(False)
- ax.grid("off")
- ax.xaxis.set_visible(False)
- for i, ax in enumerate(axes):
- grid = np.linspace(*ranges[i], num=n_ordinate_levels)
- gridlabel = ["{}".format(round(x,2)) for x in grid]
- if ranges[i][0] > ranges[i][1]:
- grid = grid[::-1] # hack to invert grid
- # gridlabels aren''t reversed
- gridlabel[0] = "" # clean up origin
- ax.set_rgrids(grid, labels=gridlabel, angle=angles[i])
- ax.set_ylim(*ranges[i])
- # variables for plotting
- self.angle = np.deg2rad(np.r_[angles, angles[0]])
- self.ranges = ranges
- self.ax = axes[0]
- def generate_circle_points(radius, initial_angle, final_angle, points=199):
- """
- This methods generates points in a circle shape at (0,0) with a specific radius and from a
- starting angle to a final angle.
- Args:
- radius: radius of the circle in microns
- initial_angle: initial angle of the drawing in degrees
- final_angle: final angle of the drawing in degrees
- points: amount of points to be generated (default 199)
- Returns:
- Set of points that form the circle
- """
- theta = np.linspace( np.deg2rad(initial_angle),
- np.deg2rad(final_angle),
- points)
- return radius * np.cos(theta) , radius * np.sin(theta)
- def disttoedge(self, x, d):
- rd = numpy.deg2rad(d)
- dx, dy = numpy.cos(rd), numpy.sin(rd)
- maxx = self.width()
- maxy = self.height()
- if dx == 0:
- lefthit, righthit = sys.maxsize, sys.maxsize
- tophit, bothit = (maxy - y) / dy, (-y) / dy
- elif dy == 0:
- lefthit, righthit = (-x) / dx, (maxx - x) / dx
- tophit, bothit = sys.maxsize, sys.maxsize
- else:
- lefthit, (-y) / dy
- # Return smallest positive
- dists = list(filter(lambda s: s > 0, [lefthit, righthit, tophit, bothit]))
- if len(dists) == 0:
- return 0
- else:
- return min(dists)
- def rotation_matrix_axis(C_values):
- # Change coordinate system through matrix C
- rx = np.deg2rad(float(C_values[0]))
- ry = np.deg2rad(float(C_values[1]))
- rz = np.deg2rad(float(C_values[2]))
- Cx = np.matrix([[1,
- [0, np.cos(rx), np.sin(rx)], -np.sin(rx), np.cos(rx)]])
- Cy = np.matrix([[np.cos(ry), -np.sin(ry)],
- [np.sin(ry), np.cos(ry)]])
- Cz = np.matrix([[np.cos(rz), np.sin(rz),
- [-np.sin(rz), np.cos(rz), 1]])
- C = Cx * Cy * Cz
- Cinv = np.linalg.inv(C)
- return C, Cinv
- def rotation_matrix(bone, tx, ty, tz):
- # Construct rotation matrix M
- tx = np.deg2rad(tx)
- ty = np.deg2rad(ty)
- tz = np.deg2rad(tz)
- Mx = np.matrix([[1, np.cos(tx), np.sin(tx)], -np.sin(tx), np.cos(tx)]])
- My = np.matrix([[np.cos(ty), -np.sin(ty)],
- [np.sin(ty), np.cos(ty)]])
- Mz = np.matrix([[np.cos(tz), np.sin(tz),
- [-np.sin(tz), np.cos(tz), 1]])
- M = Mx * My * Mz
- L = bone.Cinv * M * bone.C
- return L
- def keyframedb(self, verbose=True):
- sampler = PoseSampler(theta=theta, lookup_history=lookup_history,
- get_sample=lambda (t, channel, frame): frame.pose, verbose=verbose)
- self.iterframes = partial(sampler.iteritems, self.iterframes())
- return self
- # def list_annotations(self,target_name=None):
- # " List of lists"
- # inds = self.annotated_inds
- # return [ filter(lambda frame:
- # target_name is None or name is in target_name,
- # self.dataset.annotationdb.iterframes(inds))
- # def _build_graph(self):
- # # Keep a queue of finite length to ensure
- # # time-sync with RGB and IMU
- # self.__pose_q = deque(maxlen=10)
- # self.nodes_ = []
- # for (t,ch,data) in self.dataset_.itercursors(topics=[]):
- # if ch == TANGO_VIO_CHANNEL:
- # self.__pose_q.append(data)
- # continue
- # if not len(self.__pose_q):
- # continue
- # assert(ch == TANGO_RGB_CHANNEL)
- # self.nodes_.append(dict(img=data,pose=self.__pose_q[-1]))
- # Basic type for tango frame (includes pose,image,timestamp)
- def draw_camera(pose, zmax=0.1, fov=np.deg2rad(60)):
- frustum = Frustum(pose, zmin=zmin, zmax=zmax, fov=fov)
- nul, nll, nlr, nur, ful, fll, flr, fur = frustum.vertices
- # nll,nlr,nur,nul,fll,flr,fur,ful = frustum.vertices
- faces = []
- # Triangles: Front Face
- faces.extend([ful, fur, flr])
- faces.extend([flr, fll])
- # Triangles: Back Face
- faces.extend([nul, nlr])
- faces.extend([nlr, nul, nll])
- # Triangles: Four walls (2-triangles per face)
- left, top, right, bottom = [fll, nul], \\
- [ful, nur], \\
- [fur, nlr], \\
- [flr, nll]
- faces.extend([left, bottom]) # left,top,right,bottom wall
- faces = np.vstack(faces)
- # Lines: zmin-zmax
- pts = []
- pts.extend([ful, ful])
- pts.extend([ful, ful])
- pts.extend([fur, fur])
- pts.extend([flr, flr])
- pts = np.vstack(pts)
- return (faces, np.hstack([pts[:-1], pts[1:]]).reshape((-1,3)))
- def __init__(self, pose, fov=np.deg2rad(60)):
- # FoV derived from fx,fy,cx,cy=500,500,320,240
- # fovx,fovy = 65.23848614 51.28201165
- rx, ry = 0.638, 0.478
- self.pose = pose
- arr = [np.array([-rx, -ry, 1.]) * zmin,
- np.array([-rx, ry,
- np.array([ rx,
- np.array([-rx, 1.]) * zmax, 1.]) * zmax]
- # vertices: nul,nll,ful,fur
- self.vertices_ = self.pose * np.vstack(arr)
- # self.near,self.far = np.array([0,zmin]),np.array([0,zmax])
- # self.near_off,self.far_off = np.tan(fov / 2) * zmin,np.tan(fov / 2) * zmax
- # arr = [self.near + np.array([-1,-1,0]) * self.near_off,
- # self.near + np.array([1,1,
- # self.near + np.array([-1,
- # self.far + np.array([-1,0]) * self.far_off,
- # self.far + np.array([1,
- # self.far + np.array([-1,0]) * self.far_off]
- # nll,ful = self.pose * np.vstack(arr)
- # return nll,ful
- def __init__(self,
- get_sample=lambda item: item,
- on_sampled_cb=lambda index, verbose=False):
- Sampler.__init__(self,
- get_sample=get_sample,
- on_sampled_cb=on_sampled_cb, verbose=verbose)
- self.displacement_ = displacement
- self.theta_ = theta
- def obj_set_position_target(self, handle, angle):
- return self.RAPI_rc(vrep.simxSetJointTargetPosition( self.cID,handle,
- -np.deg2rad(angle),
- vrep.simx_opmode_blocking))
- def getJitteredParams(self, num, center=(0.0, 0.0), maxRot=(-5.0, 5.0), maxTranslate=(-2.0, 2.0),
- maxScale=(-0.1, 0.1), mirror=True):
- if not (type(maxRot) is tuple):
- maxRot = (-maxRot, maxRot)
- if not (type(maxTranslate) is tuple):
- maxTranslate = (-maxTranslate, maxTranslate)
- if not (type(maxScale) is tuple):
- maxScale = (-maxScale, maxScale)
- alphas = self.rng.rand(num) * (maxRot[1] - maxRot[0]) + maxRot[0]
- alphas = numpy.deg2rad(alphas)
- tx = self.rng.rand(num) * (maxTranslate[1] - maxTranslate[0]) + maxTranslate[0]
- ty = self.rng.rand(num) * (maxTranslate[1] - maxTranslate[0]) + maxTranslate[0]
- sc = 2 ** -(self.rng.rand(num) * (maxScale[1] - maxScale[0]) + maxScale[0])
- if mirror:
- mi = self.rng.randint(2, size=num) # mirror true or false
- else:
- mi = numpy.zeros(num)
- transformationMats = []
- for i in range(num):
- # First is not modified
- if i == 0:
- t = numpy.array([0, 0])
- else:
- t = numpy.array([alphas[i], tx[i], ty[i], sc[i], mi[i]])
- transformationMats.append(t)
- return transformationMats
- def rotate(self, deg, center = (0,0)):
- '''''' rotates the image by set degree''''''
- #where c is the cosine of the angle,s is the sine of the angle and
- #x0,y0 are used to correctly translate the rotated image.
- # size of source image
- src_dimsx = self.data.shape[0]
- src_dimsy = self.data.shape[1]
- # get the radians and calculate sin and cos
- rad = np.deg2rad(deg)
- c = np.cos(rad)
- s = np.sin(rad)
- # calculate center of image
- cx = center[0] + src_dimsx/2
- cy = center[1] + src_dimsy/2
- # factor that moves the index to the center
- x0 = cx - c*cx - s*cx
- y0 = cy - c*cy + s*cy
- # initialize destination image
- dest = MyImage(self.data.shape)
- for y in range(src_dimsy):
- for x in range(src_dimsx):
- # get the source indexes
- src_x = int(c*x + s*y + x0)
- src_y = int(-s*x + c*y + y0)
- if src_y > 0 and src_y < src_dimsy and src_x > 0 and src_x < src_dimsx:
- #paste the value in the destination image
- dest.data[x][y] = self.data[src_x][src_y]
- self.data = dest.data
- def normalize_cord(latitude, longitude):
- ''''''
- normalize GPS cord array,assuming the earth is shpherical
- :param latitude: latitude array to normalize
- :param longitude: longitude array to normalize
- :return: normalized arrays (np.array)
- ''''''
- rad_lat = np.deg2rad(latitude)
- rad_lon = np.deg2rad(longitude)
- x = np.cos(rad_lat) * np.cos(rad_lon)
- y = np.cos(rad_lat) * np.sin(rad_lon)
- z = np.sin(rad_lat)
- return x, z
- def d_xy(self):
- """
- The sampling interval along the (X,Y) spatial dimensions,
- translated from the pixel size.
- Unit: [Mpc]
- Reference: Ref.[liu2014].Eq.(A7)
- """
- pixelsize = self.pixelsize / 3600 # [arcsec] -> [deg]
- d_xy = self.DMz * np.deg2rad(pixelsize)
- return d_xy
- def rotate_about_center(src, scale=1.):
- w = src.shape[1]
- h = src.shape[0]
- rangle = np.deg2rad(angle) # angle in radians
- nw = (abs(np.sin(rangle)*h) + abs(np.cos(rangle)*w))*scale
- nh = (abs(np.cos(rangle)*h) + abs(np.sin(rangle)*w))*scale
- rot_mat = cv2.getRotationMatrix2D((nw*0.5, nh*0.5), scale)
- rot_move = np.dot(rot_mat, np.array([(nw-w)*0.5, (nh-h)*0.5,0]))
- rot_mat[0,2] += rot_move[0]
- rot_mat[1,2] += rot_move[1]
- return cv2.warpAffine(src, (int(math.ceil(nw)), int(math.ceil(nh))), flags=cv2.INTER_lanczos4)
Jupyter 中的 Numpy 在打印时出错(Python 版本 3.8.8):TypeError: 'numpy.ndarray' object is not callable
如何解决Jupyter 中的 Numpy 在打印时出错(Python 版本 3.8.8):TypeError: ''numpy.ndarray'' object is not callable?
晚安, 尝试打印以下内容时,我在 jupyter 中遇到了 numpy 问题,并且得到了一个 错误: 需要注意的是python版本是3.8.8。 我先用 spyder 测试它,它运行正确,它给了我预期的结果
使用 Spyder:
import numpy as np
for i in range (5):
n = np.random.rand ()
print (n)
Results
0.6604903457995978
0.8236300859753154
0.16067650689842816
0.6967868357083673
0.4231597934445466
现在有了 jupyter
import numpy as np
for i in range (5):
n = np.random.rand ()
print (n)
-------------------------------------------------- ------
TypeError Traceback (most recent call last)
<ipython-input-78-0c6a801b3ea9> in <module>
2 for i in range (5):
3 n = np.random.rand ()
----> 4 print (n)
TypeError: ''numpy.ndarray'' object is not callable
感谢您对我如何在 Jupyter 中解决此问题的帮助。
非常感谢您抽出宝贵时间。
阿特,约翰”
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)
numpy.random.random & numpy.ndarray.astype & numpy.arange
今天看到这样一句代码:
xb = np.random.random((nb, d)).astype(''float32'') #创建一个二维随机数矩阵(nb行d列)
xb[:, 0] += np.arange(nb) / 1000. #将矩阵第一列的每个数加上一个值
要理解这两句代码需要理解三个函数
1、生成随机数
numpy.random.random(size=None)
size为None时,返回float。
size不为None时,返回numpy.ndarray。例如numpy.random.random((1,2)),返回1行2列的numpy数组
2、对numpy数组中每一个元素进行类型转换
numpy.ndarray.astype(dtype)
返回numpy.ndarray。例如 numpy.array([1, 2, 2.5]).astype(int),返回numpy数组 [1, 2, 2]
3、获取等差数列
numpy.arange([start,]stop,[step,]dtype=None)
功能类似python中自带的range()和numpy中的numpy.linspace
返回numpy数组。例如numpy.arange(3),返回numpy数组[0, 1, 2]
numpy.ravel()/numpy.flatten()/numpy.squeeze()
numpy.ravel(a, order=''C'')
Return a flattened array
numpy.chararray.flatten(order=''C'')
Return a copy of the array collapsed into one dimension
numpy.squeeze(a, axis=None)
Remove single-dimensional entries from the shape of an array.
相同点: 将多维数组 降为 一维数组
不同点:
ravel() 返回的是视图(view),意味着改变元素的值会影响原始数组元素的值;
flatten() 返回的是拷贝,意味着改变元素的值不会影响原始数组;
squeeze()返回的是视图(view),仅仅是将shape中dimension为1的维度去掉;
ravel()示例:
1 import matplotlib.pyplot as plt
2 import numpy as np
3
4 def log_type(name,arr):
5 print("数组{}的大小:{}".format(name,arr.size))
6 print("数组{}的维度:{}".format(name,arr.shape))
7 print("数组{}的维度:{}".format(name,arr.ndim))
8 print("数组{}元素的数据类型:{}".format(name,arr.dtype))
9 #print("数组:{}".format(arr.data))
10
11 a = np.floor(10*np.random.random((3,4)))
12 print(a)
13 log_type(''a'',a)
14
15 a1 = a.ravel()
16 print("a1:{}".format(a1))
17 log_type(''a1'',a1)
18 a1[2] = 100
19
20 print(a)
21 log_type(''a'',a)
flatten()示例
1 import matplotlib.pyplot as plt
2 import numpy as np
3
4 def log_type(name,arr):
5 print("数组{}的大小:{}".format(name,arr.size))
6 print("数组{}的维度:{}".format(name,arr.shape))
7 print("数组{}的维度:{}".format(name,arr.ndim))
8 print("数组{}元素的数据类型:{}".format(name,arr.dtype))
9 #print("数组:{}".format(arr.data))
10
11 a = np.floor(10*np.random.random((3,4)))
12 print(a)
13 log_type(''a'',a)
14
15 a1 = a.flatten()
16 print("修改前a1:{}".format(a1))
17 log_type(''a1'',a1)
18 a1[2] = 100
19 print("修改后a1:{}".format(a1))
20
21 print("a:{}".format(a))
22 log_type(''a'',a)
squeeze()示例:
1. 没有single-dimensional entries的情况
1 import matplotlib.pyplot as plt
2 import numpy as np
3
4 def log_type(name,arr):
5 print("数组{}的大小:{}".format(name,arr.size))
6 print("数组{}的维度:{}".format(name,arr.shape))
7 print("数组{}的维度:{}".format(name,arr.ndim))
8 print("数组{}元素的数据类型:{}".format(name,arr.dtype))
9 #print("数组:{}".format(arr.data))
10
11 a = np.floor(10*np.random.random((3,4)))
12 print(a)
13 log_type(''a'',a)
14
15 a1 = a.squeeze()
16 print("修改前a1:{}".format(a1))
17 log_type(''a1'',a1)
18 a1[2] = 100
19 print("修改后a1:{}".format(a1))
20
21 print("a:{}".format(a))
22 log_type(''a'',a)
从结果中可以看到,当没有single-dimensional entries时,squeeze()返回额数组对象是一个view,而不是copy。
2. 有single-dimentional entries 的情况
1 import matplotlib.pyplot as plt
2 import numpy as np
3
4 def log_type(name,arr):
5 print("数组{}的大小:{}".format(name,arr.size))
6 print("数组{}的维度:{}".format(name,arr.shape))
7 print("数组{}的维度:{}".format(name,arr.ndim))
8 print("数组{}元素的数据类型:{}".format(name,arr.dtype))
9 #print("数组:{}".format(arr.data))
10
11 a = np.floor(10*np.random.random((1,3,4)))
12 print(a)
13 log_type(''a'',a)
14
15 a1 = a.squeeze()
16 print("修改前a1:{}".format(a1))
17 log_type(''a1'',a1)
18 a1[2] = 100
19 print("修改后a1:{}".format(a1))
20
21 print("a:{}".format(a))
22 log_type(''a'',a)
Numpy:数组创建 numpy.arrray() , numpy.arange()、np.linspace ()、数组基本属性
一、Numpy数组创建
part 1:np.linspace(起始值,终止值,元素总个数
import numpy as np
''''''
numpy中的ndarray数组
''''''
ary = np.array([1, 2, 3, 4, 5])
print(ary)
ary = ary * 10
print(ary)
''''''
ndarray对象的创建
''''''
# 创建二维数组
# np.array([[],[],...])
a = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
print(a)
# np.arange(起始值, 结束值, 步长(默认1))
b = np.arange(1, 10, 1)
print(b)
print("-------------np.zeros(数组元素个数, dtype=''数组元素类型'')-----")
# 创建一维数组:
c = np.zeros(10)
print(c, ''; c.dtype:'', c.dtype)
# 创建二维数组:
print(np.zeros ((3,4)))
print("----------np.ones(数组元素个数, dtype=''数组元素类型'')--------")
# 创建一维数组:
d = np.ones(10, dtype=''int64'')
print(d, ''; d.dtype:'', d.dtype)
# 创建三维数组:
print(np.ones( (2,3,4), dtype=np.int32 ))
# 打印维度
print(np.ones( (2,3,4), dtype=np.int32 ).ndim) # 返回:3(维)
结果图:
part 2 :np.linspace ( 起始值,终止值,元素总个数)
import numpy as np
a = np.arange( 10, 30, 5 )
b = np.arange( 0, 2, 0.3 )
c = np.arange(12).reshape(4,3)
d = np.random.random((2,3)) # 取-1到1之间的随机数,要求设置为诶2行3列的结构
print(a)
print(b)
print(c)
print(d)
print("-----------------")
from numpy import pi
print(np.linspace( 0, 2*pi, 100 ))
print("-------------np.linspace(起始值,终止值,元素总个数)------------------")
print(np.sin(np.linspace( 0, 2*pi, 100 )))
结果图:
二、Numpy的ndarray对象属性:
数组的结构:array.shape
数组的维度:array.ndim
元素的类型:array.dtype
数组元素的个数:array.size
数组的索引(下标):array[0]
''''''
数组的基本属性
''''''
import numpy as np
print("--------------------案例1:------------------------------")
a = np.arange(15).reshape(3, 5)
print(a)
print(a.shape) # 打印数组结构
print(len(a)) # 打印有多少行
print(a.ndim) # 打印维度
print(a.dtype) # 打印a数组内的元素的数据类型
# print(a.dtype.name)
print(a.size) # 打印数组的总元素个数
print("-------------------案例2:---------------------------")
a = np.array([[1, 2, 3], [4, 5, 6]])
print(a)
# 测试数组的基本属性
print(''a.shape:'', a.shape)
print(''a.size:'', a.size)
print(''len(a):'', len(a))
# a.shape = (6, ) # 此格式可将原数组结构变成1行6列的数据结构
# print(a, ''a.shape:'', a.shape)
# 数组元素的索引
ary = np.arange(1, 28)
ary.shape = (3, 3, 3) # 创建三维数组
print("ary.shape:",ary.shape,"\n",ary )
print("-----------------")
print(''ary[0]:'', ary[0])
print(''ary[0][0]:'', ary[0][0])
print(''ary[0][0][0]:'', ary[0][0][0])
print(''ary[0,0,0]:'', ary[0, 0, 0])
print("-----------------")
# 遍历三维数组:遍历出数组里的每个元素
for i in range(ary.shape[0]):
for j in range(ary.shape[1]):
for k in range(ary.shape[2]):
print(ary[i, j, k], end='' '')
结果图:
关于Python numpy 模块-deg2rad() 实例源码和python中numpy模块的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于Jupyter 中的 Numpy 在打印时出错(Python 版本 3.8.8):TypeError: 'numpy.ndarray' object is not callable、numpy.random.random & numpy.ndarray.astype & numpy.arange、numpy.ravel()/numpy.flatten()/numpy.squeeze()、Numpy:数组创建 numpy.arrray() , numpy.arange()、np.linspace ()、数组基本属性等相关知识的信息别忘了在本站进行查找喔。
本文标签: