GVKun编程网logo

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

3

如果您想了解Pythonnumpy模块-ediff1d()实例源码的相关知识,那么本文是一篇不可错过的文章,我们将对python中numpy模块进行全面详尽的解释,并且为您提供关于Jupyter中的N

如果您想了解Python numpy 模块-ediff1d() 实例源码的相关知识,那么本文是一篇不可错过的文章,我们将对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 模块-ediff1d() 实例源码(python中numpy模块)

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

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

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

项目:astronomy-utilities    作者:astronomeralex    | 项目源码 | 文件源码
  1. def eta(radii, phot):
  2. """
  3. eta = I(r) / \\bar{I}(<r)
  4.  
  5. radii -- 1d array of aperture photometry radii
  6. phot -- 1d array of aperture photometry fluxes
  7.  
  8. this is currently calculated quite naively,and probably Could be done better
  9. """
  10. phot_area = np.pi * radii**2
  11. phot_area_diff = np.ediff1d(phot_area, to_begin=phot_area[0])
  12. I_bar = phot / (phot_area)
  13. I_delta_r = np.ediff1d(phot, to_begin=phot[0]) / phot_area_diff
  14. I_r = (I_delta_r[:-1] + I_delta_r[1:]) / 2 #lost last array element here
  15. I_r = np.append(I_r, I_delta_r[-1]) #added it back in here
  16. eta = I_r / I_bar
  17. return eta
项目:ghetto_omr    作者:pohzhiee    | 项目源码 | 文件源码
  1. def SpaceFunc(val_x_array,val_y_array):
  2. spa_X_array = np.ediff1d(val_x_array)
  3. spa_Y_array = np.ediff1d(val_y_array)
  4.  
  5. return spa_X_array,spa_Y_array
  6.  
  7. #Fucntion to convert matrix to binary (those with value to 1,those with 0 to 0)
