在这篇文章中,我们将带领您了解Pythonnumpy模块-bitwise_not()实例源码的全貌,包括python中numpy模块的相关情况。同时,我们还将为您介绍有关Jupyter中的Numpy在
在这篇文章中,我们将带领您了解Python numpy 模块-bitwise_not() 实例源码的全貌,包括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 模块-bitwise_not() 实例源码(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 模块-bitwise_not() 实例源码(python中numpy模块)
Python numpy 模块,bitwise_not() 实例源码
我们从Python开源项目中,提取了以下6个代码示例,用于说明如何使用numpy.bitwise_not()。
- def test_values(self):
- for dt in self.bitwise_types:
- zeros = np.array([0], dtype=dt)
- ones = np.array([-1], dtype=dt)
- msg = "dt = ''%s''" % dt.char
- assert_equal(np.bitwise_not(zeros), ones, err_msg=msg)
- assert_equal(np.bitwise_not(ones), zeros, err_msg=msg)
- assert_equal(np.bitwise_or(zeros, zeros), err_msg=msg)
- assert_equal(np.bitwise_or(zeros, ones), err_msg=msg)
- assert_equal(np.bitwise_or(ones, err_msg=msg)
- assert_equal(np.bitwise_xor(zeros, err_msg=msg)
- assert_equal(np.bitwise_xor(zeros, err_msg=msg)
- assert_equal(np.bitwise_xor(ones, err_msg=msg)
- assert_equal(np.bitwise_and(zeros, err_msg=msg)
- assert_equal(np.bitwise_and(zeros, err_msg=msg)
- assert_equal(np.bitwise_and(ones, err_msg=msg)
- def test_types(self):
- for dt in self.bitwise_types:
- zeros = np.array([0], dtype=dt)
- msg = "dt = ''%s''" % dt.char
- assert_(np.bitwise_not(zeros).dtype == dt, msg)
- assert_(np.bitwise_or(zeros, zeros).dtype == dt, msg)
- assert_(np.bitwise_xor(zeros, msg)
- assert_(np.bitwise_and(zeros, msg)
- def _mask_trigs(events, mask):
- """Helper function for masking digital trigger values"""
- if not isinstance(mask, int):
- raise TypeError(''You provided a(n) %s. Mask must be an int.''
- % type(mask))
- n_events = len(events)
- if n_events == 0:
- return events.copy()
- mask = np.bitwise_not(mask)
- events[:, 1:] = np.bitwise_and(events[:, 1:], mask)
- events = events[events[:, 1] != events[:, 2]]
- return events
- def _numpy(self, data, weights, shape):
- q = self.quantity(data)
- self._checkNPQuantity(q, shape)
- self._checkNPWeights(weights, shape)
- weights = self._makeNPWeights(weights, shape)
- newentries = weights.sum()
- import numpy
- selection = numpy.isnan(q)
- numpy.bitwise_not(selection, selection)
- subweights = weights.copy()
- subweights[selection] = 0.0
- self.nanflow._numpy(data, subweights, shape)
- # switch to float here like in bin.py else numpy throws
- # TypeError on trivial integer cases such as:
- # >>> q = numpy.array([1,2,3,4])
- # >>> np.divide(q,1,q)
- # >>> np.floor(q,q)
- q = numpy.array(q, dtype=numpy.float64)
- neginfs = numpy.isneginf(q)
- posinfs = numpy.isposinf(q)
- numpy.subtract(q, self.origin, q)
- numpy.divide(q, self.binWidth, q)
- numpy.floor(q, q)
- q = numpy.array(q, dtype=numpy.int64)
- q[neginfs] = LONG_MINUSINF
- q[posinfs] = LONG_PLUSINF
- selected = q[weights > 0.0]
- selection = numpy.empty(q.shape, dtype=numpy.bool)
- for index in numpy.unique(selected):
- if index != LONG_NAN:
- bin = self.bins.get(index)
- if bin is None:
- bin = self.value.zero()
- self.bins[index] = bin
- numpy.not_equal(q, index, selection)
- subweights[:] = weights
- subweights[selection] = 0.0
- bin._numpy(data, shape)
- # no possibility of exception from here on out (for rollback)
- self.entries += float(newentries)
- def __init__(self, M, row_sparsity=None, column_sparsity=None, sparsity_threshold=0.05):
- # pylint: disable=len-as-condition
- self.M = M
- self.num_rows, self.num_columns = M.shape
- self.sparsity_threshold = sparsity_threshold*np.max(M.shape)
- self.M_csr = sp.sparse.csr_matrix(M)
- if row_sparsity is None:
- self.elements_per_row = np.array([self.M_csr.indptr[i + 1] - self.M_csr.indptr[i] for i in range(0, len(self.M_csr.indptr) - 1)])
- row_sparsity = self.elements_per_row < self.sparsity_threshold
- if column_sparsity is None:
- self.M_csc = sp.sparse.csc_matrix(M)
- self.elements_per_column = np.array([self.M_csc.indptr[i + 1] - self.M_csc.indptr[i] for i in range(0, len(self.M_csc.indptr) - 1)])
- column_sparsity = self.elements_per_column < self.sparsity_threshold
- self.r_s = row_sparsity if len(row_sparsity) else np.array([True]*self.M.shape[0])
- self.r_d = np.bitwise_not(self.r_s)
- self.ri_s = self.r_s.nonzero()[0]
- self.ri_d = self.r_d.nonzero()[0]
- self.c_s = column_sparsity if len(column_sparsity) else np.array([True]*self.M.shape[1])
- self.c_d = np.bitwise_not(self.c_s)
- self.ci_s = self.c_s.nonzero()[0]
- self.ci_d = self.c_d.nonzero()[0]
- M_coo = sp.sparse.coo_matrix(M)
- # sparse blocks s,and ss are created to be the size of the entire matrix,M. Dense blocks,however,are just the size of the subblocks.
- self.block_s = mask_sparse_matrix_by_rows(M_coo, self.row_sparsity)
- self.block_ss = mask_sparse_matrix_by_columns(self.block_s, self.column_sparsity).tocsr()
- self.block_ss_csc = self.block_ss.tocsc()
- self.block_sd = mask_sparse_matrix_by_columns(self.block_s, self.column_density).tocsr()[:, self.dense_column_indices].todense() if self.num_dense_columns else np.zeros((self.num_sparse_rows, self.num_dense_columns))
- self.block_s = self.block_s.tocsr()
- self.block_s_csc = self.block_s.tocsc()
- self.block_d_sparse = mask_sparse_matrix_by_rows(M_coo, self.row_density).tocsr()
- self.block_d = self.block_d_sparse[self.dense_row_indices, :].todense()
- self.block_ds = self.block_d[:, self.sparse_column_indices]
- self.block_dd = self.block_d[:, self.dense_column_indices]
- self.sparse_block = self.block_ss_csc[:, self.sparse_column_indices].tocsr()[self.sparse_row_indices, :]
- def get_demand_or_head_residual(self, head, demand):
- if self.mode == ''PDD'':
- minP = self.minimum_pressures
- nomP = self.nominal_pressures
- j_d = self.junction_demand
- m = self._slope_of_pdd_curve
- delta = self._pdd_smoothing_delta
- n_j = self.num_junctions
- P = head[:n_j] - self.node_elevations[:n_j]
- H = head[:n_j]
- Dact = demand[:n_j]
- self.demand_or_head_residual[:n_j] = (
- self.isolated_junction_array * H + (1.0 - self.isolated_junction_array)*(
- (P <= minP) * (Dact - j_d*m*(P-minP)) +
- (P > minP) * (P <= (minP + delta)) * (
- Dact - j_d*(
- self.pdd_poly1_coeffs_a*P**3 +
- self.pdd_poly1_coeffs_b*P**2 +
- self.pdd_poly1_coeffs_c*P +
- self.pdd_poly1_coeffs_d
- )
- ) +
- (P > (nomP - delta)) * (P <= nomP) * (
- Dact - j_d*(
- self.pdd_poly2_coeffs_a*P**3 +
- self.pdd_poly2_coeffs_b*P**2 +
- self.pdd_poly2_coeffs_c*P +
- self.pdd_poly2_coeffs_d
- )
- ) +
- (P > nomP) * (Dact - j_d * (m*(P-nomP) + 1.0))
- )
- )
- # for the last segment,assignment is required because 0*np.nan does not equal 0 (same with np.inf)
- last_segment = (Dact - j_d*((P-minP)/(nomP-minP))**0.5)
- last_segment[np.bitwise_not((P > (minP + delta))*(P <= (nomP - delta)))] = 0.0
- self.demand_or_head_residual[:n_j] = (self.demand_or_head_residual[:n_j] +
- last_segment*(1.0-self.isolated_junction_array))
- else:
- self.demand_or_head_residual[:self.num_junctions] = (
- self.isolated_junction_array * head[:self.num_junctions] +
- (1.0 - self.isolated_junction_array) * (demand[:self.num_junctions] - self.junction_demand)
- )
- for node_id in self._tank_ids:
- self.demand_or_head_residual[node_id] = head[node_id] - self.tank_head[node_id]
- for node_id in self._reservoir_ids:
- self.demand_or_head_residual[node_id] = head[node_id] - self.reservoir_head[node_id]
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 模块-bitwise_not() 实例源码和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 ()、数组基本属性的相关知识,请在本站进行查询。
本文标签: