GVKun编程网logo

Python numpy 模块-bitwise_not() 实例源码(python中numpy模块)

1

在这篇文章中,我们将带领您了解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模块)

Python numpy 模块-bitwise_not() 实例源码(python中numpy模块)

Python numpy 模块,bitwise_not() 实例源码

我们从Python开源项目中,提取了以下6个代码示例,用于说明如何使用numpy.bitwise_not()

项目:deliver    作者:orchestor    | 项目源码 | 文件源码
  1. def test_values(self):
  2. for dt in self.bitwise_types:
  3. zeros = np.array([0], dtype=dt)
  4. ones = np.array([-1], dtype=dt)
  5. msg = "dt = ''%s''" % dt.char
  6.  
  7. assert_equal(np.bitwise_not(zeros), ones, err_msg=msg)
  8. assert_equal(np.bitwise_not(ones), zeros, err_msg=msg)
  9.  
  10. assert_equal(np.bitwise_or(zeros, zeros), err_msg=msg)
  11. assert_equal(np.bitwise_or(zeros, ones), err_msg=msg)
  12. assert_equal(np.bitwise_or(ones, err_msg=msg)
  13.  
  14. assert_equal(np.bitwise_xor(zeros, err_msg=msg)
  15. assert_equal(np.bitwise_xor(zeros, err_msg=msg)
  16. assert_equal(np.bitwise_xor(ones, err_msg=msg)
  17.  
  18. assert_equal(np.bitwise_and(zeros, err_msg=msg)
  19. assert_equal(np.bitwise_and(zeros, err_msg=msg)
  20. assert_equal(np.bitwise_and(ones, err_msg=msg)
项目:deliver    作者:orchestor    | 项目源码 | 文件源码
  1. def test_types(self):
  2. for dt in self.bitwise_types:
  3. zeros = np.array([0], dtype=dt)
  4. msg = "dt = ''%s''" % dt.char
  5.  
  6. assert_(np.bitwise_not(zeros).dtype == dt, msg)
  7. assert_(np.bitwise_or(zeros, zeros).dtype == dt, msg)
  8. assert_(np.bitwise_xor(zeros, msg)
  9. assert_(np.bitwise_and(zeros, msg)
项目:decoding_challenge_cortana_2016_3rd    作者:kingjr    | 项目源码 | 文件源码
  1. def _mask_trigs(events, mask):
  2. """Helper function for masking digital trigger values"""
  3. if not isinstance(mask, int):
  4. raise TypeError(''You provided a(n) %s. Mask must be an int.''
  5. % type(mask))
  6. n_events = len(events)
  7. if n_events == 0:
  8. return events.copy()
  9.  
  10. mask = np.bitwise_not(mask)
  11. events[:, 1:] = np.bitwise_and(events[:, 1:], mask)
  12. events = events[events[:, 1] != events[:, 2]]
  13.  
  14. return events
项目:Eskapade    作者:KaveIO    | 项目源码 | 文件源码
  1. def _numpy(self, data, weights, shape):
  2. q = self.quantity(data)
  3. self._checkNPQuantity(q, shape)
  4. self._checkNPWeights(weights, shape)
  5. weights = self._makeNPWeights(weights, shape)
  6. newentries = weights.sum()
  7.  
  8. import numpy
  9.  
  10. selection = numpy.isnan(q)
  11. numpy.bitwise_not(selection, selection)
  12. subweights = weights.copy()
  13. subweights[selection] = 0.0
  14. self.nanflow._numpy(data, subweights, shape)
  15.  
  16. # switch to float here like in bin.py else numpy throws
  17. # TypeError on trivial integer cases such as:
  18. # >>> q = numpy.array([1,2,3,4])
  19. # >>> np.divide(q,1,q)
  20. # >>> np.floor(q,q)
  21. q = numpy.array(q, dtype=numpy.float64)
  22. neginfs = numpy.isneginf(q)
  23. posinfs = numpy.isposinf(q)
  24.  
  25. numpy.subtract(q, self.origin, q)
  26. numpy.divide(q, self.binWidth, q)
  27. numpy.floor(q, q)
  28. q = numpy.array(q, dtype=numpy.int64)
  29. q[neginfs] = LONG_MINUSINF
  30. q[posinfs] = LONG_PLUSINF
  31.  
  32. selected = q[weights > 0.0]
  33.  
  34. selection = numpy.empty(q.shape, dtype=numpy.bool)
  35. for index in numpy.unique(selected):
  36. if index != LONG_NAN:
  37. bin = self.bins.get(index)
  38. if bin is None:
  39. bin = self.value.zero()
  40. self.bins[index] = bin
  41.  
  42. numpy.not_equal(q, index, selection)
  43. subweights[:] = weights
  44. subweights[selection] = 0.0
  45. bin._numpy(data, shape)
  46.  
  47. # no possibility of exception from here on out (for rollback)
  48. self.entries += float(newentries)
项目:blmath    作者:bodylabs    | 项目源码 | 文件源码
  1. def __init__(self, M, row_sparsity=None, column_sparsity=None, sparsity_threshold=0.05):
  2. # pylint: disable=len-as-condition
  3. self.M = M
  4. self.num_rows, self.num_columns = M.shape
  5. self.sparsity_threshold = sparsity_threshold*np.max(M.shape)
  6.  
  7. self.M_csr = sp.sparse.csr_matrix(M)
  8. if row_sparsity is None:
  9. 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)])
  10. row_sparsity = self.elements_per_row < self.sparsity_threshold
  11.  
  12.  
  13. if column_sparsity is None:
  14. self.M_csc = sp.sparse.csc_matrix(M)
  15. 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)])
  16. column_sparsity = self.elements_per_column < self.sparsity_threshold
  17.  
  18. self.r_s = row_sparsity if len(row_sparsity) else np.array([True]*self.M.shape[0])
  19. self.r_d = np.bitwise_not(self.r_s)
  20. self.ri_s = self.r_s.nonzero()[0]
  21. self.ri_d = self.r_d.nonzero()[0]
  22.  
  23. self.c_s = column_sparsity if len(column_sparsity) else np.array([True]*self.M.shape[1])
  24. self.c_d = np.bitwise_not(self.c_s)
  25. self.ci_s = self.c_s.nonzero()[0]
  26. self.ci_d = self.c_d.nonzero()[0]
  27.  
  28. M_coo = sp.sparse.coo_matrix(M)
  29. # 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.
  30.  
  31. self.block_s = mask_sparse_matrix_by_rows(M_coo, self.row_sparsity)
  32. self.block_ss = mask_sparse_matrix_by_columns(self.block_s, self.column_sparsity).tocsr()
  33. self.block_ss_csc = self.block_ss.tocsc()
  34. 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))
  35. self.block_s = self.block_s.tocsr()
  36. self.block_s_csc = self.block_s.tocsc()
  37.  
  38. self.block_d_sparse = mask_sparse_matrix_by_rows(M_coo, self.row_density).tocsr()
  39. self.block_d = self.block_d_sparse[self.dense_row_indices, :].todense()
  40. self.block_ds = self.block_d[:, self.sparse_column_indices]
  41. self.block_dd = self.block_d[:, self.dense_column_indices]
  42.  
  43. self.sparse_block = self.block_ss_csc[:, self.sparse_column_indices].tocsr()[self.sparse_row_indices, :]
项目:WNTR    作者:USEPA    | 项目源码 | 文件源码
  1. def get_demand_or_head_residual(self, head, demand):
  2.  
  3. if self.mode == ''PDD'':
  4. minP = self.minimum_pressures
  5. nomP = self.nominal_pressures
  6. j_d = self.junction_demand
  7. m = self._slope_of_pdd_curve
  8. delta = self._pdd_smoothing_delta
  9. n_j = self.num_junctions
  10. P = head[:n_j] - self.node_elevations[:n_j]
  11. H = head[:n_j]
  12. Dact = demand[:n_j]
  13.  
  14. self.demand_or_head_residual[:n_j] = (
  15. self.isolated_junction_array * H + (1.0 - self.isolated_junction_array)*(
  16. (P <= minP) * (Dact - j_d*m*(P-minP)) +
  17. (P > minP) * (P <= (minP + delta)) * (
  18. Dact - j_d*(
  19. self.pdd_poly1_coeffs_a*P**3 +
  20. self.pdd_poly1_coeffs_b*P**2 +
  21. self.pdd_poly1_coeffs_c*P +
  22. self.pdd_poly1_coeffs_d
  23. )
  24. ) +
  25. (P > (nomP - delta)) * (P <= nomP) * (
  26. Dact - j_d*(
  27. self.pdd_poly2_coeffs_a*P**3 +
  28. self.pdd_poly2_coeffs_b*P**2 +
  29. self.pdd_poly2_coeffs_c*P +
  30. self.pdd_poly2_coeffs_d
  31. )
  32. ) +
  33. (P > nomP) * (Dact - j_d * (m*(P-nomP) + 1.0))
  34. )
  35. )
  36. # for the last segment,assignment is required because 0*np.nan does not equal 0 (same with np.inf)
  37. last_segment = (Dact - j_d*((P-minP)/(nomP-minP))**0.5)
  38. last_segment[np.bitwise_not((P > (minP + delta))*(P <= (nomP - delta)))] = 0.0
  39. self.demand_or_head_residual[:n_j] = (self.demand_or_head_residual[:n_j] +
  40. last_segment*(1.0-self.isolated_junction_array))
  41. else:
  42. self.demand_or_head_residual[:self.num_junctions] = (
  43. self.isolated_junction_array * head[:self.num_junctions] +
  44. (1.0 - self.isolated_junction_array) * (demand[:self.num_junctions] - self.junction_demand)
  45. )
  46. for node_id in self._tank_ids:
  47. self.demand_or_head_residual[node_id] = head[node_id] - self.tank_head[node_id]
  48. for node_id in self._reservoir_ids:
  49. 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):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

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()/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:数组创建 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 ()、数组基本属性的相关知识,请在本站进行查询。

本文标签: