尼采般地抒情

尼采般地抒情

尼采般地抒情

音乐盒

站点信息

文章总数目: 316
已运行时间: 1570

一、NumPy

ndarray 理解多维数组


import numpy as np

生成指定维度的随机多维数据

#数学建模应该用不到
data = np.random.rand(2, 3)
print (data)
print (type(data))
#type是显示数据类型;shape显示维度;ndim维度个数;type另外的作用


[[0.46686682 0.68844304 0.76663872]
 [0.70747721 0.47887587 0.25943412]]
<class 'numpy.ndarray'>


ndim, shape 和 dtype 属性


print ('维度个数', data.ndim)
print ('各维度大小: ', data.shape)
print ('数据类型: ', data.dtype)


维度个数 2
各维度大小:  (2, 3)
数据类型:  float64


创建ndarray


'''1. array创建'''
# list转换为 ndarray
l = range(10)
data = np.array(l)
print (data)
print (data.shape)
print (data.ndim)


[0 1 2 3 4 5 6 7 8 9]
(10,)
1


# 嵌套序列转换为ndarray
l2 = [range(10), range(10)]
#就这样形成了一个数组
data = np.array(l2)
print (data)
print (data.shape)


[[0 1 2 3 4 5 6 7 8 9]
 [0 1 2 3 4 5 6 7 8 9]]
(2, 10)


'''2. zeros;ones;empty创建'''

np.zeros

zeros_arr = np.zeros((3, 4))
#注意元组,这里经常报错

np.ones

ones_arr = np.ones((2, 3))

np.empty[不全为零,而且是随机的一些数字]

empty_arr = np.empty((3, 3))

np.empty 指定数据类型

empty_int_arr = np.empty((3, 3), int)

print (zeros_arr)
print (‘————-‘)
print (ones_arr)
print (‘————-‘)
print (empty_arr)
print (‘————-‘)
print (empty_int_arr)


[[0. 0. 0. 0.]
 [0. 0. 0. 0.]
 [0. 0. 0. 0.]]
-------------
[[1. 1. 1.]
 [1. 1. 1.]]
-------------
[[0.000e+000 0.000e+000 0.000e+000]
 [0.000e+000 0.000e+000 2.174e-321]
 [0.000e+000 0.000e+000 0.000e+000]]
-------------
[[0 0 0]
 [0 0 0]
 [0 0 0]]


# np.arange()
#创建一系列连续的数算是numpy里面类似python里面range的功能
print (np.arange(10))


[0 1 2 3 4 5 6 7 8 9]


二、操作nddarray


矢量化 (vectorization)


# 矢量与矢量运算
arr = np.array([[1, 2, 3],
                [4, 5, 6]])

print ("元素之间相乘:")
#注意区分矩阵之间的运算。这里的矢量原酸相当于是广播式的运算
print (arr * arr)

print ("矩阵相加:")
print (arr + arr)


元素之间相乘:
[[ 1  4  9]
 [16 25 36]]
矩阵相加:
[[ 2  4  6]
 [ 8 10 12]]


# 矢量与标量运算
print (1. / arr)
print (2. * arr)


[[1.         0.5        0.33333333]
 [0.25       0.2        0.16666667]]
[[ 2.  4.  6.]
 [ 8. 10. 12.]]


索引与切片


# 一维数组
arr1 = np.arange(10)
print (arr1)

print (arr1[2:5])


[0 1 2 3 4 5 6 7 8 9]
[2 3 4]


# 多维数组
arr2 = np.arange(12).reshape(3,4)
#要学会定义多维数组,arange是形成12个随机数,之后的reshape是形成维数
#多维数组的空间含义就是比如:3.4.5=长4宽5高3
#还有点数就是应用函数
print (arr2)


[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]


print (arr2[1])

print (arr2[0:2, 2:])

print (arr2[:, 1:3])


[4 5 6 7]
[[2 3]
 [6 7]]
[[ 1  2]
 [ 5  6]
 [ 9 10]]


# 条件索引

找出 data_arr 中 2015年后的数据

data_arr = np.random.rand(3,3)
print (data_arr)

year_arr = np.array([[2000, 2001, 2000],
[2005, 2002, 2009],
[2001, 2003, 2010]])

