python机器学习库numpy---9、访问数组元素


python机器学习库numpy---9、访问数组元素

一、总结

一句话总结:

在numpy中,我们可以通过下标的方式来访问数组元素,比如arr[1][1],我们也可以通过索引的方式来访问数组,比如arr[1,1:3](第1行 列从1-2)
import numpy as np
arr=np.arange(4,20).reshape(4,4)
print(arr)

[[ 4  5  6  7]
 [ 8  9 10 11]
 [12 13 14 15]
 [16 17 18 19]]

print(arr[1][2])
10


# 逗号前面的表示行
# 逗号后面的表示列
# 留头不留尾
print(arr[1:3,1:3])

[[ 9 10]
 [13 14]]

 

 

 

二、访问数组元素

博客对应课程的视频位置:9、访问数组元素-范仁义-读书编程笔记
https://www.fanrenyi.com/video/38/352

 

numpy中,可以像普通数组一样用下标来访问元素,比如a[1][1]、a[1,1]


numpy中通过索引访问数组元素

a[1,:](访问第1行元素)

a[:,1](访问第1列元素)

a[1,1:3](访问第1行的,第1-2列元素)

1、pyhton列表中访问元素

In [12]:
list1=[[1,2,3,4],[5,6,7,8]] print(list1) 
[[1, 2, 3, 4], [5, 6, 7, 8]]
In [13]:
print(list1[1]) 
[5, 6, 7, 8]
In [14]:
print(list1[1][1]) 
6
In [18]:
print(list1[1:2]) 
[[5, 6, 7, 8]]
In [15]:
# 不支持
print(list1[1,1]) 
---------------------------------------------------------------------------
TypeError Traceback (most recent call last) <ipython-input-15-5f9f4dbe9414> in <module> ----> 1 print(list1[1,1]) TypeError: list indices must be integers or slices, not tuple
In [17]:
# 不支持
print(list1[1:2,1:2]) 
---------------------------------------------------------------------------
TypeError Traceback (most recent call last) <ipython-input-17-4666c8770ee5> in <module> ----> 1 print(list1[1:2,1:2]) TypeError: list indices must be integers or slices, not tuple

2、numpy数组访问元素

In [1]:
import numpy as np arr=np.arange(4,20).reshape(4,4) print(arr) 
[[ 4  5  6  7]
 [ 8  9 10 11]
 [12 13 14 15]
 [16 17 18 19]]
In [2]:
print(arr[1]) 
[ 8  9 10 11]
In [4]:
print(arr[1][2]) print(arr[1,2]) 
10
10
In [5]:
# 逗号前面的表示行
# 逗号后面的表示列 # 留头不留尾 print(arr[1:3,1:3]) 
[[ 9 10]
 [13 14]]
In [6]:
print(arr[2:4,1:4]) 
[[13 14 15]
 [17 18 19]]
In [8]:
print(arr) 
[[ 4  5  6  7]
 [ 8  9 10 11]
 [12 13 14 15]
 [16 17 18 19]]
In [9]:
print(arr[:,1:4]) 
[[ 5  6  7]
 [ 9 10 11]
 [13 14 15]
 [17 18 19]]
In [10]:
print(arr[1:4,:]) 
[[ 8  9 10 11]
 [12 13 14 15]
 [16 17 18 19]]
In [11]:
print(arr[1,:]) 
[ 8  9 10 11]
In [ ]:
 
 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM