溫馨提示×

numpy怎么獲取指定行列數(shù)據(jù)

小億
181
2024-01-25 09:47:57
欄目: 編程語言

在numpy中,我們可以使用索引來獲取指定行列的數(shù)據(jù)。

例如,假設(shè)我們有一個(gè)2維的numpy數(shù)組arr,我們想要獲取第2行和第3列的數(shù)據(jù),可以使用以下代碼:

import numpy as np

arr = np.array([[1, 2, 3],
                [4, 5, 6],
                [7, 8, 9]])

row = 1
column = 2

# 獲取指定行
row_data = arr[row, :]

# 獲取指定列
column_data = arr[:, column]

print("第2行的數(shù)據(jù):", row_data)
print("第3列的數(shù)據(jù):", column_data)

輸出結(jié)果為:

第2行的數(shù)據(jù): [4 5 6]
第3列的數(shù)據(jù): [3 6 9]

我們可以使用索引arr[row, :]來獲取指定行的數(shù)據(jù),其中row表示行的索引。同樣地,我們可以使用索引arr[:, column]來獲取指定列的數(shù)據(jù),其中column表示列的索引。請(qǐng)注意,索引從0開始計(jì)數(shù)。

0