is_year_after_2005 = year_arr >= 2005
#:他会扩展成同类型的数组
print (is_year_after_2005, is_year_after_2005.dtype)

filtered_arr = data_arr[is_year_after_2005]

filtered_arr = data_arr[year_arr >= 2005]
print (filtered_arr)
#中间的一些语句可以删除
#最后生成得是一维数组,进行数据过滤的时候很有用


[[0.61482194 0.0249229  0.28525661]
 [0.05121173 0.37672803 0.86259463]
 [0.22648329 0.4581513  0.18620441]]
[[False False False]
 [ True False  True]
 [False False  True]] bool
[0.05121173 0.86259463 0.18620441]


# 多个条件& |
filtered_arr = data_arr[(year_arr <= 2005) & (year_arr % 2 == 0)]
print (filtered_arr)


[0.61482194 0.28525661 0.37672803]


转置 === transpose


arr = np.random.rand(2,3)
print (arr)
print (arr.transpose())


[[0.01538974 0.47573964 0.90684253]
 [0.93683601 0.64306611 0.63846634]]
[[0.01538974 0.93683601]
 [0.47573964 0.64306611]
 [0.90684253 0.63846634]]


#高维数组的转换(图像里面会用得到转换维度)

arr3d = np.random.rand(2,3,4)
print (arr3d)
print (‘———————-‘)
print (arr3d.transpose((1,0,2))) # 多维数组的转置和定义不会


[[[0.18074837 0.64652003 0.80527972 0.67800268]
  [0.95766577 0.2498768  0.00304503 0.7058178 ]
  [0.12523549 0.18796252 0.72463798 0.15352211]]

[[0.38808013 0.31075033 0.53082474 0.32254431]
[0.6861262 0.02999367 0.70980993 0.09099878]
[0.14987301 0.78237398 0.90159408 0.82897071]]]


[[[0.18074837 0.64652003 0.80527972 0.67800268]
[0.38808013 0.31075033 0.53082474 0.32254431]]

[[0.95766577 0.2498768 0.00304503 0.7058178 ]
[0.6861262 0.02999367 0.70980993 0.09099878]]

[[0.12523549 0.18796252 0.72463798 0.15352211]
[0.14987301 0.78237398 0.90159408 0.82897071]]]


ndarray数据类型转化 === astype


zeros_float_arr = np.zeros((3, 4), dtype=np.float64)
print (zeros_float_arr)
print (zeros_float_arr.dtype)

astype转换数据类型

zeros_int_arr = zeros_float_arr.astype(np.int32)
print (zeros_int_arr)
print (zeros_int_arr.dtype)


[[0. 0. 0. 0.]
 [0. 0. 0. 0.]
 [0. 0. 0. 0.]]
float64
[[0 0 0 0]
 [0 0 0 0]
 [0 0 0 0]]
int32


文本文件的读取


# loadtxt
filename = './presidential_polls.csv'
data_array = np.loadtxt(filename,      # 文件名
                        delimiter=',', # 指定里面的元素分隔符
                        dtype=str,     # 指定数据类型
                        usecols=(0,2,3)) # 指定读取的列索引号
print (data_array, data_array.shape)


[['cycle' 'type' 'matchup']
 ['2016' '"polls-plus"' '"Clinton vs. Trump vs. Johnson"']
 ['2016' '"polls-plus"' '"Clinton vs. Trump vs. Johnson"']
 ...
 ['2016' '"polls-only"' '"Clinton vs. Trump vs. Johnson"']
 ['2016' '"polls-only"' '"Clinton vs. Trump vs. Johnson"']
 ['2016' '"polls-only"' '"Clinton vs. Trump vs. Johnson"']] (10237, 3)


# loadtxt, 明确指定每列数据的类型
filename = './presidential_polls.csv'
data_array = np.loadtxt(filename,      # 文件名
                        delimiter=',', # 分隔符
                        skiprows=1,
                        dtype={'names':('cycle', 'type', 'matchup'),
                               'formats':('i4', 'S15', 'S50')},     # 数据类型
                        usecols=(0,2,3)) # 指定读取的列索引号

print (data_array, data_array.shape) # 读取的结果是一维的数组,每个元素是一个元组