项目:ghetto_omr    作者:pohzhiee    | 项目源码 | 文件源码
  1. def SpaceFunc(matr):
  2. matr_shape = matr.shape
  3. spa_X_array = np.array([])
  4. spa_Y_array = np.array([])
  5. val_X_matrix = np.zeros((matr_shape[0], matr_shape[1]), dtype=np.ndarray)
  6. val_Y_matrix = np.zeros((matr_shape[0], dtype=np.ndarray)
  7. val_X_matrix_counter = np.zeros((matr_shape[0], dtype=np.ndarray)
  8. val_Y_matrix_counter=np.zeros((matr_shape[0], dtype=np.ndarray)
  9.  
  10.  
  11. counter_g1 = 0
  12. while counter_g1 < matr_shape[1]:
  13. counter_g2 = 0
  14. while counter_g2 < matr_shape[0]:
  15. matr_value = matr[counter_g2, counter_g1]
  16. matr_value=np.asarray(matr_value)
  17.  
  18. if matr_value.size==3:
  19. val_X_matrix[counter_g2, counter_g1] = matr_value[0]
  20. val_Y_matrix[counter_g2, counter_g1] = matr_value[1]
  21. val_X_matrix_counter[counter_g2, counter_g1] = 1
  22. val_Y_matrix_counter[counter_g2, counter_g1] = 1
  23. elif matr_value.size == 0:
  24. val_X_matrix[counter_g2, counter_g1] = 0
  25. val_Y_matrix[counter_g2, counter_g1] = 0
  26. val_X_matrix_counter[counter_g2, counter_g1] = 0
  27. val_Y_matrix_counter[counter_g2, counter_g1] = 0
  28. counter_g2 = counter_g2 + 1
  29. counter_g1 = counter_g1 + 1
  30.  
  31. val_X_array_counter = val_X_matrix_counter.sum(axis=0)
  32. val_Y_array_counter = val_Y_matrix_counter.sum(axis=1)
  33. val_X_array_acc = val_X_matrix.sum(axis=0)
  34. val_Y_array_acc=val_Y_matrix.sum(axis=1)
  35. val_X_array = val_X_array_acc/val_X_array_counter
  36. val_Y_array = val_Y_array_acc / val_Y_array_counter
  37.  
  38. spa_X_array=np.ediff1d(val_X_array)
  39. spa_Y_array=np.ediff1d(val_Y_array)
  40.  
  41. #Creating function to convert matrix to binary (those with value to 1,those with 0 to 0)
项目:ghetto_omr    作者:pohzhiee    | 项目源码 | 文件源码
  1. def SpaceFunc(matr):
  2. matr_shape = matr.shape
  3. spa_X_array = np.array([])
  4. spa_Y_array = np.array([])
  5. val_X_matrix = np.zeros((matr_shape[0],those with 0 to 0)
项目:ECNN    作者:alazareva    | 项目源码 | 文件源码
  1. def learning_rate(lr=LEARNING_RATE):
  2. decrease_rate = 0.75
  3. lr = lr
  4. window = []
  5. window_size = 5
  6. def f(loss = float(''inf'')):
  7. nonlocal window
  8. nonlocal lr
  9. nonlocal window_size
  10. window.append(loss)
  11. if len(window) == window_size:
  12. diffs = np.ediff1d(window)
  13. if np.all(abs(diffs) > np.array(window[:-1])*0.05) and np.mean(diffs > 0) >= 0.5: # if large loss
  14. # fluctuations
  15. print("fluctuating", window)
  16. lr *= decrease_rate
  17. window = []
  18. elif np.all(abs(diffs) < np.array(window[:-1])*0.01) and np.all(diffs < 0): # if decreased by
  19. # small amount
  20. print("too slow", window)
  21. lr *= 1/decrease_rate
  22. window = []
  23. else:
  24. window.pop(0)
  25. return lr
  26. return f
项目:ECNN    作者:alazareva    | 项目源码 | 文件源码
  1. def stopping_rule():
  2. window = []
  3. window_size = 5
  4. def c(val_acc):
  5. nonlocal window
  6. nonlocal window_size
  7. print(''acc'', val_acc)
  8. window.append(val_acc)
  9. if len(window) == window_size:
  10. diffs = np.ediff1d(window)
  11. if np.all(diffs < 0):
  12. return True
  13. window.pop(0)
  14. return False
  15. return c
项目:radar    作者:amoose136    | 项目源码 | 文件源码
  1. def ediff1d(ary, to_end=None, to_begin=None):
  2. """
  3. The differences between consecutive elements of an array.
  4.  
  5. Parameters
  6. ----------
  7. ary : array_like
  8. If necessary,will be flattened before the differences are taken.
  9. to_end : array_like,optional
  10. Number(s) to append at the end of the returned differences.
  11. to_begin : array_like,optional
  12. Number(s) to prepend at the beginning of the returned differences.
  13.  
  14. Returns
  15. -------
  16. ediff1d : ndarray
  17. The differences. Loosely,this is ``ary.flat[1:] - ary.flat[:-1]``.
  18.  
  19. See Also
  20. --------
  21. diff,gradient
  22.  
  23. Notes
  24. -----
  25. When applied to masked arrays,this function drops the mask information
  26. if the `to_begin` and/or `to_end` parameters are used.
  27.  
  28. Examples
  29. --------
  30. >>> x = np.array([1,2,4,7,0])
  31. >>> np.ediff1d(x)
  32. array([ 1,3,-7])
  33.  
  34. >>> np.ediff1d(x,to_begin=-99,to_end=np.array([88,99]))
  35. array([-99,1,-7,88,99])
  36.  
  37. The returned array is always 1D.
  38.  
  39. >>> y = [[1,4],[1,6,24]]
  40. >>> np.ediff1d(y)
  41. array([ 1,-3,5,18])
  42.  
  43. """
  44. ary = np.asanyarray(ary).flat
  45. ed = ary[1:] - ary[:-1]
  46. arrays = [ed]
  47. if to_begin is not None:
  48. arrays.insert(0, to_begin)
  49. if to_end is not None:
  50. arrays.append(to_end)
  51.  
  52. if len(arrays) != 1:
  53. # We''ll save ourselves a copy of a potentially large array in
  54. # the common case where neither to_begin or to_end was given.
  55. ed = np.hstack(arrays)
  56.  
  57. return ed
项目:radar    作者:amoose136    | 项目源码 | 文件源码
  1. def setxor1d(ar1, ar2, assume_unique=False):
  2. """
  3. Find the set exclusive-or of two arrays.
  4.  
  5. Return the sorted,unique values that are in only one (not both) of the
  6. input arrays.
  7.  
  8. Parameters
  9. ----------
  10. ar1,ar2 : array_like
  11. Input arrays.
  12. assume_unique : bool
  13. If True,the input arrays are both assumed to be unique,which
  14. can speed up the calculation. Default is False.
  15.  
  16. Returns
  17. -------
  18. setxor1d : ndarray
  19. Sorted 1D array of unique values that are in only one of the input
  20. arrays.
  21.  
  22. Examples
  23. --------
  24. >>> a = np.array([1,4])
  25. >>> b = np.array([2,5])
  26. >>> np.setxor1d(a,b)
  27. array([1,7])
  28.  
  29. """
  30. if not assume_unique:
  31. ar1 = unique(ar1)
  32. ar2 = unique(ar2)
  33.  
  34. aux = np.concatenate((ar1, ar2))
  35. if aux.size == 0:
  36. return aux
  37.  
  38. aux.sort()
  39. # flag = ediff1d( aux,to_end = 1,to_begin = 1 ) == 0
  40. flag = np.concatenate(([True], aux[1:] != aux[:-1], [True]))
  41. # flag2 = ediff1d( flag ) == 0
  42. flag2 = flag[1:] == flag[:-1]
  43. return aux[flag2]
项目:lineage    作者:apriha    | 项目源码 | 文件源码
  1. def _compute_snp_distances(self, df, build):
  2. if build == 36:
  3. hapmap = self._resources.get_hapmap_h36()
  4. else:
  5. hapmap = self._resources.get_hapmap_h37()
  6.  
  7. for chrom in df[''chrom''].unique():
  8. if chrom not in hapmap.keys():
  9. continue
  10.  
  11. # create a new dataframe from the positions for the current chromosome
  12. temp = pd.DataFrame(df.loc[(df[''chrom''] == chrom)][''pos''].values, columns=[''pos''])
  13.  
  14. # merge HapMap for this chrom
  15. temp = temp.append(hapmap[chrom], ignore_index=True)
  16.  
  17. # sort based on pos
  18. temp = temp.sort_values(''pos'')
  19.  
  20. # fill cM rates forward and backward
  21. temp[''rate''] = temp[''rate''].fillna(method=''ffill'')
  22. temp[''rate''] = temp[''rate''].fillna(method=''bfill'')
  23.  
  24. # get difference between positions
  25. pos_diffs = np.ediff1d(temp[''pos''])
  26.  
  27. # compute cMs between each pos based on probabilistic recombination rate
  28. # https://www.biostars.org/p/123539/
  29. cMs_match_segment = (temp[''rate''] * np.r_[pos_diffs, 0] / 1e6).values
  30.  
  31. # add back into temp
  32. temp[''cMs''] = np.r_[0, cMs_match_segment][:-1]
  33.  
  34. temp = temp.reset_index()
  35. del temp[''index'']
  36.  
  37. # use null `map` values to find locations of SNPs
  38. snp_indices = temp.loc[temp[''map''].isnull()].index
  39.  
  40. # use SNP indices to determine boundaries over which to sum cMs
  41. start_snp_ix = snp_indices + 1
  42. end_snp_ix = np.r_[snp_indices, snp_indices[-1]][1:] + 1
  43. snp_boundaries = np.c_[start_snp_ix, end_snp_ix]
  44.  
  45. # sum cMs between SNPs to get total cM distance between SNPs
  46. # http://stackoverflow.com/a/7471967
  47. c = np.r_[0, temp[''cMs''].cumsum()][snp_boundaries]
  48. cM_from_prev_snp = c[:, 1] - c[:, 0]
  49.  
  50. # debug
  51. # temp.loc[snp_indices,''cM_from_prev_snp''] = np.r_[0,cM_from_prev_snp][:-1]
  52. # temp.to_csv(''debug.csv'')
  53.  
  54. # add back into df
  55. df.loc[(df[''chrom''] == chrom), ''cM_from_prev_snp''] = np.r_[0, cM_from_prev_snp][:-1]
  56.  
  57. return hapmap, df
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
  1. def ediff1d(ary, to_begin)
  2. if to_end is not None:
  3. arrays.append(to_end)
  4.  
  5. if len(arrays) != 1:
  6. # We''ll save ourselves a copy of a potentially large array in
  7. # the common case where neither to_begin or to_end was given.
  8. ed = np.hstack(arrays)
  9.  
  10. return ed
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
  1. def setxor1d(ar1, [True]))
  2. # flag2 = ediff1d( flag ) == 0
  3. flag2 = flag[1:] == flag[:-1]
  4. return aux[flag2]
项目:aws-lambda-numpy    作者:vitolimandibhrata    | 项目源码 | 文件源码
  1. def ediff1d(ary, to_begin)
  2. if to_end is not None:
  3. arrays.append(to_end)
  4.  
  5. if len(arrays) != 1:
  6. # We''ll save ourselves a copy of a potentially large array in
  7. # the common case where neither to_begin or to_end was given.
  8. ed = np.hstack(arrays)
  9.  
  10. return ed
项目:aws-lambda-numpy    作者:vitolimandibhrata    | 项目源码 | 文件源码
  1. def setxor1d(ar1, [True]))
  2. # flag2 = ediff1d( flag ) == 0
  3. flag2 = flag[1:] == flag[:-1]
  4. return aux[flag2]
项目:qudi    作者:Ulm-IQO    | 项目源码 | 文件源码
  1. def estimate_baresine(self, x_axis, data, params):
  2. """ Bare sine estimator with a frequency and phase.
  3.  
  4. @param numpy.array x_axis: 1D axis values
  5. @param numpy.array data: 1D data,should have the same dimension as x_axis.
  6. @param lmfit.Parameters params: object includes parameter dictionary which
  7. can be set
  8.  
  9. @return tuple (error,params):
  10.  
  11. Explanation of the return parameter:
  12. int error: error code (0:OK,-1:error)
  13. lmfit.Parameters params: derived OrderedDict object contains the initial
  14. values for the fit.
  15. """
  16.  
  17. # Convert for safety:
  18. x_axis = np.array(x_axis)
  19. data = np.array(data)
  20.  
  21. error = self._check_1D_input(x_axis=x_axis, data=data, params=params)
  22.  
  23. # calculate dft with zeropadding to obtain nicer interpolation between the
  24. # appearing peaks.
  25. dft_x, dft_y = compute_ft(x_axis, zeropad_num=1)
  26.  
  27. stepsize = x_axis[1]-x_axis[0] # for frequency axis
  28. frequency_max = np.abs(dft_x[np.log(dft_y).argmax()])
  29.  
  30. # find minimal distance to the next meas point in the corresponding time value>
  31. min_x_diff = np.ediff1d(x_axis).min()
  32.  
  33. # How many points are used to sample the estimated frequency with min_x_diff:
  34. iter_steps = int(1/(frequency_max*min_x_diff))
  35. if iter_steps < 1:
  36. iter_steps = 1
  37.  
  38. sum_res = np.zeros(iter_steps)
  39.  
  40. # Procedure: Create sin waves with different phases and perform a summation.
  41. # The sum shows how well the sine was fitting to the actual data.
  42. # The best fitting sine should be a maximum of the summed time
  43. # trace.
  44.  
  45. for iter_s in range(iter_steps):
  46. func_val = np.sin(2*np.pi*frequency_max*x_axis + iter_s/iter_steps *2*np.pi)
  47. sum_res[iter_s] = np.abs(data - func_val).sum()
  48.  
  49. # The minimum indicates where the sine function was fittng the worst,
  50. # therefore subtract pi. This will also ensure that the estimated phase will
  51. # be in the interval [-pi,pi].
  52. phase = sum_res.argmax()/iter_steps *2*np.pi - np.pi
  53.  
  54. params[''frequency''].set(value=frequency_max, min=0.0, max=1/(stepsize)*3)
  55. params[''phase''].set(value=phase, min=-np.pi, max=np.pi)
  56.  
  57. return error, params
项目:qudi    作者:Ulm-IQO    | 项目源码 | 文件源码
  1. def sine_testing2():
  2. """ Sinus fit testing with the direct fit method. """
  3.  
  4.  
  5. x_axis = np.linspace(0, 250, 75)
  6. x_axis1 = np.linspace(250, 500, 75)
  7. x_axis = np.append(x_axis, x_axis1)
  8. x_nice = np.linspace(x_axis[0],x_axis[-1], 1000)
  9.  
  10.  
  11. mod, params = qudi_fitting.make_sine_model()
  12.  
  13. params[''phase''].value = np.pi/2 # np.random.uniform()*2*np.pi
  14. params[''frequency''].value = 0.01
  15. params[''amplitude''].value = 1.5
  16. params[''offset''].value = 0.4
  17.  
  18. data = mod.eval(x=x_axis, params=params)
  19. data_noisy = (mod.eval(x=x_axis, params=params)
  20. + 1.5* np.random.normal(size=x_axis.shape))
  21.  
  22. # sorted_indices = x_axis.argsort()
  23. # x_axis = x_axis[sorted_indices]
  24. # data = data[sorted_indices]
  25. # diff_array = np.ediff1d(x_axis)
  26. # print(diff_array)
  27. # print(diff_array.min())
  28. # min_x_diff = diff_array.min()
  29. # if np.isclose(min_x_diff,0.0):
  30. # index = np.argmin(diff_array)
  31. # print(''index'',index)
  32. # diff_array = np.delete(diff_array,index)
  33. # print(''diff_array'',diff_array)
  34.  
  35. update_dict = {}
  36. update_dict[''phase''] = {''vary'': False, ''value'': np.pi/2.}
  37.  
  38. result = qudi_fitting.make_sine_fit(x_axis=x_axis, data=data_noisy,
  39. add_params=update_dict)
  40.  
  41.  
  42. plt.figure()
  43. # plt.plot(x_axis,data,''simulate data'')
  44. plt.plot(x_axis, data_noisy, label=''noisy data'')
  45. plt.plot(x_axis, result.init_fit, label=''initial data'')
  46. plt.plot(x_axis, result.best_fit, label=''fit data'')
  47. plt.xlabel(''time'')
  48. plt.ylabel(''signal'')
  49. plt.legend(bBox_to_anchor=(0., 1.02, 1., .102), loc=3,
  50. ncol=2, mode="expand", borderaxespad=0.)
  51. plt.show()
项目:lambda-numba    作者:rlhotovy    | 项目源码 | 文件源码
  1. def ediff1d(ary, to_begin)
  2. if to_end is not None:
  3. arrays.append(to_end)
  4.  
  5. if len(arrays) != 1:
  6. # We''ll save ourselves a copy of a potentially large array in
  7. # the common case where neither to_begin or to_end was given.
  8. ed = np.hstack(arrays)
  9.  
  10. return ed
项目:lambda-numba    作者:rlhotovy    | 项目源码 | 文件源码
  1. def setxor1d(ar1, [True]))
  2. # flag2 = ediff1d( flag ) == 0
  3. flag2 = flag[1:] == flag[:-1]
  4. return aux[flag2]
项目:deliver    作者:orchestor    | 项目源码 | 文件源码
  1. def setxor1d(ar1, [True]))
  2. # flag2 = ediff1d( flag ) == 0
  3. flag2 = flag[1:] == flag[:-1]
  4. return aux[flag2]
项目:Alfred    作者:jkachhadia    | 项目源码 | 文件源码
  1. def ediff1d(ary, to_begin)
  2. if to_end is not None:
  3. arrays.append(to_end)
  4.  
  5. if len(arrays) != 1:
  6. # We''ll save ourselves a copy of a potentially large array in
  7. # the common case where neither to_begin or to_end was given.
  8. ed = np.hstack(arrays)
  9.  
  10. return ed
项目:Alfred    作者:jkachhadia    | 项目源码 | 文件源码
  1. def setxor1d(ar1, [True]))
  2. # flag2 = ediff1d( flag ) == 0
  3. flag2 = flag[1:] == flag[:-1]
  4. return aux[flag2]

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 模块-ediff1d() 实例源码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 ()、数组基本属性的相关信息,可以在本站进行搜索。

本文标签: