python array如何选取列
时间: 2023-06-15 21:06:09 浏览: 92
在 Python 中,可以使用 NumPy 库来操作数组并选择特定的列。以下是选择数组列的几种方法:
1. 使用切片操作符 `:` 来选择列:
```python
import numpy as np
arr = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
# 选择第二列
col_2 = arr[:, 1]
print(col_2)
# 输出:[2 5 8]
```
2. 使用索引列表来选择列:
```python
import numpy as np
arr = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
# 选择第一列和第三列
col_1_and_3 = arr[:, [0, 2]]
print(col_1_and_3)
# 输出:[[1 3]
# [4 6]
# [7 9]]
```
3. 使用布尔数组来选择列:
```python
import numpy as np
arr = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
# 选择第一列和第三列
bool_arr = np.array([True, False, True])
selected_cols = arr[:, bool_arr]
print(selected_cols)
# 输出:[[1 3]
# [4 6]
# [7 9]]
```
以上是几种常见的选择数组列的方法。
阅读全文
相关推荐

