[(2016, b'"polls-plus"', b'"Clinton vs. Trump vs. Johnson"')
 (2016, b'"polls-plus"', b'"Clinton vs. Trump vs. Johnson"')
 (2016, b'"polls-plus"', b'"Clinton vs. Trump vs. Johnson"') ...
 (2016, b'"polls-only"', b'"Clinton vs. Trump vs. Johnson"')
 (2016, b'"polls-only"', b'"Clinton vs. Trump vs. Johnson"')
 (2016, b'"polls-only"', b'"Clinton vs. Trump vs. Johnson"')] (10236,)



三、np的常用函数


转置transpose


import numpy as np


arr = np.random.rand(2,3)
print (arr)
print (arr.transpose())


[[0.78485041 0.88817969 0.34809014]
 [0.32744286 0.97539301 0.94401872]]
[[0.78485041 0.32744286]
 [0.88817969 0.97539301]
 [0.34809014 0.94401872]]


#高维数组的转换(图像里面会用得到转换维度)
#不懂这里!!!
arr3d = np.random.rand(2,3,4)
print (arr3d)
print ('----------------------')
print (arr3d.transpose((1,0,2))) # 多维数组的转置和定义不会


[[[0.28492549 0.60197236 0.45582367 0.21992479]
  [0.1747163  0.69201365 0.85460359 0.65311699]
  [0.62189644 0.25217555 0.16347156 0.29831219]]

[[0.42826733 0.81396165 0.187138 0.560564 ]
[0.10162186 0.66419751 0.03261665 0.06969256]
[0.55461652 0.55020586 0.50693591 0.31741807]]]


[[[0.28492549 0.60197236 0.45582367 0.21992479]
[0.42826733 0.81396165 0.187138 0.560564 ]]

[[0.1747163 0.69201365 0.85460359 0.65311699]
[0.10162186 0.66419751 0.03261665 0.06969256]]

[[0.62189644 0.25217555 0.16347156 0.29831219]
[0.55461652 0.55020586 0.50693591 0.31741807]]]


ceil和floor和rint和isnan


arr = np.random.randn(2,3)

print (arr)
print (np.ceil(arr))
#向上最接近的整数
print (np.floor(arr))
#向下最接近的整数
print (np.rint(arr))
#四舍五入
print (np.isnan(arr))
#判断元素是否为NaN
#笔记上还有其他的函数


[[ 0.262106   -1.33680008 -1.08562543]
 [ 0.3990978   0.1410074   0.64278274]]
[[ 1. -1. -1.]
 [ 1.  1.  1.]]
[[ 0. -2. -2.]
 [ 0.  0.  0.]]
[[ 0. -1. -1.]
 [ 0.  0.  1.]]
[[False False False]
 [False False False]]


where


arr = np.random.randn(3,4)
print (arr)

np.where(arr > 0, 1, -1)
#(条件,满足输出,不满足输出)


[[ 2.04688394  0.48063737  1.20876913 -0.93412937]
 [-0.43427472 -1.47755481  0.36882256 -0.08943138]
 [-0.2847686   0.96915893  0.32641235  0.28346922]]





array([[ 1, 1, 1, -1],
[-1, -1, 1, -1],
[-1, 1, 1, 1]])


sum


arr = np.arange(10).reshape(5,2)
print (arr)

print (np.sum(arr))
print (np.sum(arr, axis=0))
print (np.sum(arr, axis=1))


[[0 1]
 [2 3]
 [4 5]
 [6 7]
 [8 9]]
45
[20 25]
[ 1  5  9 13 17]


all和any


import numpy as np
arr = np.random.randn(2,3)
print (arr)

print (np.any(arr > 0))
#有一个就对
print (np.all(arr > 0))
#全部对才对
‘’’
·用处就是判断一组数据当中,是否===有点类似布尔类型的
·这个也可以应用在pandas中的DataFrame中
‘’’


[[-1.020184   -0.48466272 -0.8496271 ]
 [ 0.88815825 -0.81911857  0.64570539]]
True
False





‘\n·用处就是判断一组数据当中,是否===有点类似布尔类型的\n·这个也可以应用在pandas中的DataFrame中\n’


unique


arr = np.array([[1, 2, 1], [2, 3, 4]])
print (arr)
print (np.unique(arr))


[[1 2 1]
 [2 3 4]]
[1 2 3 4]

评论区