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