GVKun编程网logo

Python numpy 模块-string_() 实例源码(numpy fromstring)

4

以上就是给各位分享Pythonnumpy模块-string_()实例源码,其中也会对numpyfromstring进行解释,同时本文还将给你拓展Jupyter中的Numpy在打印时出错(Python版

以上就是给各位分享Python numpy 模块-string_() 实例源码,其中也会对numpy fromstring进行解释,同时本文还将给你拓展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 模块-string_() 实例源码(numpy fromstring)

Python numpy 模块-string_() 实例源码(numpy fromstring)

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

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

项目:Eskapade    作者:KaveIO    | 项目源码 | 文件源码
  1. def categorize_columns(self, df):
  2. """Categorize columns of dataframe by data type
  3.  
  4. :param df: input (pandas) data frame
  5. """
  6.  
  7. # check presence and data type of requested columns
  8. # sort columns into numerical,timestamp and category based
  9. for c in self.columns:
  10. for col in c:
  11. if col not in df.columns:
  12. raise KeyError(''column "{0:s}" not in dataframe "{1:s}"''.format(col, self.read_key))
  13. dt = self.get_data_type(df, col)
  14. if col not in self.var_dtype:
  15. self.var_dtype[col] = dt.type
  16. if (self.var_dtype[col] is np.string_) or (self.var_dtype[col] is np.object_):
  17. self.var_dtype[col] = str
  18. if not any(dt in types for types in (STRING_SUBSTR, NUMERIC_SUBSTR, TIME_SUBSTR)):
  19. raise TypeError(''cannot process column "{0:s}" of data type "{1:s}"''.format(col, str(dt)))
  20. is_number = isinstance(dt.type(), np.number)
  21. is_timestamp = isinstance(dt.type(), np.datetime64)
  22. colset = self.num_cols if is_number else self.dt_cols if is_timestamp else self.str_cols
  23. if col not in colset:
  24. colset.append(col)
  25. self.log().debug(''Data type of column "%s" is "%s"'', col, self.var_dtype[col])
项目:radar    作者:amoose136    | 项目源码 | 文件源码
  1. def add(x1, x2):
  2. """
  3. Return element-wise string concatenation for two arrays of str or unicode.
  4.  
  5. Arrays `x1` and `x2` must have the same shape.
  6.  
  7. Parameters
  8. ----------
  9. x1 : array_like of str or unicode
  10. Input array.
  11. x2 : array_like of str or unicode
  12. Input array.
  13.  
  14. Returns
  15. -------
  16. add : ndarray
  17. Output array of `string_` or `unicode_`,depending on input types
  18. of the same shape as `x1` and `x2`.
  19.  
  20. """
  21. arr1 = numpy.asarray(x1)
  22. arr2 = numpy.asarray(x2)
  23. out_size = _get_num_chars(arr1) + _get_num_chars(arr2)
  24. dtype = _use_unicode(arr1, arr2)
  25. return _vec_string(arr1, (dtype, out_size), ''__add__'', (arr2,))
项目:radar    作者:amoose136    | 项目源码 | 文件源码
  1. def test_from_string_array(self):
  2. A = np.array(asbytes_nested([[''abc'', ''foo''],
  3. [''long '', ''0123456789'']]))
  4. assert_equal(A.dtype.type, np.string_)
  5. B = np.char.array(A)
  6. assert_array_equal(B, A)
  7. assert_equal(B.dtype, A.dtype)
  8. assert_equal(B.shape, A.shape)
  9. B[0, 0] = ''changed''
  10. assert_(B[0, 0] != A[0, 0])
  11. C = np.char.asarray(A)
  12. assert_array_equal(C, A)
  13. assert_equal(C.dtype, A.dtype)
  14. C[0, 0] = ''changed again''
  15. assert_(C[0, 0] != B[0, 0])
  16. assert_(C[0, 0] == A[0, 0])
项目:radar    作者:amoose136    | 项目源码 | 文件源码
  1. def test_ljust(self):
  2. assert_(issubclass(self.A.ljust(10).dtype.type, np.string_))
  3.  
  4. C = self.A.ljust([10, 20])
  5. assert_array_equal(np.char.str_len(C), [[10, 20], [10, [12, 20]])
  6.  
  7. C = self.A.ljust(20, asbytes(''#''))
  8. assert_array_equal(C.startswith(asbytes(''#'')), [
  9. [False, True], [False, False], False]])
  10. assert_(np.all(C.endswith(asbytes(''#''))))
  11.  
  12. C = np.char.ljust(asbytes(''FOO''), [15, 8]])
  13. tgt = asbytes_nested([[''FOO '', ''FOO ''],
  14. [''FOO '', ''FOO '']])
  15. assert_(issubclass(C.dtype.type, np.string_))
  16. assert_array_equal(C, tgt)
项目:radar    作者:amoose136    | 项目源码 | 文件源码
  1. def test_lstrip(self):
  2. tgt = asbytes_nested([[''abc '', ''''],
  3. [''12345'', ''MixedCase''],
  4. [''123 \\t 345 \\0 '', ''UPPER'']])
  5. assert_(issubclass(self.A.lstrip().dtype.type, np.string_))
  6. assert_array_equal(self.A.lstrip(), tgt)
  7.  
  8. tgt = asbytes_nested([['' abc'',
  9. [''2345'', ''ixedCase''],
  10. [''23 \\t 345 \\x00'', ''UPPER'']])
  11. assert_array_equal(self.A.lstrip(asbytes_nested([''1'', ''M''])), tgt)
  12.  
  13. tgt = [[sixu(''\\u03a3 ''),
  14. [''12345'',
  15. [''123 \\t 345 \\0 '', ''UPPER'']]
  16. assert_(issubclass(self.B.lstrip().dtype.type, np.unicode_))
  17. assert_array_equal(self.B.lstrip(), tgt)
项目:radar    作者:amoose136    | 项目源码 | 文件源码
  1. def test_rstrip(self):
  2. assert_(issubclass(self.A.rstrip().dtype.type, np.string_))
  3.  
  4. tgt = asbytes_nested([['' abc'',
  5. [''123 \\t 345'', ''UPPER'']])
  6. assert_array_equal(self.A.rstrip(), tgt)
  7.  
  8. tgt = asbytes_nested([['' abc '',
  9. [''1234'',
  10. [''123 \\t 345 \\x00'', ''UPP'']
  11. ])
  12. assert_array_equal(self.A.rstrip(asbytes_nested([''5'', ''ER''])), tgt)
  13.  
  14. tgt = [[sixu('' \\u03a3''),
  15. [''123 \\t 345'', ''UPPER'']]
  16. assert_(issubclass(self.B.rstrip().dtype.type, np.unicode_))
  17. assert_array_equal(self.B.rstrip(), tgt)
项目:radar    作者:amoose136    | 项目源码 | 文件源码
  1. def test_strip(self):
  2. tgt = asbytes_nested([[''abc'', ''UPPER'']])
  3. assert_(issubclass(self.A.strip().dtype.type, np.string_))
  4. assert_array_equal(self.A.strip(),
  5. [''234'', ''ixedCas''], ''UPP'']])
  6. assert_array_equal(self.A.strip(asbytes_nested([''15'', ''EReM''])), tgt)
  7.  
  8. tgt = [[sixu(''\\u03a3''), ''UPPER'']]
  9. assert_(issubclass(self.B.strip().dtype.type, np.unicode_))
  10. assert_array_equal(self.B.strip(), tgt)
项目:kripodb    作者:3D-e-Chem    | 项目源码 | 文件源码
  1. def from_array(self, data, labels):
  2. """Fill matrix from 2 dimensional array
  3.  
  4. Args:
  5. data (np.array): 2 dimensional square array with scores
  6. labels (list): List of labels for each column and row index
  7. """
  8. labels = [np.string_(d) for d in labels]
  9. self.labels = self.h5file.create_carray(''/'', ''labels'', obj=labels, filters=self.filters)
  10. self.h5file.flush()
  11. self.build_label_cache()
  12.  
  13. nr_frags = len(labels)
  14. self.scores = self.h5file.create_carray(''/'', ''scores'', atom=tables.UInt16Atom(),
  15. shape=(nr_frags, nr_frags), chunkshape=(1,
  16. filters=self.filters)
  17. self.scores[0:nr_frags, 0:nr_frags] = (data * self.score_precision).astype(''uint16'')
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
  1. def add(x1,))
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
  1. def test_from_string_array(self):
  2. A = np.array(asbytes_nested([[''abc'', 0])
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
  1. def test_ljust(self):
  2. assert_(issubclass(self.A.ljust(10).dtype.type, tgt)
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
  1. def test_lstrip(self):
  2. tgt = asbytes_nested([[''abc '', tgt)
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
  1. def test_rstrip(self):
  2. assert_(issubclass(self.A.rstrip().dtype.type, tgt)
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
  1. def test_strip(self):
  2. tgt = asbytes_nested([[''abc'', tgt)
项目:BetaElephant    作者:milkpku    | 项目源码 | 文件源码
  1. def fen2state(fen):
  2. ''''''
  3. transfer the fen string to chessboard
  4. fen: fen string
  5. return: state of the chessboard
  6. ''''''
  7. fenstrlist = fen.split()
  8. cstate = chessboradstate()
  9. cstate.state = np.zeros([10, 9], np.string_)
  10. fenstr1st = fenstrlist[0].split(''/'')
  11. for i in range(len(fenstr1st)):
  12. current = 0
  13. for j in range(len(fenstr1st[i])):
  14. if fenstr1st[i][j].isdigit():
  15. num = int(fenstr1st[i][j])
  16. for k in range(num):
  17. cstate.state[i][current+k] = '' ''
  18. current += num
  19. else:
  20. cstate.state[i][current] = fenstr1st[i][j]
  21. current += 1
  22. cstate.turn = fenstrlist[1]
  23. cstate.roundcnt = int(fenstrlist[5])
  24. return cstate
项目:BetaElephant    作者:milkpku    | 项目源码 | 文件源码
  1. def move(cstate, move):
  2. ''''''
  3. move the chess according to the move action
  4. state: the current chessborad,numpy.array[10][9],dtype=string_
  5. move: the action to move,string format as:''D5-E5''
  6. ''''''
  7. src = []
  8. des = []
  9. src.append(9 - int(move[1]))
  10. src.append(ord(move[0]) - ord(''A''))
  11. des.append(9 - int(move[4]))
  12. des.append(ord(move[3]) - ord(''A''))
  13. # print src,des
  14. chess = cstate.state[src[0]][src[1]]
  15. cstate.state[src[0]][src[1]] = '' ''
  16. cstate.state[des[0]][des[1]] = chess
  17. cstate.roundcnt += 1
  18. if cstate.turn == ''b'':
  19. cstate.turn = ''w''
  20. else:
  21. cstate.turn = ''b''
项目:theanomodels    作者:clinicalml    | 项目源码 | 文件源码
  1. def saveSparseHDF5(matrix, prefix, fname):
  2. """ matrix: sparse matrix
  3. prefix: prefix of dataset
  4. fname : name of h5py file where matrix will be saved
  5. """
  6. assert matrix.__class__==csr_matrix or matrix.__class__==csc_matrix,''Expecting csc/csr''
  7. with h5py.File(fname,mode=''a'') as f:
  8. for info in [''data'',''indices'',''indptr'',''shape'']:
  9. key = ''%s_%s''%(prefix,info)
  10. try:
  11. data = getattr(matrix, info)
  12. except:
  13. assert False,''Expecting attribute ''+info+'' in matrix''
  14. """
  15. For empty arrays,data,indicies and indptr will be []
  16. To deal w/ this use np.nan in its place
  17. """
  18. if len(data)==0:
  19. f.create_dataset(key,data=np.array([np.nan]))
  20. else:
  21. f.create_dataset(key,data= data)
  22. key = prefix+''_type''
  23. val = matrix.__class__.__name__
  24. f.attrs[key] = np.string_(val)
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
  1. def test_select_dtypes_str_raises(self):
  2. df = DataFrame({''a'': list(''abc''),
  3. ''g'': list(u(''abc'')),
  4. ''b'': list(range(1, 4)),
  5. ''c'': np.arange(3, 6).astype(''u1''),
  6. ''d'': np.arange(4.0, 7.0, dtype=''float64''),
  7. ''e'': [True, False,
  8. ''f'': pd.date_range(''Now'', periods=3).values})
  9. string_dtypes = set((str, ''str'', np.string_, ''S1'',
  10. ''unicode'', np.unicode_, ''U1''))
  11. try:
  12. string_dtypes.add(unicode)
  13. except NameError:
  14. pass
  15. for dt in string_dtypes:
  16. with tm.assertRaisesRegexp(TypeError,
  17. ''string dtypes are not allowed''):
  18. df.select_dtypes(include=[dt])
  19. with tm.assertRaisesRegexp(TypeError,
  20. ''string dtypes are not allowed''):
  21. df.select_dtypes(exclude=[dt])
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
  1. def add(x1,))
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
  1. def test_from_string_array(self):
  2. A = np.array(asbytes_nested([[''abc'', 0])
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
  1. def test_join(self):
  2. if sys.version_info[0] >= 3:
  3. # NOTE: list(b''123'') == [49,50,51]
  4. # so that b'',''.join(b''123'') results to an error on Py3
  5. A0 = self.A.decode(''ascii'')
  6. else:
  7. A0 = self.A
  8.  
  9. A = np.char.join(['','', ''#''], A0)
  10. if sys.version_info[0] >= 3:
  11. assert_(issubclass(A.dtype.type, np.unicode_))
  12. else:
  13. assert_(issubclass(A.dtype.type, np.string_))
  14. tgt = np.array([['',a,b,c,
  15. [''1,2,3,4,5'', ''M#i#x#e#d#C#a#s#e''],\\t,5,\\x00, ''U#P#P#E#R'']])
  16. assert_array_equal(np.char.join(['', A0), tgt)
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
  1. def test_ljust(self):
  2. assert_(issubclass(self.A.ljust(10).dtype.type, tgt)
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
  1. def test_rjust(self):
  2. assert_(issubclass(self.A.rjust(10).dtype.type, np.string_))
  3.  
  4. C = self.A.rjust([10, 20]])
  5.  
  6. C = self.A.rjust(20, asbytes(''#''))
  7. assert_(np.all(C.startswith(asbytes(''#''))))
  8. assert_array_equal(C.endswith(asbytes(''#'')),
  9. [[False, False]])
  10.  
  11. C = np.char.rjust(asbytes(''FOO''), 8]])
  12. tgt = asbytes_nested([['' FOO'', '' FOO''],
  13. ['' FOO'', '' FOO'']])
  14. assert_(issubclass(C.dtype.type, tgt)
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
  1. def test_rstrip(self):
  2. assert_(issubclass(self.A.rstrip().dtype.type, tgt)
项目:aws-lambda-numpy    作者:vitolimandibhrata    | 项目源码 | 文件源码
  1. def add(x1,))
项目:aws-lambda-numpy    作者:vitolimandibhrata    | 项目源码 | 文件源码
  1. def test_from_string_array(self):
  2. A = np.array(asbytes_nested([[''abc'', 0])
项目:aws-lambda-numpy    作者:vitolimandibhrata    | 项目源码 | 文件源码
  1. def test_ljust(self):
  2. assert_(issubclass(self.A.ljust(10).dtype.type, tgt)
项目:aws-lambda-numpy    作者:vitolimandibhrata    | 项目源码 | 文件源码
  1. def test_lstrip(self):
  2. tgt = asbytes_nested([[''abc '', tgt)
项目:aws-lambda-numpy    作者:vitolimandibhrata    | 项目源码 | 文件源码
  1. def test_rstrip(self):
  2. assert_(issubclass(self.A.rstrip().dtype.type, tgt)
项目:aws-lambda-numpy    作者:vitolimandibhrata    | 项目源码 | 文件源码
  1. def test_strip(self):
  2. tgt = asbytes_nested([[''abc'', tgt)
项目:fbpic    作者:fbpic    | 项目源码 | 文件源码
  1. def setup_openpmd_meshes_group( self, dset ) :
  2. """
  3. Set the attributes that are specific to the mesh path
  4.  
  5. Parameter
  6. ---------
  7. dset : an h5py.Group object that contains all the mesh quantities
  8. """
  9. # Field Solver
  10. dset.attrs["fieldSolver"] = np.string_("PSATD")
  11. # Field boundary
  12. dset.attrs["fieldBoundary"] = np.array([
  13. np.string_("reflecting"), np.string_("reflecting"),
  14. np.string_("reflecting"), np.string_("reflecting") ])
  15. # Particle boundary
  16. dset.attrs["particleBoundary"] = np.array([
  17. np.string_("absorbing"), np.string_("absorbing"),
  18. np.string_("absorbing"), np.string_("absorbing") ])
  19. # Current Smoothing
  20. dset.attrs["currentSmoothing"] = np.string_("Binomial")
  21. dset.attrs["currentSmoothingParameters"] = \\
  22. np.string_("period=1;numPasses=1;compensator=false")
  23. # Charge correction
  24. dset.attrs["chargeCorrection"] = np.string_("spectral")
  25. dset.attrs["chargeCorrectionParameters"] = np.string_("period=1")
项目:lambda-numba    作者:rlhotovy    | 项目源码 | 文件源码
  1. def add(x1,))
项目:lambda-numba    作者:rlhotovy    | 项目源码 | 文件源码
  1. def test_from_string_array(self):
  2. A = np.array(asbytes_nested([[''abc'', 0])
项目:lambda-numba    作者:rlhotovy    | 项目源码 | 文件源码
  1. def test_ljust(self):
  2. assert_(issubclass(self.A.ljust(10).dtype.type, tgt)
项目:lambda-numba    作者:rlhotovy    | 项目源码 | 文件源码
  1. def test_lstrip(self):
  2. tgt = asbytes_nested([[''abc '', tgt)
项目:lambda-numba    作者:rlhotovy    | 项目源码 | 文件源码
  1. def test_rstrip(self):
  2. assert_(issubclass(self.A.rstrip().dtype.type, tgt)
项目:lambda-numba    作者:rlhotovy    | 项目源码 | 文件源码
  1. def test_strip(self):
  2. tgt = asbytes_nested([[''abc'', tgt)
项目:deliver    作者:orchestor    | 项目源码 | 文件源码
  1. def add(x1,))
项目:deliver    作者:orchestor    | 项目源码 | 文件源码
  1. def test_from_string_array(self):
  2. A = np.array(asbytes_nested([[''abc'', 0])
项目:deliver    作者:orchestor    | 项目源码 | 文件源码
  1. def test_ljust(self):
  2. assert_(issubclass(self.A.ljust(10).dtype.type, tgt)
项目:deliver    作者:orchestor    | 项目源码 | 文件源码
  1. def test_lstrip(self):
  2. tgt = asbytes_nested([[''abc '', tgt)
项目:deliver    作者:orchestor    | 项目源码 | 文件源码
  1. def test_rstrip(self):
  2. assert_(issubclass(self.A.rstrip().dtype.type, tgt)
项目:deliver    作者:orchestor    | 项目源码 | 文件源码
  1. def test_strip(self):
  2. tgt = asbytes_nested([[''abc'', tgt)
项目:scanpy    作者:theislab    | 项目源码 | 文件源码
  1. def preprocess_writing(key, value):
  2. if isinstance(value, dict):
  3. # hack for storing dicts
  4. value = np.array([str(value)])
  5. else:
  6. value = np.array(value)
  7. if value.ndim == 0:
  8. value = np.array([value])
  9. # some output about the data to write
  10. logg.m(key, type(value),
  11. value.dtype, value.dtype.kind, value.shape,
  12. v=6)
  13. # make sure string format is chosen correctly
  14. if value.dtype.kind == ''U'':
  15. value = value.astype(np.string_)
  16. return key, value

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 模块-string_() 实例源码numpy fromstring的分享就到这里,谢谢您的阅读,如果想了解更多关于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 ()、数组基本属性的相关信息,可以在本站进行搜索。

本文标签: