当前位置:网站首页>Numpy learning
Numpy learning
2022-07-25 08:07:00 【Cherry_ Zj】
Numpy Study
numpy A preliminary understanding of
1. Use numpy Generating arrays , obtain ndarray The type of
t1 = np.array([1,2,3])
print(t1)
print(type(t1)) #<class 'numpy.ndarray'>
2. np.arange(x) The effect of the method and np.array(range(x)) The effect is the same
t2 = np.array(range(10))
print(t2)
print(type(t2))
t3 = np.arange(10)
print(t3)
print(type(t3))
3. Use dtype You can get the data type
t4 = np.arange(4,10,2)
print(t4)
print(type(t4))
print(t4.dtype)
4.numpy Data types in
t5 = np.array(range(1,4),dtype=float)
# or t5 = np.array(range(1,4),dtype="float")
# or t5 = np.array(range(1,4),dtype="float32")
print(t5)
print(t5.dtype)
# numpy Medium bool data type
t6 = np.array([0,1,1,0,1,0,0],dtype="bool")
print(t6)
print(t6.dtype)
print("//")
# Adjust the data type
t7 = t5.astype("int8")
print(t5.dtype)
print(t7.dtype)
print("***************************")
t5.dtype = "int8"
print(t5.dtype)
# numpy The decimal in
t7 = np.array([random.random() for i in range(10)])
print(t7)
print(t7.dtype)
# Modify floating point scale
t8 = np.round(t7,2) # Keep two decimal places
print(t8)
Shape and operation of array
a.shapeView array shapes
import numpy as np
t1 = np.arange(12)
print(t1)#t1:{ndarray:(12,)}
print(t1.shape)# Output results :(12,)
t2 = np.array([[1,2,3],[4,5,6]])
print(t2)#t2:{ndarray:(2,3)}
print(t2.shape)# Output results :(2,3)
t3 = np.array([[[1,2,3],[4,5,6]],[[7,8,9],[10,11,12]]])
print(t3)#t2:{ndarray:(2,2,3)}
print(t3.shape)# Output results :(2,2,3)
2.a.reshape(3,4) Modify array shape
t4 = np.arange(12)
print(t4)
print(t4.reshape(3,4))
print(t4.reshape(3,5))# Cannot become an array of this shape
t5 = np.arange(24).reshape(2,3,4)
print(t5)
print("---------------")
# t5.reshape(4,6) There is a return value , Will not change t5 Value
print(t5.reshape(4,6))
print("---------------")
print(t5)
print("---------------")
# take t5 Into a one-dimensional array
print(t5.reshape(24,))
print("---------------")
# Find out the following two situations
print(t5.reshape(24,1))
print("---------------")
print(t5.reshape(1,24))
print("#######################")
3.t5.flatten(), take t5 Into a one-dimensional array Don't know t5 How much data is there , take t5 Into a one-dimensional array
# Law 1
t5 = np.arange(24).reshape(2,3,4)
print(t5.reshape(t5.shape[0]*t5.shape[1]*t5.shape[2],))
print("#######################")
# Law two :
print(t5.flatten())
4. The operation of arrays and numbers
# Operation of array
t5 = np.arange(24).reshape(2,3,4)
t6 = t5.reshape(4,6)
print(t6)
print("************************")
print(t6+2)
print("************************")
print(t6-2)
print("************************")
print(t6*2)
print("************************")
print(t6/2)
print("************************")
print(t6/0)
The result is :
5. Array and array operation
① Situation 1 :
t5 = np.arange(24).reshape(2,3,4)
t6 = t5.reshape(4,6)
t7 = np.arange(100,124).reshape(4,6)
print(t7)
print("**************************")
print(t6+t7)
print("**************************")
print(t6-t7)
print("**************************")
print(t6*t7)
print("**************************")
print(t6/t7)
The result is :
② Situation two :
t5 = np.arange(24).reshape(2,3,4)
t6 = t5.reshape(4,6)
t8 = np.arange(0,6)
print(t8)
print(t6)
print(t6-t8)

③ Situation three :
t5 = np.arange(24).reshape(2,3,4)
t6 = t5.reshape(4,6)
t9 = np.arange(4).reshape(4,1)
print(t9)
print(t6)
print(t6-t9)

④ Situation four :
t5 = np.arange(24).reshape(2,3,4)
t6 = t5.reshape(4,6)
t10 = np.arange(10)
print(t10)
print(t6)
# Can't calculate
print(t6-t10)
print("*"*100)

numpy Index and slice of
1. Take one row and one column or multiple rows and multiple columns

import numpy as np
us_file_path = "./dataCSV/data.csv"
t1 = np.loadtxt(us_file_path,delimiter=",",dtype="int",unpack=True)
t2 = np.loadtxt(us_file_path,delimiter=",",dtype="int")
print(t1)
print("*"*100)
print(t2)
print("*"*100)
# Take row
print(t2[2])
print("*"*100)
# Take consecutive lines
print(t2[2:])
print("*"*100)
# Take discontinuous lines , Take the first place 2,8,10 That's ok
print(t2[[2,8,10]])
print("*"*100)
# Take row print(t2[ That's ok , Column ])
# print(t2[1,:])
# print(t2[2:,:])
# print(t2[[2,8,10],:])
# Fetch
print(t2[:,0]) # Take the data in the first column of all rows
print("*"*100)
# Take consecutive Columns
print(t2[:,2:])# Take all column data after the third column of all rows
print("*"*100)
# Take consecutive Columns
print(t2[:,[0,2]])## Take the data of the first and third columns of all rows
print("*"*100)
# Fetching rows and columns , Take the third line , The value of the fourth column
a = t2[2,3]
print(a)
print(type(a))
print("*"*100)
# Fetching multiple rows and columns , Take the third line to the fifth line , The values of the second to fourth columns ( Take the position where rows and columns intersect )
b = t2[2:5,1:4]
print(b)
print("*"*100)
# Take multiple non adjacent points
# The result is (0,0) (2,1) (2,3)
c = t2[[0,2,2],[0,1,3]]
print(c)
2. The exchange of ranks

3. Array splicing
①np.vstack(t1,t2) For vertical splicing
②np.hstack(t1,t2) Use horizontal splicing 
4. Array transposition
Transpose is a transformation , about numpy For arrays in , Is in the Exchange data diagonally , The purpose is also to process data more conveniently . There are three ways :
①t.transpose()
②t.swapaxes(1,0)
③t.T
5.numpy Reading data


6.numpy Generate random number

7.numpy Boolean index in
t5 = np.arange(24).reshape(2,3,4)
t6 = t5.reshape(4,6)
print(t6<10)
print("*"*100)
t6[t6<10]=3
print(t6)
print("*"*100)
print(t6[t6>20])
print("*"*100)
t6[t6>20]=20
print(t6)
print("*"*100)

8. The ternary operation
# The ternary operation
# hold t6 Less than equal to 3 Of is replaced by 100, Otherwise replace with 300
t5 = np.arange(24).reshape(2,3,4)
t6 = t5.reshape(4,6)
print(np.where(t6<=3,100,300))
print("*"*100)
print(t6)
print("*"*100)

## 9. Assign a value to nan
t5 = np.arange(24).reshape(2,3,4)
t6 = t5.reshape(4,6)
t6 = t6.astype(float)
t6[3,3]=np.nan
print(t6)

9.numpy Medium clip

numpy Medium nan and inf

numpy Medium nan Points for attention


Handle : to nan Assigned mean value
import numpy as np
# to nan Assigned mean value
def fill_ndarray(t1):
for i in range(t1.shape[1]):
temp_col = t1[:,i]
nan_num = np.count_nonzero(temp_col != temp_col)
if nan_num != 0:# Not for 0, It indicates that there are nan
temp_not_nan_col = temp_col[temp_col == temp_col] # The current column is not nan Of array
# Check that the current is nan The location of , Assign a value that is not nan The average of
temp_col[np.isnan(temp_col)] = temp_not_nan_col.mean()
return t1
if __name__ == '__main__':
t1 = np.arange(12).reshape((3, 4)).astype("float")
t1[1, 2:] = np.nan
print(t1)
print("*"*100)
t1 = fill_ndarray(t1)
print(t1)
numpy Common functions in


numpy Medium copy and view

边栏推荐
- Common commands of raspberry pie
- Raspberrypico analytic PWM
- Implement hot post | community project with timed tasks and cache
- pom容易忽略的问题
- [recommended reading] a collection of super useful vulnerability scanning tools!
- P1046 [NOIP2005 普及组 T1] 陶陶摘苹果
- Network packet loss, network delay? This artifact helps you solve all problems
- mysql 如何获取两个集合的交集/差集/并集
- 由两个栈组成的队列
- Learn when playing No 2 | learning is too boring? Learning maps lets you learn and play
猜你喜欢

MVC mode three-tier architecture

Eval and assert one sentence Trojan horse analysis

Calculation formula of cross entropy

第十七届振兴杯计算机程序设计员(云计算平台运维与开发)决赛

Surpassing transformer, Tsinghua, byte significantly refresh parallel text generation SOTA performance | ICML 2022

How should enterprise users choose aiops or APM?

CAS操作

Recommend 7 open source projects of yyds this week

牛客动态规划训练

A review of nature: gender differences in anxiety and depression - circuits and mechanisms
随机推荐
How to do a good job in safety development?
【FFmpeg】mp4转yuv
Dijkstra序列(暑假每日一题 5)
如何仅用递归函数和栈操作逆序一个栈
475-82(230、43、78、79、213、198、1143)
Calculation formula of cross entropy
CAS operation
Advanced C language (XIII) - Example Analysis of dynamic memory management
Implement hot post | community project with timed tasks and cache
C# 43. 获取UDP可用端口
A powerful port scanning tool (nmap)
[QNX Hypervisor 2.2用户手册]9.3 cpu
People who lose weight should cry: it's no good not eating food, because your brain will be inflamed
Cache design in Web services (error allowed, error not allowed)
Hikaricp connection pool does not operate for a period of time, and the data is automatically disconnected
由两个栈组成的队列
What products and funds should novices invest in first?
Cerebral cortex: the relationship between lifestyle and brain function in the elderly and its relationship with cognitive decline
Pricing is arbitrary, products are difficult to distinguish between true and false, and platforms are running away. Will the Tibetan market continue to be popular?
app耗电量测试