GVKun编程网logo

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

3

关于Pythonnumpy模块-str_()实例源码和python中numpy模块的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于+不支持的操作数类型:“float”和“numpy.str

关于Python numpy 模块-str_() 实例源码python中numpy模块的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于+ 不支持的操作数类型:“float”和“numpy.str_”、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()等相关知识的信息别忘了在本站进行查找喔。

本文目录一览:

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

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

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

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

项目:radar    作者:amoose136    | 项目源码 | 文件源码
  1. def test_scalar_none_comparison(self):
  2. # Scalars should still just return False and not give a warnings.
  3. # The comparisons are flagged by pep8,ignore that.
  4. with warnings.catch_warnings(record=True) as w:
  5. warnings.filterwarnings(''always'', '''', FutureWarning)
  6. assert_(not np.float32(1) == None)
  7. assert_(not np.str_(''test'') == None)
  8. # This is dubIoUs (see below):
  9. assert_(not np.datetime64(''NaT'') == None)
  10.  
  11. assert_(np.float32(1) != None)
  12. assert_(np.str_(''test'') != None)
  13. # This is dubIoUs (see below):
  14. assert_(np.datetime64(''NaT'') != None)
  15. assert_(len(w) == 0)
  16.  
  17. # For documentation purposes,this is why the datetime is dubIoUs.
  18. # At the time of deprecation this was no behavIoUr change,but
  19. # it has to be considered when the deprecations are done.
  20. assert_(np.equal(np.datetime64(''NaT''), None))
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
  1. def test_scalar_none_comparison(self):
  2. # Scalars should still just return False and not give a warnings.
  3. # The comparisons are flagged by pep8, None))
项目:mean-teacher    作者:CurIoUsAI    | 项目源码 | 文件源码
  1. def test_stratified_batches():
  2. data = np.array([(''a'', -1), (''b'', 0), (''c'', 1), (''d'', (''e'', -1)],
  3. dtype=[(''x'', np.str_, 8), (''y'', np.int32)])
  4.  
  5. assert list(data[''x'']) == [''a'', ''b'', ''c'', ''d'', ''e'']
  6. assert list(data[''y'']) == [-1, 0, 1, -1, -1]
  7.  
  8. batch_generator = training_batches(data, batch_size=3, n_labeled_per_batch=1)
  9.  
  10. first_ten_batches = list(islice(batch_generator, 10))
  11.  
  12. labeled_batch_portions = [batch[:1] for batch in first_ten_batches]
  13. unlabeled_batch_portions = [batch[1:] for batch in first_ten_batches]
  14.  
  15. labeled_epochs = np.split(np.concatenate(labeled_batch_portions), 5)
  16. unlabeled_epochs = np.split(np.concatenate(unlabeled_batch_portions), 4)
  17.  
  18. assert ([sorted(items[''x''].tolist()) for items in labeled_epochs] ==
  19. [[''b'', ''c'']] * 5)
  20. assert ([sorted(items[''y''].tolist()) for items in labeled_epochs] ==
  21. [[0, 1]] * 5)
  22. assert ([sorted(items[''x''].tolist()) for items in unlabeled_epochs] ==
  23. [[''a'', ''e'']] * 4)
  24. assert ([sorted(items[''y''].tolist()) for items in unlabeled_epochs] ==
  25. [[-1, -1]] * 4)
项目:score_card_base_python    作者:zzstrwolf    | 项目源码 | 文件源码
  1. def discrete(self, x, bin=5):
  2. #res = np.array([0] * x.shape[-1],dtype=int)
  3. #?????????????????????woe?????????????<=?woe??
  4. x_copy = pd.Series.copy(x)
  5. x_copy = x_copy.astype(str)
  6. #x_copy = x_copy.astype(np.str_)
  7. #x_copy = x
  8. x_gt0 = x[x>=0]
  9. #if x.name == ''TD_pltF_CNT_1M'':
  10. #bin = 5
  11. #x_gt0 = x[(x>=0) & (x<=24)]
  12.  
  13. for i in range(bin):
  14. point1 = stats.scoreatpercentile(x_gt0, i * (100.0/bin))
  15. point2 = stats.scoreatpercentile(x_gt0, (i + 1) * (100.0/bin))
  16. x1 = x[(x >= point1) & (x <= point2)]
  17. mask = np.in1d(x, x1)
  18. #x_copy[mask] = i + 1
  19. x_copy[mask] = ''%s-%s'' % (point1,point2)
  20. #x_copy[mask] = point1
  21. #print x_copy[mask]
  22. #print x
  23. #print x
  24. return x_copy
项目:score_card_base_python    作者:zzstrwolf    | 项目源码 | 文件源码
  1. def grade(self,dtype=int)
  2. #?????????????????????woe?????????????<=?woe??
  3. x_copy = np.copy(x)
  4. #x_copy = x_copy.astype(str)
  5. #x_copy = x_copy.astype(np.str_)
  6. #x_copy = x
  7. x_gt0 = x[x>=0]
  8.  
  9. for i in range(bin):
  10. point1 = stats.scoreatpercentile(x_gt0, x1)
  11. #x_copy[mask] = i + 1
  12. x_copy[mask] = i + 1
  13. #x_copy[mask] = point1
  14. #print x_copy[mask]
  15. #print x
  16. print point1,point2
  17. #print x
  18. return x_copy
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
  1. def test_scalar_none_comparison(self):
  2. # Scalars should still just return false and not give a warnings.
  3. # The comparisons are flagged by pep8, FutureWarning)
  4. assert_(not np.float32(1) == None)
  5. assert_(not np.str_(''test'') == None)
  6. # This is dubIoUs (see below):
  7. assert_(not np.datetime64(''NaT'') == None)
  8.  
  9. assert_(np.float32(1) != None)
  10. assert_(np.str_(''test'') != None)
  11. # This is dubIoUs (see below):
  12. assert_(np.datetime64(''NaT'') != None)
  13. assert_(len(w) == 0)
  14.  
  15. # For documentaiton purpose,but
  16. # it has to be considered when the deprecations is done.
  17. assert_(np.equal(np.datetime64(''NaT''), None))
项目:aws-lambda-numpy    作者:vitolimandibhrata    | 项目源码 | 文件源码
  1. def test_scalar_none_comparison(self):
  2. # Scalars should still just return false and not give a warnings.
  3. # The comparisons are flagged by pep8, None))
项目:lambda-numba    作者:rlhotovy    | 项目源码 | 文件源码
  1. def test_scalar_none_comparison(self):
  2. # Scalars should still just return False and not give a warnings.
  3. # The comparisons are flagged by pep8, None))
项目:deliver    作者:orchestor    | 项目源码 | 文件源码
  1. def test_scalar_none_comparison(self):
  2. # Scalars should still just return False and not give a warnings.
  3. # The comparisons are flagged by pep8, None))
项目:loompy    作者:linnaRSSon-lab    | 项目源码 | 文件源码
  1. def normalize_attr_strings(a: np.ndarray) -> np.ndarray:
  2. """
  3. Take an np.ndarray of all kinds of string-like elements,and return an array of ascii (np.string_) objects
  4. """
  5. if np.issubdtype(a.dtype, np.object_):
  6. if np.all([type(x) is str for x in a]) or np.all([type(x) is np.str_ for x in a]) or np.all([type(x) is np.unicode_ for x in a]):
  7. return np.array([x.encode(''ascii'', ''xmlcharrefreplace'') for x in a])
  8. elif np.all([type(x) is np.string_ for x in a]) or np.all([type(x) is np.bytes_ for x in a]):
  9. return a.astype("string_")
  10. else:
  11. print(type(a[0]))
  12. raise ValueError("Arbitrary numpy object arrays not supported (all elements must be string objects).")
  13. elif np.issubdtype(a.dtype, np.string_) or np.issubdtype(a.dtype, np.object_):
  14. return a
  15. elif np.issubdtype(a.dtype, np.str_) or np.issubdtype(a.dtype, np.unicode_):
  16. return np.array([x.encode(''ascii'', ''xmlcharrefreplace'') for x in a])
  17. else:
  18. raise ValueError("String values must be object,ascii or unicode.")
项目:loompy    作者:linnaRSSon-lab    | 项目源码 | 文件源码
  1. def materialize_attr_values(a: np.ndarray) -> np.ndarray:
  2. scalar = False
  3. if np.isscalar(a):
  4. scalar = True
  5. a = np.array([a])
  6. result: np.ndarray = None
  7. if np.issubdtype(a.dtype, np.string_):
  8. # First ensure that what we load is valid ascii (i.e. ignore anything outside 7-bit range)
  9. temp = np.array([x.decode(''ascii'', ''ignore'') for x in a])
  10. # Then unescape XML entities and convert to unicode
  11. result = np.array([html.unescape(x) for x in temp.astype(str)], dtype=np.str_)
  12. elif np.issubdtype(a.dtype, np.unicode_):
  13. result = np.array(a.astype(str), dtype=np.str_)
  14. else:
  15. result = a
  16. if scalar:
  17. return result[0]
  18. else:
  19. return result
项目:lim    作者:limix    | 项目源码 | 文件源码
  1. def npy2py_type(npy_type):
  2. int_types = [
  3. np.int_, np.intc, np.intp, np.int8, np.int16, np.int32, np.int64,
  4. np.uint8, np.uint16, np.uint32, np.uint64
  5. ]
  6.  
  7. float_types = [np.float_, np.float16, np.float32, np.float64]
  8.  
  9. bytes_types = [np.str_, np.string_]
  10.  
  11. if npy_type in int_types:
  12. return int
  13. if npy_type in float_types:
  14. return float
  15. if npy_type in bytes_types:
  16. return bytes
  17.  
  18. if hasattr(npy_type, ''char''):
  19. if npy_type.char in [''S'', ''a'']:
  20. return bytes
  21. raise TypeError
  22.  
  23. return npy_type
项目:Alfred    作者:jkachhadia    | 项目源码 | 文件源码
  1. def test_scalar_none_comparison(self):
  2. # Scalars should still just return False and not give a warnings.
  3. # The comparisons are flagged by pep8, None))
项目:Eskapade    作者:KaveIO    | 项目源码 | 文件源码
  1. def initialize(self):
  2. """Initialize FixPandasDataFrame"""
  3.  
  4. self.check_arg_types(read_key=str, store_key=str)
  5. self.check_arg_types(recurse=True, allow_none=True, original_columns=str)
  6. self.check_arg_vals(''read_key'')
  7.  
  8. if not isinstance(self.cleanup_string_columns, list) and not isinstance(self.cleanup_string_columns, bool):
  9. raise AssertionError(''cleanup_string_columns should be a list of column names or boolean.'')
  10.  
  11. if self.read_key == self.store_key:
  12. self.inplace = True
  13. self.log().debug(''store_key equals read_key; inplace has been set to "True"'')
  14.  
  15. if self.inplace:
  16. self.store_key = self.read_key
  17. self.log().debug(''store_key has been set to read_key "%s"'', self.store_key)
  18.  
  19. if not self.store_key:
  20. self.store_key = self.read_key + ''_fix''
  21. self.log().debug(''store_key has been set to "%s"'', self.store_key)
  22.  
  23. # check data types
  24. for k in self.var_dtype.keys():
  25. if k not in self.contaminated_columns:
  26. self.contaminated_columns.append(k)
  27. try:
  28. # convert to consistent types
  29. dt = np.dtype(self.var_dtype[k]).type
  30. if dt is np.str_ or dt is np.object_:
  31. dt = str
  32. self.var_dtype[k] = dt
  33. except BaseException:
  34. raise TypeError(''unkNown assigned datatype to variable "%s"'' % k)
  35.  
  36. return StatusCode.Success
项目:radar    作者:amoose136    | 项目源码 | 文件源码
  1. def test_object_array_to_fixed_string(self):
  2. # Ticket #1235.
  3. a = np.array([''abcdefgh'', ''ijklmnop''], dtype=np.object_)
  4. b = np.array(a, dtype=(np.str_, 8))
  5. assert_equal(a, b)
  6. c = np.array(a, 5))
  7. assert_equal(c, np.array([''abcde'', ''ijklm'']))
  8. d = np.array(a, 12))
  9. assert_equal(a, d)
  10. e = np.empty((2, ), 8))
  11. e[:] = a[:]
  12. assert_equal(a, e)
项目:MIT-Thesis    作者:alec-heif    | 项目源码 | 文件源码
  1. def test_string(self):
  2. lr = LogisticRegression()
  3. for col in [''features'', u''features'', np.str_(''features'')]:
  4. lr.setFeaturesCol(col)
  5. self.assertEqual(lr.getFeaturesCol(), ''features'')
  6. self.assertRaises(TypeError, lambda: LogisticRegression(featuresCol=2.3))
项目:MIT-Thesis    作者:alec-heif    | 项目源码 | 文件源码
  1. def _can_convert_to_string(value):
  2. vtype = type(value)
  3. return isinstance(value, basestring) or vtype in [np.unicode_, np.string_, np.str_]
项目:MIT-Thesis    作者:alec-heif    | 项目源码 | 文件源码
  1. def toString(value):
  2. """
  3. Convert a value to a string,if possible.
  4. """
  5. if isinstance(value, basestring):
  6. return value
  7. elif type(value) in [np.string_, np.str_]:
  8. return str(value)
  9. elif type(value) == np.unicode_:
  10. return unicode(value)
  11. else:
  12. raise TypeError("Could not convert %s to string type" % type(value))
项目:describe    作者:SINGROUP    | 项目源码 | 文件源码
  1. def symbols_to_numbers(symbols):
  2. """Given element symbol(s),return the atomic number(s) (number of protons).
  3.  
  4. Args:
  5. symbols (str or list of str): Atomic symbol(s).
  6.  
  7. Returns:
  8. ndarray: Atomic number(s) (number of protons).
  9.  
  10. Raises:
  11. ValueError: If a given atomic symbol is invalid and doesn''t have a
  12. corresponding number.
  13. """
  14. single_value = False
  15. if isinstance(symbols, (str, np.str_)):
  16. symbols = [symbols]
  17. single_value = True
  18. numbers = []
  19. for symbol in symbols:
  20. number = SYMBOL_TO_NUMBER_MAP.get(symbol)
  21. if number is None:
  22. raise ValueError(
  23. "Given atomic symbol {} is invalid and doesn''t have a number "
  24. "associated with it.".format(symbol)
  25. )
  26. numbers.append(number)
  27. return numbers[0] if single_value else np.array(numbers)
项目:Dragonfly    作者:duaneloh    | 项目源码 | 文件源码
  1. def init_list(self):
  2. if self.fname is '''' or not os.path.isfile(self.fname):
  3. sys.stderr.write(''Initializing empty class list\\n'')
  4. self.clist = np.zeros((self.num_frames,), dtype=np.str_)
  5. else:
  6. self.clist = self.load()
  7. self.key, self.key_pos, self.key_counts = np.unique(self.clist, return_inverse=True, return_counts=True)
项目:automatic-portrait-tf    作者:Corea    | 项目源码 | 文件源码
  1. def main():
  2. net = caffe.Net(MODEL_DEF, MODEL_WEIGHT, caffe.TRAIN)
  3.  
  4. mat = []
  5. for i in range(len(net.layers)):
  6. mat_type = net.layers[i].type
  7. mat_data = []
  8. for j in range(len(net.layers[i].blobs)):
  9. mat_data.append(net.layers[i].blobs[j].data)
  10. mat.append((mat_type, mat_data))
  11.  
  12. dt = np.dtype([(''type'', 16), (''data'', np.ndarray)])
  13. results = np.array(mat, dtype=dt)
  14. results.dump(MAT_RESULT)
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
  1. def test_object_array_to_fixed_string(self):
  2. # Ticket #1235.
  3. a = np.array([''abcdefgh'', e)
项目:packaging    作者:blockstack    | 项目源码 | 文件源码
  1. def encode_ascii(s):
  2. if isinstance(s, str):
  3. return s.encode(''ascii'')
  4. elif isinstance(s, numpy.ndarray) and \\
  5. issubclass(s.dtype.type, numpy.str_):
  6. ns = numpy.char.encode(s, ''ascii'').view(type(s))
  7. if ns.dtype.itemsize != s.dtype.itemsize / 4:
  8. ns = ns.astype((numpy.bytes_, s.dtype.itemsize / 4))
  9. return ns
  10. return s
项目:packaging    作者:blockstack    | 项目源码 | 文件源码
  1. def decode_ascii(s):
  2. if isinstance(s, bytes):
  3. return s.decode(''ascii'')
  4. elif (isinstance(s, numpy.ndarray) and
  5. issubclass(s.dtype.type, numpy.bytes_)):
  6. # np.char.encode/decode annoyingly don''t preserve the type of the
  7. # array,hence the view() call
  8. # It also doesn''t necessarily preserve widths of the strings,
  9. # hence the astype()
  10. ns = numpy.char.decode(s, ''ascii'').view(type(s))
  11. if ns.dtype.itemsize / 4 != s.dtype.itemsize:
  12. ns = ns.astype((numpy.str_, s.dtype.itemsize))
  13. return ns
  14. return s
项目:score_card_base_python    作者:zzstrwolf    | 项目源码 | 文件源码
  1. def regroup(df,column,split_points):
  2. for i in range(len(split_points)-1):
  3. df[column][(df[column]>=split_points[i]) & (df[column]<=split_points[i+1])] = ''%s-%s'' % (split_points[i],split_points[i+1])
  4. df[column] = df[column].astype(np.str_)
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
  1. def test_astype_str(self):
  2. # GH4405
  3. digits = string.digits
  4. s1 = Series([digits * 10, tm.rands(63), tm.rands(64), tm.rands(1000)])
  5. s2 = Series([digits * 10, nan, 1.0])
  6. types = (compat.text_type, np.str_)
  7. for typ in types:
  8. for s in (s1, s2):
  9. res = s.astype(typ)
  10. expec = s.map(compat.text_type)
  11. assert_series_equal(res, expec)
  12.  
  13. # GH9757
  14. # Test str and unicode on python 2.x and just str on python 3.x
  15. for tt in set([str, compat.text_type]):
  16. ts = Series([Timestamp(''2010-01-04 00:00:00'')])
  17. s = ts.astype(tt)
  18. expected = Series([tt(''2010-01-04'')])
  19. assert_series_equal(s, expected)
  20.  
  21. ts = Series([Timestamp(''2010-01-04 00:00:00'', tz=''US/Eastern'')])
  22. s = ts.astype(tt)
  23. expected = Series([tt(''2010-01-04 00:00:00-05:00'')])
  24. assert_series_equal(s, expected)
  25.  
  26. td = Series([timedelta(1, unit=''d'')])
  27. s = td.astype(tt)
  28. expected = Series([tt(''1 days 00:00:00.000000000'')])
  29. assert_series_equal(s, expected)
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
  1. def test_constructor_empty_with_string_dtype(self):
  2. # GH 9428
  3. expected = DataFrame(index=[0, 1], columns=[0, dtype=object)
  4.  
  5. df = DataFrame(index=[0, dtype=str)
  6. assert_frame_equal(df, expected)
  7. df = DataFrame(index=[0, dtype=np.str_)
  8. assert_frame_equal(df, dtype=np.unicode_)
  9. assert_frame_equal(df, dtype=''U5'')
  10. assert_frame_equal(df, expected)
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
  1. def test_numpy_informed(self):
  2.  
  3. # np.dtype doesn''t kNow about our new dtype
  4. def f():
  5. np.dtype(self.dtype)
  6.  
  7. self.assertRaises(TypeError, f)
  8.  
  9. self.assertNotEqual(self.dtype, np.str_)
  10. self.assertNotEqual(np.str_, self.dtype)
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
  1. def test_isscalar_numpy_array_scalars(self):
  2. self.assertTrue(lib.isscalar(np.int64(1)))
  3. self.assertTrue(lib.isscalar(np.float64(1.)))
  4. self.assertTrue(lib.isscalar(np.int32(1)))
  5. self.assertTrue(lib.isscalar(np.object_(''foobar'')))
  6. self.assertTrue(lib.isscalar(np.str_(''foobar'')))
  7. self.assertTrue(lib.isscalar(np.unicode_(u(''foobar''))))
  8. self.assertTrue(lib.isscalar(np.bytes_(b''foobar'')))
  9. self.assertTrue(lib.isscalar(np.datetime64(''2014-01-01'')))
  10. self.assertTrue(lib.isscalar(np.timedelta64(1, ''h'')))
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
  1. def test_object_array_to_fixed_string(self):
  2. # Ticket #1235.
  3. a = np.array([''abcdefgh'', e)
项目:aws-lambda-numpy    作者:vitolimandibhrata    | 项目源码 | 文件源码
  1. def test_object_array_to_fixed_string(self):
  2. # Ticket #1235.
  3. a = np.array([''abcdefgh'', e)
项目:larray-editor    作者:larray-project    | 项目源码 | 文件源码
  1. def set_format(self, data, digits, scientific):
  2. """data: object with a dtype attribute"""
  3. type = data.dtype.type
  4. if type in (np.str, np.bool_, np.bool, np.object_):
  5. fmt = ''%s''
  6. else:
  7. # XXX: use self.digits_spinBox.getValue() and instead?
  8. # XXX: use self.digits_spinBox.getValue() instead?
  9. format_letter = ''e'' if scientific else ''f''
  10. fmt = ''%%.%d%s'' % (digits, format_letter)
  11. # this does not call model_data.reset() so it should be called by the caller
  12. self.model_data._set_format(fmt)
项目:larray-editor    作者:larray-project    | 项目源码 | 文件源码
  1. def to_excel(self):
  2. """View selection in Excel"""
  3. if xw is None:
  4. QMessageBox.critical(self, "Error", "to_excel() is not available because xlwings is not installed")
  5. data = self._selection_data()
  6. if data is None:
  7. return
  8. # convert (row) generators to lists then array
  9. # Todo: the conversion to array is currently necessary even though xlwings will translate it back to a list
  10. # anyway. The problem is that our lists contains numpy types and especially np.str_ crashes xlwings.
  11. # unsure how we should fix this properly: in xlwings,or change _selection_data to return only standard
  12. # Python types.
  13. xw.view(np.array([list(r) for r in data]))
项目:lambda-numba    作者:rlhotovy    | 项目源码 | 文件源码
  1. def test_object_array_to_fixed_string(self):
  2. # Ticket #1235.
  3. a = np.array([''abcdefgh'', e)
项目:mxnet_tk1    作者:starimpact    | 项目源码 | 文件源码
  1. def get_data(lst,preproc):
  2. data = []
  3. result = []
  4. for path in lst:
  5. f = dicom.read_file(path)
  6. img = preproc(f.pixel_array.astype(float) / np.max(f.pixel_array))
  7. dst_path = path.rsplit(".", 1)[0] + ".64x64.jpg"
  8. scipy.misc.imsave(dst_path, img)
  9. result.append(dst_path)
  10. data.append(img)
  11. data = np.array(data, dtype=np.uint8)
  12. data = data.reshape(data.size)
  13. data = np.array(data,dtype=np.str_)
  14. data = data.reshape(data.size)
  15. return [data,result]
项目:deliver    作者:orchestor    | 项目源码 | 文件源码
  1. def test_object_array_to_fixed_string(self):
  2. # Ticket #1235.
  3. a = np.array([''abcdefgh'', e)
项目:deliver    作者:orchestor    | 项目源码 | 文件源码
  1. def test_structure_format(self):
  2. dt = np.dtype([(''name'', (''grades'', np.float64, (2,))])
  3. x = np.array([(''Sarah'', (8.0, 7.0)), (''John'', (6.0, 7.0))], dtype=dt)
  4. assert_equal(np.array2string(x),
  5. "[(''Sarah'',[ 8.,7.]) (''John'',[ 6.,7.])]")
  6.  
  7. # for issue #5692
  8. A = np.zeros(shape=10, dtype=[("A", "M8[s]")])
  9. A[5:].fill(np.nan)
  10. assert_equal(np.array2string(A),
  11. "[(''1970-01-01T00:00:00'',) (''1970-01-01T00:00:00'',) " +
  12. "(''1970-01-01T00:00:00'',)\\n (''1970-01-01T00:00:00'',) (''NaT'',)\\n " +
  13. "(''NaT'',)]")
  14.  
  15. # See #8160
  16. struct_int = np.array([([1, -1], ([123,)], dtype=[(''B'', ''i4'', 2)])
  17. assert_equal(np.array2string(struct_int),
  18. "[([ 1,-1],) ([123,1],)]")
  19. struct_2dint = np.array([([[0, [2, 3]], ([[12, 0], [0, 0]],
  20. dtype=[(''B'', 2))])
  21. assert_equal(np.array2string(struct_2dint),
  22. "[([[ 0,[ 2,3]],) ([[12,0],[ 0,0]],)]")
  23.  
  24. # See #8172
  25. array_scalar = np.array(
  26. (1., 2.1234567890123456789, 3.), dtype=(''f8,f8,f8''))
  27. assert_equal(np.array2string(array_scalar), "( 1.,2.12345679,3.)")
项目:ANI1_dataset    作者:isayev    | 项目源码 | 文件源码
  1. def store_data(self, store_loc, **kwargs):
  2. """Put arrays to store
  3. """
  4. #print(store_loc)
  5. g = self.store.create_group(store_loc)
  6. for k, v, in kwargs.items():
  7. #print(type(v[0]))
  8.  
  9. #print(k)
  10. if type(v) == list:
  11. if len(v) != 0:
  12. if type(v[0]) is np.str_ or type(v[0]) is str:
  13. v = [a.encode(''utf8'') for a in v]
  14.  
  15. g.create_dataset(k, data=v, compression=self.clib, compression_opts=self.clev)
项目:Alfred    作者:jkachhadia    | 项目源码 | 文件源码
  1. def test_object_array_to_fixed_string(self):
  2. # Ticket #1235.
  3. a = np.array([''abcdefgh'', e)
项目:TDOSE    作者:kasperschmidt    | 项目源码 | 文件源码
  1. def get_datinfo(cutoutid,setupdic):
  2. """
  3. Function returning information on file names etc. for both default run and cutout run
  4.  
  5. --- INPUT ---
  6. cutoutid ID to return information for
  7. setupdic Dictionary containing the setup parameters read from the TDOSE setup file
  8.  
  9. """
  10. if cutoutid == -9999:
  11. cutstr = None
  12. imgsize = setupdic[''cutout_sizes'']
  13. refimg = setupdic[''ref_image'']
  14. datacube = setupdic[''data_cube'']
  15. variancecube = setupdic[''noise_cube'']
  16. sourcecat = setupdic[''source_catalog'']
  17. else:
  18. if type(setupdic[''cutout_sizes'']) == np.str_:
  19. sizeinfo = np.genfromtxt(setupdic[''cutout_sizes''],dtype=None,comments=''#'')
  20. objent = np.where(sizeinfo[:,0] == cutoutid)[0]
  21.  
  22. if len(objent) > 1:
  23. sys.exit('' ---> More than one match in ''+setupdic[''cutout_sizes'']+'' for object ''+str(cutoutid))
  24. elif len(objent) == 0:
  25. sys.exit('' ---> No match in ''+setupdic[''cutout_sizes'']+'' for object ''+str(cutoutid))
  26. else:
  27. imgsize = sizeinfo[objent,1:][0].astype(float).tolist()
  28. else:
  29. imgsize = setupdic[''cutout_sizes'']
  30.  
  31. cutstr = (''_id''+str(int(cutoutid))+''_cutout''+str(imgsize[0])+''x''+str(imgsize[1])+''arcsec'').replace(''.'',''p'')
  32. img_init_base = setupdic[''ref_image''].split(''/'')[-1]
  33. cube_init_base = setupdic[''data_cube''].split(''/'')[-1]
  34. var_init_base = setupdic[''variance_cube''].split(''/'')[-1]
  35.  
  36. cut_img = setupdic[''cutout_directory'']+img_init_base.replace(''.fits'',cutstr+''.fits'')
  37. cut_cube = setupdic[''cutout_directory'']+cube_init_base.replace(''.fits'',cutstr+''.fits'')
  38. cut_variance = setupdic[''cutout_directory'']+var_init_base.replace(''.fits'',cutstr+''.fits'')
  39. cut_sourcecat = setupdic[''source_catalog''].replace(''.fits'',cutstr+''.fits'')
  40.  
  41. if setupdic[''wht_image''] is None:
  42. refimg = cut_img
  43. else:
  44. wht_init_base = setupdic[''wht_image''].split(''/'')[-1]
  45. wht_img = setupdic[''cutout_directory'']+wht_init_base.replace(''.fits'',cutstr+''.fits'')
  46. refimg = [cut_img,wht_img]
  47.  
  48. datacube = cut_cube
  49. variancecube = cut_variance
  50. sourcecat = cut_sourcecat
  51.  
  52.  
  53. return cutstr, imgsize, refimg, datacube, variancecube, sourcecat
  54. # = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
  1. def _infer_dtype_from_scalar(val):
  2. """ interpret the dtype from a scalar """
  3.  
  4. dtype = np.object_
  5.  
  6. # a 1-element ndarray
  7. if isinstance(val, np.ndarray):
  8. if val.ndim != 0:
  9. raise ValueError(
  10. "invalid ndarray passed to _infer_dtype_from_scalar")
  11.  
  12. dtype = val.dtype
  13. val = val.item()
  14.  
  15. elif isinstance(val, compat.string_types):
  16.  
  17. # If we create an empty array using a string to infer
  18. # the dtype,NumPy will only allocate one character per entry
  19. # so this is kind of bad. Alternately we Could use np.repeat
  20. # instead of np.empty (but then you still don''t want things
  21. # coming out as np.str_!
  22.  
  23. dtype = np.object_
  24.  
  25. elif isinstance(val, (np.datetime64,
  26. datetime)) and getattr(val, ''tzinfo'', None) is None:
  27. val = lib.Timestamp(val).value
  28. dtype = np.dtype(''M8[ns]'')
  29.  
  30. elif isinstance(val, (np.timedelta64, timedelta)):
  31. val = tslib.convert_to_timedelta(val, ''ns'')
  32. dtype = np.dtype(''m8[ns]'')
  33.  
  34. elif is_bool(val):
  35. dtype = np.bool_
  36.  
  37. elif is_integer(val):
  38. if isinstance(val, np.integer):
  39. dtype = type(val)
  40. else:
  41. dtype = np.int64
  42.  
  43. elif is_float(val):
  44. if isinstance(val, np.floating):
  45. dtype = type(val)
  46. else:
  47. dtype = np.float64
  48.  
  49. elif is_complex(val):
  50. dtype = np.complex_
  51.  
  52. return dtype, val
项目:PoseNet    作者:bellatoris    | 项目源码 | 文件源码
  1. def make_dataset(dir, train=True):
  2. paths = None
  3. poses = None
  4. # ??? ? ??? ?
  5. for target in os.listdir(dir):
  6. target_dir = os.path.join(dir, target)
  7. # if not os.path.isdir(target_dir) or target == "Street" or target == "GreatCourt":
  8. # if not os.path.isdir(target_dir):
  9. if not target == "KingsCollege":
  10. continue
  11.  
  12. # ?? ??? ?? ??? ?? ???? ??? ? ?
  13. if train:
  14. path = np.genfromtxt(os.path.join(target_dir, ''dataset_train.txt''),
  15. dtype=np.str_, delimiter='' '', skip_header=3,
  16. usecols=[0])
  17. pose = np.genfromtxt(os.path.join(target_dir,
  18. dtype=np.float32,
  19. usecols=[1, 2, 3, 4, 5, 6, 7])
  20. else:
  21. path = np.genfromtxt(os.path.join(target_dir, ''dataset_test.txt''), 7])
  22. # order ? path ? ????? ???
  23. order = path.argsort()
  24.  
  25. # order ? sorting
  26. path1 = path[order]
  27. pose1 = pose[order]
  28.  
  29. # reverse order ?? sorting
  30. path2 = path[order[-2::-1]]
  31. pose2 = pose[order[-2::-1]]
  32.  
  33. # concat
  34. path = np.hstack((path1, path2))
  35. pose = np.vstack((pose1, pose2))
  36.  
  37. path = np.core.defchararray.add(target + ''/'', path)
  38.  
  39. if paths is None:
  40. paths = path
  41. poses = pose
  42. else:
  43. paths = np.hstack((paths, path))
  44. poses = np.vstack((poses, pose))
  45.  
  46. return paths, poses
项目:larray-editor    作者:larray-project    | 项目源码 | 文件源码
  1. def data(self, index, role=Qt.displayRole):
  2. """Cell content"""
  3. if not index.isValid():
  4. return to_qvariant()
  5. # if role == Qt.decorationRole:
  6. # return ima.icon(''editcopy'')
  7. # if role == Qt.displayRole:
  8. # return ""
  9.  
  10. if role == Qt.TextAlignmentRole:
  11. return to_qvariant(int(Qt.AlignRight | Qt.AlignVCenter))
  12. elif role == Qt.FontRole:
  13. return self.font
  14.  
  15. value = self.get_value(index)
  16. if role == Qt.displayRole:
  17. if value is np.ma.masked:
  18. return ''''
  19. # for headers
  20. elif isinstance(value, str) and not isinstance(value, np.str_):
  21. return value
  22. else:
  23. return to_qvariant(self._format % value)
  24. elif role == Qt.BackgroundColorRole:
  25. if self.bgcolor_possible and self.bg_gradient is not None and value is not np.ma.masked:
  26. if self.bg_value is None:
  27. try:
  28. v = self.color_func(value) if self.color_func is not None else value
  29. if -np.inf < v < self.vmin:
  30. # Todo: this is suboptimal,as it can reset many times (though in practice,it is usually
  31. # ok). When we get buffering,we will need to compute vmin/vmax on the whole buffer
  32. # at once,eliminating this problem (and we Could even compute final colors directly
  33. # all at once)
  34. self.vmin = v
  35. self.reset()
  36. elif self.vmax < v < np.inf:
  37. self.vmax = v
  38. self.reset()
  39. v = scale_to_01range(v, self.vmin, self.vmax)
  40. except TypeError:
  41. v = np.nan
  42. else:
  43. i, j = index.row(), index.column()
  44. v = self.bg_value[i, j]
  45. return self.bg_gradient[v]
  46. # elif role == Qt.ToolTipRole:
  47. # return to_qvariant("{}\\n{}".format(repr(value),self.get_labels(index)))
  48. return to_qvariant()
项目:hco-experiments    作者:zooniverse    | 项目源码 | 文件源码
  1. def main():
  2. parser = argparse.ArgumentParser()
  3. parser.add_argument(''file'')
  4. args = parser.parse_args()
  5. print("Using file %s" % args.file)
  6.  
  7. if not os.path.isfile(args.file):
  8. raise FileNotFoundError("Couldn''t find file at ''%s''" % args.file)
  9. if args.file.split(''.'')[-1] != ''mat'':
  10. raise ValueError("File ''%s'' not a valid mat file" % args.file)
  11.  
  12. file = args.file
  13. name = file.split(''.'')[0]
  14. outfile = ''.''.join([name, ''csv''])
  15.  
  16. data = sio.loadmat(file)
  17.  
  18. keys = [''classification_id'', ''user_name'',''user_id'',\\
  19. ''annotation'',''gold_label'',''machine_score'', \\
  20. ''diff'',''object_id'',''subject_id'',''mag'',''mag_err'']
  21.  
  22. count = 0
  23.  
  24. with open(outfile, ''w'') as csvfile:
  25. writer = csv.DictWriter(csvfile, fieldnames=keys)
  26. writer.writeheader()
  27.  
  28.  
  29. for index in range(len(data[''classification_id''][0])):
  30. d = {}
  31.  
  32. for key in keys:
  33. #print(key,data[key],type(data[key][0]))
  34. if type(data[key][0]) is numpy.str_:
  35. d[key] = data[key][index].strip()
  36. else:
  37. d[key] = data[key][0][index]
  38.  
  39.  
  40. writer.writerow(d)
  41.  
  42. sys.stdout.write("%d records processed\\r" % count)
  43. sys.stdout.flush()
  44.  
  45. count += 1
项目:WellApplication    作者:inkenbrandt    | 项目源码 | 文件源码
  1. def get_wqp_results(self, service, **kwargs):
  2. """Bring data from WQP site into a Pandas DataFrame for analysis"""
  3.  
  4. # set data types
  5. Rdtypes = {"OrganizationIdentifier": np.str_, "OrganizationFormalName": np.str_, "ActivityIdentifier": np.str_,
  6. "ActivityStartTime/Time": np.str_,
  7. "ActivityTypeCode": np.str_, "ActivityMediaName": np.str_, "ActivityMediaSubdivisionName": np.str_,
  8. "ActivityStartDate": np.str_, "ActivityStartTime/TimeZoneCode": np.str_,
  9. "ActivityEndDate": np.str_, "ActivityEndTime/Time": np.str_, "ActivityEndTime/TimeZoneCode": np.str_,
  10. "ActivityDepthHeightMeasure/MeasureValue": np.float16,
  11. "ActivityDepthHeightMeasure/MeasureUnitCode": np.str_,
  12. "ActivityDepthAltitudeReferencePointText": np.str_,
  13. "ActivityTopDepthHeightMeasure/MeasureValue": np.float16,
  14. "ActivityTopDepthHeightMeasure/MeasureUnitCode": np.str_,
  15. "ActivityBottomDepthHeightMeasure/MeasureValue": np.float16,
  16. "ActivityBottomDepthHeightMeasure/MeasureUnitCode": np.str_,
  17. "ProjectIdentifier": np.str_, "ActivityConductingOrganizationText": np.str_,
  18. "MonitoringLocationIdentifier": np.str_, "ActivityCommentText": np.str_,
  19. "SampleAquifer": np.str_, "HydrologicCondition": np.str_, "HydrologicEvent": np.str_,
  20. "SampleCollectionMethod/MethodIdentifier": np.str_,
  21. "SampleCollectionMethod/MethodIdentifierContext": np.str_,
  22. "SampleCollectionMethod/MethodName": np.str_, "SampleCollectionEquipmentName": np.str_,
  23. "ResultDetectionConditionText": np.str_, "CharacteristicName": np.str_,
  24. "ResultSampleFractionText": np.str_,
  25. "ResultMeasureValue": np.str_, "ResultMeasure/MeasureUnitCode": np.str_,
  26. "MeasureQualifierCode": np.str_,
  27. "ResultStatusIdentifier": np.str_, "StatisticalBaseCode": np.str_, "ResultValueTypeName": np.str_,
  28. "ResultWeightBasisText": np.str_, "ResultTimeBasisText": np.str_,
  29. "ResultTemperatureBasisText": np.str_,
  30. "ResultParticleSizeBasisText": np.str_, "PrecisionValue": np.str_, "ResultCommentText": np.str_,
  31. "USGSPCode": np.str_, "ResultDepthHeightMeasure/MeasureValue": np.float16,
  32. "ResultDepthHeightMeasure/MeasureUnitCode": np.str_,
  33. "ResultDepthAltitudeReferencePointText": np.str_,
  34. "SubjectTaxonomicName": np.str_, "SampleTissueAnatomyName": np.str_,
  35. "ResultAnalyticalMethod/MethodIdentifier": np.str_,
  36. "ResultAnalyticalMethod/MethodIdentifierContext": np.str_,
  37. "ResultAnalyticalMethod/MethodName": np.str_, "MethodDescriptionText": np.str_,
  38. "LaboratoryName": np.str_,
  39. "AnalysisstartDate": np.str_, "ResultLaboratoryCommentText": np.str_,
  40. "DetectionQuantitationLimitTypeName": np.str_,
  41. "DetectionQuantitationLimitMeasure/MeasureValue": np.str_,
  42. "DetectionQuantitationLimitMeasure/MeasureUnitCode": np.str_, "PreparationStartDate": np.str_,
  43. "ProviderName": np.str_}
  44.  
  45. # define date field indices
  46. dt = [6, 56, 61]
  47. csv = self.get_response(service, **kwargs).url
  48. print(csv)
  49. # read csv into DataFrame
  50. df = pd.read_csv(csv, dtype=Rdtypes, parse_dates=dt)
  51. return df

+ 不支持的操作数类型:“float”和“numpy.str_”

+ 不支持的操作数类型:“float”和“numpy.str_”

如何解决+ 不支持的操作数类型:“float”和“numpy.str_”

我有以下 2 个列表。

  1. [''4794447'',''1132804'',''1392609'',''9512999'',''2041520'',''7233323'',''2853077'',''4297617'',''1321426'',''2155664'',''13310447'',''6066387'',''3551036'',''4098927'',''1865298'',''20153634'',''1323783'',''6070500'',''4661537'',''2342299'',''1302946'',''6657982'',''2807002'',''3032171'',''5928040'',''2463431'',''6131977'',''778489'']
  2. [0.7142857142857143,0.35714285714285715,0.5138888888888888,0.4583333333333333,0.6,0.5675675675675675,0.589041095890411,0.43478260869565216,0.47368421052631576,0.68,0.622894633764199,0.5945945945945946,0.6338028169014085,0.42028985507246375,0.7464788732394366,0.47593226788432264,0.39436619718309857,0.6176470588235294,0.4142857142857143,0.618421052631579,0.5070422535211268,0.625,0.5789473684210527,0.7012987012987013,0.6533333333333333,0.43661971830985913,0.7222222222222222]

我需要计算相关性,所以我这样做了:

  1. population_by_region = result[''Population''].tolist()
  2. win_loss_by_region = result[''wl_ratio''].tolist()
  3. corr,val = stats.pearsonr(population_by_region,win_loss_by_region)

但是我得到这个不是很清楚的错误:

  1. ---------------------------------------------------------------------------
  2. TypeError Traceback (most recent call last)
  3. <ipython-input-28-37cd29ba1516> in <module>
  4. 66 print(win_loss_by_region)
  5. 67 #print(cities)
  6. ---> 68 corr,win_loss_by_region)
  7. 69
  8. 70 print(corr)
  9. /opt/conda/lib/python3.7/site-packages/scipy/stats/stats.py in pearsonr(x,y)
  10. 3403 # that the data type is at least 64 bit floating point. It might have
  11. 3404 # more precision if the input is,for example,np.longdouble.
  12. -> 3405 dtype = type(1.0 + x[0] + y[0])
  13. 3406
  14. 3407 if n == 2:
  15. TypeError: unsupported operand type(s) for +: ''float'' and ''numpy.str_''

两个列表的长度相同!

解决方法

我认为需要两个数字,所以使用:

  1. population_by_region = result[''Population''].astype(int).tolist()

也不需要转换为列表,传递两列,如:

  1. corr,val = stats.pearsonr(result[''Population''].astype(int),result[''wl_ratio''])
  2. print (corr,val)
  3. -0.04027318804589655 0.8387661496942489

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)

 

关于Python numpy 模块-str_() 实例源码python中numpy模块的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于+ 不支持的操作数类型:“float”和“numpy.str_”、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()等相关知识的信息别忘了在本站进行查找喔。

本文标签: