In [32]:
import numpy as np
a = np.array([])
a
Out[32]:
array([], dtype=float64)
In [38]:
dt = np.dtype(np.int32)
dt.__repr__()
Out[38]:
"dtype('int32')"
In [39]:
# int8, int16, int32, int64 可以使用字符串 'i1', 'i2', 'i4', 'i8' 代替
for tp in ['i1', 'i2', 'i4', 'i8']:
print(np.dtype(tp))
int8 int16 int32 int64
In [40]:
dt = np.dtype('<i4') # 小端
dt
Out[40]:
dtype('int32')
In [47]:
age_dt = np.dtype([('age', np.int8)])
age_dt
Out[47]:
dtype([('age', 'i1')])
In [48]:
# 将数据类型应用于 ndarray 对象
import numpy as np
dt = np.dtype([('age',np.int8)])
a = np.array([(10,),(20,),(30,)], dtype = age_dt)
a
Out[48]:
array([(10,), (20,), (30,)], dtype=[('age', 'i1')])
In [51]:
import numpy as np
student = np.dtype([('name','S20'), ('age', 'i1'), ('marks', 'f4')])
student
Out[51]:
dtype([('name', 'S20'), ('age', 'i1'), ('marks', '<f4')])
字符 | 对应类型 |
---|---|
b | 布尔型 |
i | (有符号) 整型 |
u | 无符号整型 integer |
f | 浮点型 |
c | 复数浮点型 |
m | timedelta(时间间隔) |
M | datetime(日期时间) |
O | (Python) 对象 |
S, a | (byte-)字符串 |
U | Unicode |
V | 原始数据 (void) |
In [52]:
import numpy as np
student = np.dtype([('name','S20'), ('age', 'i1'), ('marks', 'f4')])
a = np.array([('abc', 21, 50),('xyz', 18, 75)], dtype = student)
a
Out[52]:
array([(b'abc', 21, 50.), (b'xyz', 18, 75.)], dtype=[('name', 'S20'), ('age', 'i1'), ('marks', '<f4')])
In [1]:
import numpy as np
student = np.dtype([('name','U20'), ('age', 'i1'), ('marks', 'f4')])
a = np.array([('abc', 21, 50),('xyz', 18, 75)], dtype = student)
a
Out[1]:
array([('abc', 21, 50.), ('xyz', 18, 75.)], dtype=[('name', '<U20'), ('age', 'i1'), ('marks', '<f4')])
In [2]:
print ('包含从数组中删除的替代值的切片:')
a = np.array([1,2,3,4,5,6,7,8,9,10])
print (np.delete(a, np.s_[::2]))
包含从数组中删除的替代值的切片: [ 2 4 6 8 10]
In [3]:
np.lookfor('s_')
Search results for 's_' ----------------------- numpy.is_busday Calculates which of the given dates are valid days, and which are not. numpy.less_equal Return the truth value of (x1 =< x2) element-wise. numpy.str0 str(bytes_or_buffer[, encoding[, errors]]) -> str numpy.issubclass_ Determine if a class is a subclass of a second class. numpy.bytes0 bytes(iterable_of_ints) -> bytes numpy.shares_memory Determine if two arrays share memory. numpy.result_type result_type(*arrays_and_dtypes) numpy.datetime_as_string Convert an array of datetimes into an array of strings. numpy.char.less_equal Return (x1 <= x2) element-wise. numpy.ma.less_equal Return the truth value of (x1 =< x2) element-wise. numpy.ma.compress_cols Suppress whole columns of a 2-D array that contain masked values. numpy.ma.compress_rows Suppress whole rows of a 2-D array that contain masked values. numpy.compat.is_pathlib_path Check whether obj is a pathlib.Path object. numpy.double.as_integer_ratio Return a pair of integers, whose ratio is exactly equal to the original numpy.float16.as_integer_ratio Return a pair of integers, whose ratio is exactly equal to the original numpy.float32.as_integer_ratio Return a pair of integers, whose ratio is exactly equal to the original numpy.longdouble.as_integer_ratio Return a pair of integers, whose ratio is exactly equal to the original numpy.testing.assert_raises_regex assert_raises_regex(exception_class, expected_regexp, callable, *args, numpy.core._internal._getfield_is_safe Checks safety of getfield for object arrays. numpy.core._multiarray_umath.is_busday Calculates which of the given dates are valid days, and which are not. numpy.core._multiarray_umath._ones_like This function used to be the numpy.ones_like, but now a specific numpy.AxisError.__class__.__subclasses__ __subclasses__() -> list of immediate subclasses numpy.core._multiarray_umath.shares_memory Determine if two arrays share memory. numpy.core._multiarray_umath.correlate numpy.core._internal._ctypes.strides_as Return the strides tuple as an array of some other numpy.npv Returns the NPV (Net Present Value) of a cash flow series. numpy.ones_like Return an array of ones with the same shape and type as a given array. numpy.pad Pad an array. numpy.core._multiarray_umath.result_type result_type(*arrays_and_dtypes) numpy.less Return the truth value of (x1 < x2) element-wise. numpy.ones Return a new array of given shape and type, filled with ones. numpy.take Take elements from an array along an axis. numpy.zeros_like Return an array of zeros with the same shape and type as a given array. numpy.array Create an array. numpy.core._multiarray_umath.datetime_as_string Convert an array of datetimes into an array of strings. numpy.equal Return (x1 == x2) element-wise. numpy.split Split an array into multiple sub-arrays as views into `ary`. numpy.zeros Return a new array of given shape and type, filled with zeros. numpy.delete Return a new array with sub-arrays along an axis deleted. For a one numpy.core._internal._ctypes.data_as Return the data pointer cast to a particular c-types object. numpy.median Compute the median along the specified axis. numpy.nansum Return the sum of array elements over a given axis treating Not a numpy.nditer Efficient multi-dimensional iterator object to iterate over arrays. numpy.core._multiarray_umath.normalize_axis_index Normalizes an axis index, `axis`, such that is a valid positive index into numpy.greater Return the truth value of (x1 > x2) element-wise. numpy.quantile Compute the q-th quantile of the data along the specified axis. numpy.array_str Return a string representation of the data in an array. numpy.full_like Return a full array with the same shape and type as a given array. numpy.not_equal Return (x1 != x2) element-wise. numpy.ma.is_mask Return True if m is a valid, standard mask. numpy.array_repr Return the string representation of an array. numpy.empty_like Return a new array with the same shape and type as a given array. numpy.issubdtype Returns True if first argument is a typecode lower/equal in type hierarchy. numpy.percentile Compute the q-th percentile of the data along the specified axis. numpy.array_split Split an array into multiple sub-arrays. numpy.binary_repr Return the binary representation of the input number as a string. numpy.bitwise_not Compute bit-wise inversion, or bit-wise NOT, element-wise. numpy.nanquantile Compute the qth quantile of the data along the specified axis, numpy.show_config Show libraries in the system on which NumPy was built. numpy.triu_indices_from Return the indices for the upper-triangle of arr. numpy.ma.is_masked Determine whether input has masked values. numpy.array2string Return a string representation of an array. numpy.busday_count Counts the number of valid days between `begindates` and numpy.diag_indices Return the indices to access the main diagonal of an array. numpy.char.less Return (x1 < x2) element-wise. numpy.ma.less Return the truth value of (x1 < x2) element-wise. numpy.busday_offset First adjusts the date to fall on a valid day according to numpy.ma.ones Return a new array of given shape and type, filled with ones. numpy.distutils.system_info.BlasSrcNotFoundError Blas (http://www.netlib.org/blas/) sources not found. numpy.fill_diagonal Fill the main diagonal of the given array of any dimensionality. numpy.greater_equal Return the truth value of (x1 >= x2) element-wise. numpy.nanpercentile Compute the qth percentile of the data along the specified axis, numpy.char.equal Return (x1 == x2) element-wise. numpy.ma.compress_nd Suppress slices from multiple dimensions which contain masked values. numpy.ma.equal Return (x1 == x2) element-wise. numpy.busdaycalendar A business day calendar object that efficiently stores information numpy.ma.zeros Return a new array of given shape and type, filled with zeros. numpy.put_along_axis Put values into the destination array by matching 1d index and data slices. numpy.distutils.system_info.BlasILP64NotFoundError 64-bit Blas libraries not found. numpy.char.greater Return (x1 > x2) element-wise. numpy.take_along_axis Take values from the input array by matching 1d index and data slices. numpy.apply_along_axis Apply a function to 1-D slices along the given axis. numpy.ma.greater Return the truth value of (x1 > x2) element-wise. numpy.may_share_memory Determine if two arrays might share memory numpy.distutils.system_info.LapackILP64NotFoundError 64-bit Lapack libraries not found. numpy.char.not_equal Return (x1 != x2) element-wise. numpy.ma.not_equal Return (x1 != x2) element-wise. numpy.ma.compress_rowcols Suppress the rows and/or columns of a 2-D array that contain numpy.ma.empty_like empty_like(prototype, dtype=None, order='K', subok=True, shape=None) numpy.histogram_bin_edges Function to calculate only the edges of the bins used by the `histogram` numpy.chararray.__le__ Return (self <= other) element-wise. numpy.ma.masked_less_equal Mask an array where less than or equal to a given value. numpy.testing.raises Decorator to check for raised exceptions. numpy.ma.masked_where Mask an array where a condition is met. numpy.char.greater_equal Return (x1 >= x2) element-wise. numpy.ma.greater_equal Return the truth value of (x1 >= x2) element-wise. numpy.dtype.newbyteorder Return a new dtype with a different byte order. numpy.ma.notmasked_edges Find the indices of the first and last unmasked values along an axis. numpy.ma.apply_along_axis Apply a function to 1-D slices along the given axis. numpy.core._dtype._is_packed Checks whether the structured data type in 'dtype' numpy.testing.suppress_warnings Context manager and decorator doing much the same as numpy.ma.notmasked_contiguous Find contiguous unmasked data in a masked array along the given axis. numpy.distutils.command.bdist_rpm.bdist_rpm.debug_print Print 'msg' to stdout if the global DEBUG (taken from the numpy.lib._iotools.easy_dtype Convenience function to create a `np.dtype` object. numpy.distutils.__config__.show Show libraries in the system on which NumPy was built. numpy.lib._iotools.has_nested_fields Returns whether one or several fields of a dtype are nested. numpy.lib.recfunctions.get_names_flat Returns the field names of the input datatype as a tuple. Nested structure numpy.polynomial.polyutils.as_series Return argument as a list of 1-d arrays. numpy.random.Generator.uniform Draw samples from a uniform distribution. numpy.distutils.fcompiler.FCompiler Abstract base class to define the interface that must be implemented numpy.random.RandomState.uniform Draw samples from a uniform distribution. numpy.core.tests.test_function_base.PhysicalQuantity.as_integer_ratio Return a pair of integers, whose ratio is exactly equal to the original numpy.random.Generator.standard_t Draw samples from a standard Student's t distribution with `df` degrees numpy.random.RandomState.get_state get_state() numpy.random.RandomState.set_state set_state(state) numpy.lib.tests.test__iotools.TestMiscFunctions.test_has_nested_dtype Test has_nested_dtype numpy.random.RandomState.standard_t Draw samples from a standard Student's t distribution with `df` degrees numpy.core._multiarray_umath.empty_like Return a new array with the same shape and type as a given array. numpy.core._multiarray_umath.busday_count Counts the number of valid days between `begindates` and numpy.core._multiarray_umath.busday_offset First adjusts the date to fall on a valid day according to numpy.core.overrides.array_function_dispatch Decorator for adding dispatch with the __array_function__ protocol. numpy.distutils.fcompiler.g95.G95FCompiler Abstract base class to define the interface that must be implemented numpy.distutils.fcompiler.gnu.GnuFCompiler Abstract base class to define the interface that must be implemented numpy.distutils.fcompiler.ibm.IBMFCompiler Abstract base class to define the interface that must be implemented numpy.distutils.fcompiler.nag.NAGFCompiler Abstract base class to define the interface that must be implemented numpy.distutils.fcompiler.sun.SunFCompiler Abstract base class to define the interface that must be implemented numpy.distutils.fcompiler.gnu.Gnu95FCompiler Abstract base class to define the interface that must be implemented numpy.distutils.fcompiler.hpux.HPUXFCompiler Abstract base class to define the interface that must be implemented numpy.distutils.fcompiler.mips.MIPSFCompiler Abstract base class to define the interface that must be implemented numpy.distutils.fcompiler.nag.NAGFORCompiler Abstract base class to define the interface that must be implemented numpy.distutils.fcompiler.none.NoneFCompiler Abstract base class to define the interface that must be implemented numpy.distutils.fcompiler.pg.PGroupFCompiler Abstract base class to define the interface that must be implemented numpy.distutils.fcompiler.vast.VastFCompiler Abstract base class to define the interface that must be implemented numpy.distutils.fcompiler.intel.IntelFCompiler Abstract base class to define the interface that must be implemented numpy.distutils.fcompiler.lahey.LaheyFCompiler Abstract base class to define the interface that must be implemented numpy.distutils.fcompiler.nag.BaseNAGFCompiler Abstract base class to define the interface that must be implemented numpy.distutils.fcompiler.absoft.AbsoftFCompiler Abstract base class to define the interface that must be implemented numpy.distutils.fcompiler.compaq.CompaqFCompiler Abstract base class to define the interface that must be implemented numpy.distutils.fcompiler.pg.PGroupFlangCompiler Abstract base class to define the interface that must be implemented numpy.distutils.fcompiler.intel.BaseIntelFCompiler Abstract base class to define the interface that must be implemented numpy.distutils.fcompiler.intel.IntelEM64TFCompiler Abstract base class to define the interface that must be implemented numpy.distutils.misc_util.Configuration.set_options Configure Configuration instance. numpy.distutils.fcompiler.intel.IntelVisualFCompiler Abstract base class to define the interface that must be implemented numpy.distutils.fcompiler.pathf95.PathScaleFCompiler Abstract base class to define the interface that must be implemented numpy.distutils.fcompiler.intel.IntelItaniumFCompiler Abstract base class to define the interface that must be implemented numpy.distutils.fcompiler.compaq.CompaqVisualFCompiler Abstract base class to define the interface that must be implemented numpy.distutils.fcompiler.intel.IntelEM64VisualFCompiler Abstract base class to define the interface that must be implemented numpy.distutils.fcompiler.intel.IntelItaniumVisualFCompiler Abstract base class to define the interface that must be implemented
In [12]:
import numpy as np
print ('13 和 17 的二进制形式:')
a,b = 13,17
print (bin(a), bin(b))
print ('\n')
print ('13 和 17 的位与:')
print (np.bitwise_and(13, 17))
np.bitwise_not(13)
13 和 17 的二进制形式: 0b1101 0b10001 13 和 17 的位与: 1
Out[12]:
-14
In [17]:
import numpy as np
print ('13 的位反转,其中 ndarray 的 dtype 是 uint8:')
print (np.bitwise_not(np.array([13], dtype = np.uint8)))
# 比较 13 和 242 的二进制表示,我们发现了位的反转
print ()
print ('13 的二进制表示:')
print (np.binary_repr(13, width = 8))
print ()
print ('242 的二进制表示:')
print (np.binary_repr(242, width = 8))
13 的位反转,其中 ndarray 的 dtype 是 uint8: [242] 13 的二进制表示: 00001101 242 的二进制表示: 11110010
In [23]:
import numpy as np
print ('将 10 左移两位:')
print (np.left_shift(10,2))
print ('\n')
print ('10 的二进制表示:')
print (np.binary_repr(10, width = 8))
print ('\n')
print ('40 的二进制表示:')
print (np.binary_repr(40, width = 8))
# '00001010' 中的两位移动到了左边,并在右边添加了两个 0。
将 10 左移两位: 40 10 的二进制表示: 00001010 40 的二进制表示: 00101000
In [29]:
import numpy as np
print(np.char.add('HEllo', ' LDS'))
print(np.char.add(['HEllo'], [' LDS']))
print ('连接示例:')
print (np.char.add(['hello', 'hi'],[' abc', ' xyz']))
HEllo LDS ['HEllo LDS'] 连接示例: ['hello abc' 'hi xyz']
In [30]:
import numpy as np
print (np.char.multiply('Runoob ',3))
Runoob Runoob Runoob
In [31]:
np.char.center("lds", 10, "^")
Out[31]:
array('^^^lds^^^^', dtype='<U10')
In [36]:
import numpy as np
print (np.char.capitalize(['runoob', 'lds', 'i like runoob']))
['Runoob' 'Lds' 'I like runoob']
In [35]:
import numpy as np
print (np.char.title(['runoob', 'lds', 'i like runoob']))
['Runoob' 'Lds' 'I Like Runoob']
In [40]:
import numpy as np
# 换行符 \n
print (np.char.splitlines('i\nlike runoob?').__repr__())
print(np.char.splitlines('i\rlike 神探?').__repr__())
array(list(['i', 'like runoob?']), dtype=object) array(list(['i', 'like 神探?']), dtype=object)
In [44]:
import numpy as np
# 操作字符串
print(np.char.join(':', 'runoob'))
# 指定多个分隔符操作数组元素
print(np.char.join([':', '-'], [['runoob', 'lds'], 'google']))
r:u:n:o:o:b ['runoob:lds' 'g-o-o-g-l-e']
In [47]:
import numpy as np
a = np.char.encode('runoob 小梁', 'GBK')
print(a)
print(np.char.decode(a, 'GBK'))
b'runoob \xd0\xa1\xc1\xba' runoob 小梁
In [48]:
import numpy as np
a = np.array([0, 30, 45, 60, 90])
print('不同角度的正弦值:')
# 通过乘 pi/180 转化为弧度
print(np.sin(a*np.pi/180))
print('\n')
print('数组中角度的余弦值:')
print(np.cos(a*np.pi/180))
print('\n')
print('数组中角度的正切值:')
print(np.tan(a*np.pi/180))
不同角度的正弦值: [0. 0.5 0.70710678 0.8660254 1. ] 数组中角度的余弦值: [1.00000000e+00 8.66025404e-01 7.07106781e-01 5.00000000e-01 6.12323400e-17] 数组中角度的正切值: [0.00000000e+00 5.77350269e-01 1.00000000e+00 1.73205081e+00 1.63312394e+16]
In [50]:
import numpy as np
a = np.array([1.0,5.35, 123, 0.567, 25.532])
print ('原数组:')
print (a)
print ('\n')
print ('舍入后:')
print (np.around(a))
print (np.around(a, decimals = 1))
print (np.around(a, decimals = -1))
原数组: [ 1. 5.35 123. 0.567 25.532] 舍入后: [ 1. 5. 123. 1. 26.] [ 1. 5.4 123. 0.6 25.5] [ 0. 10. 120. 0. 30.]
In [57]:
import numpy as np
a = np.array([[10, 7, 4], [3, 2, 1]])
print ('我们的数组是:')
print (a)
print ('调用 percentile() 函数:')
# 50% 的分位数,就是 a 里排序之后的中位数
print (np.percentile(a, 70))
# axis 为 0,在纵列上求
print (np.percentile(a, 70, axis=0))
# axis 为 1,在横行上求
print (np.percentile(a, 70, axis=1))
# 保持维度不变
print (np.percentile(a, 70, axis=1, keepdims=True))
我们的数组是: [[10 7 4] [ 3 2 1]] 调用 percentile() 函数: 5.5 [7.9 5.5 3.1] [8.2 2.4] [[8.2] [2.4]]
In [55]:
3 + 7 * 0.7
Out[55]:
7.8999999999999995
In [59]:
import numpy as np
a = np.array([1, 2, 3, 4])
print('我们的数组是:')
print(a)
print('\n')
print('调用 average() 函数:')
print(np.average(a))
print('\n')
# 不指定权重时相当于 mean 函数
wts = np.array([4, 3, 2, 1])
print("权重:", wts)
print('再次调用 average() 函数:')
print(np.average(a, weights=wts))
print('\n')
# 如果 returned 参数设为 true,则返回权重的和
print('权重的和:')
print(np.average([1, 2, 3, 4], weights=[4, 3, 2, 1], returned=True))
我们的数组是: [1 2 3 4] 调用 average() 函数: 2.5 权重: [4 3 2 1] 再次调用 average() 函数: 2.0 权重的和: (2.0, 10.0)
In [66]:
import numpy as np
a = np.array([[3, 7], [9, 1]])
print(a)
print('列排序', np.sort(a, kind='mergesort', axis=0))
print('行排序', np.sort(a, axis=1, kind="mergesort"))
[[3 7] [9 1]] 列排序 [[3 1] [9 7]] 行排序 [[3 7] [1 9]]
In [78]:
import numpy as np
x = np.arange(9.).reshape(3, 3)
print ('我们的数组是:')
print (x)
print ( '大于 3 的元素的索引:')
y = np.where(x > 3)
print (y)
print ('使用这些索引来获取满足条件的元素:')
print (x[y])
我们的数组是: [[0. 1. 2.] [3. 4. 5.] [6. 7. 8.]] 大于 3 的元素的索引: (array([1, 1, 2, 2, 2], dtype=int64), array([1, 2, 0, 1, 2], dtype=int64)) 使用这些索引来获取满足条件的元素: [4. 5. 6. 7. 8.]
In [84]:
import numpy as np
a = np.array([1, 256, 8755], dtype = np.int16)
print ('我们的数组是:')
print (a)
print ('以十六进制表示内存中的数据:')
print (list(map(hex,a)))
# byteswap() 函数通过传入 true 来原地交换
print ('调用 byteswap() 函数:')
print (a.byteswap(True))
print ('十六进制形式:')
print (list(map(hex,a)))
# 我们可以看到字节已经交换了
我们的数组是: [ 1 256 8755] 以十六进制表示内存中的数据: ['0x1', '0x100', '0x2233'] 调用 byteswap() 函数: [ 256 1 13090] 十六进制形式: ['0x100', '0x1', '0x3322']
In [86]:
import numpy as np
a = np.arange(20).reshape(4, 5)
print("原数组:", a)
print("", a[2])
Out[86]:
array([10, 11, 12, 13, 14])
In [91]:
from numpy import matlib
import numpy as np
print(np.empty((2, 2)).__repr__())
matlib.empty((2, 2))
array([[8.60334707e-315, 1.14408606e-311], [8.60334801e-315, 8.60334675e-315]])
Out[91]:
matrix([[8.60334707e-315, 1.14408606e-311], [8.60334801e-315, 8.60334675e-315]])
In [94]:
np.random.rand(3,3)
Out[94]:
array([[0.39886458, 0.59226958, 0.76513372], [0.60592693, 0.16650084, 0.14563618], [0.27846519, 0.29259619, 0.08026506]])
In [95]:
matlib.rand(3,3)
Out[95]:
matrix([[0.11958196, 0.12247145, 0.8801389 ], [0.49741205, 0.00559036, 0.03021468], [0.54922254, 0.42660782, 0.70803244]])
In [100]:
np.matrix("1,2;3,4")
Out[100]:
matrix([[1, 2], [3, 4]])
In [102]:
np.asarray(np.asmatrix("1,2;3,4"))
Out[102]:
array([[1, 2], [3, 4]])
In [112]:
import numpy as np
a = np.array([[1,2],[3,4]])
b = np.array([[11,12],[13,14]])
# 点积
a * b
Out[112]:
array([[11, 24], [39, 56]])
In [113]:
# 矩阵积
a @ b
Out[113]:
array([[37, 40], [85, 92]])
In [106]:
np.matmul(a, b)
Out[106]:
array([[37, 40], [85, 92]])
In [110]:
np.dot(a, b)
Out[110]:
array([[37, 40], [85, 92]])
In [109]:
import numpy as np
a = np.array([[1,2],[3,4]])
b = np.array([[11,12],[13,14]])
# vdot 将数组展开计算内积
np.vdot(a,b)
Out[109]:
130
In [114]:
np.inner(a, b)
Out[114]:
array([[35, 41], [81, 95]])
In [117]:
import numpy.matlib
import numpy as np
a = [[1,0],[0,1]]
b = [1,2]
print (np.matmul(a,b).__repr__())
print (np.matmul(b,a).__repr__())
array([1, 2]) array([1, 2])
In [124]:
a = [[1,2],[3,4]]
b = [1,2]
np.matmul(a, b)
Out[124]:
array([ 5, 11])
In [125]:
a = [[1,2],[3,4]]
b = [[1],[2]]
np.matmul(a, b)
Out[125]:
array([[ 5], [11]])
In [156]:
np.random.rand(2).shape
Out[156]:
(2,)
In [159]:
a = [[1,2],[3,4]]
b = [[1],[2]]
a = np.squeeze(np.matmul(a, b), 1)
a
Out[159]:
array([ 5, 11])
In [148]:
print(a.shape)
a = np.expand_dims(a, 1)
print(a)
a.shape
(2,) [[ 5] [11]]
Out[148]:
(2, 1)
In [187]:
Out[187]:
'lds'
In [ ]: