我撰寫了以下代碼:
import numpy as np
n_rows = int(input("Enter number of rows:"))
n_columns = int(input("Enter number of columns:"))
print("Enter 2D array values---")
matrix = []
for i in range(n_rows):
a=[]
for j in range(n_columns):
a.append(int(input()))
matrix.append(a)
arr=np.array(matrix)
arr
如果我輸入以下值,這將給出以下輸出:
array([[1, 2, 3],
[4, 5, 6]])
但我希望矩陣的第一行作為字串值輸入,例如:
["John","Alex","Smith"]
和矩陣的第二行作為整數值,如:
[50,60,70]
然后我想獲得以下輸出:
Name: John , Marks: 50
Name: Alex , Marks: 60
Name: Smith, Marks: 70
uj5u.com熱心網友回復:
Numpy 要求矩陣中的所有值都屬于同一型別。這是由于它如何搜索陣列中的專案(有關更多資訊,請查找strides)
因此,如果您想在您的陣列中使用文本資料,您必須將整個陣列的型別更改為支持字串的型別。
另一種方法是為名稱使用一個陣列,為值使用一個單獨的陣列。此外,您可以使用pandas.DataFrame它來直接解決您的問題
uj5u.com熱心網友回復:
串列串列:
In [274]: alist = [["John","Alex","Smith"],[50,60,70]]
In [275]: alist
Out[275]: [['John', 'Alex', 'Smith'], [50, 60, 70]]
只需呼叫即可生成np.array一個包含字串的陣列,即最小的通用 dtype:
In [276]: np.array(alist)
Out[276]:
array([['John', 'Alex', 'Smith'],
['50', '60', '70']], dtype='<U21')
我們也可以指定object,但這樣的陣列實際上與原始串列相同:
In [277]: np.array(alist, dtype=object)
Out[277]:
array([['John', 'Alex', 'Smith'],
[50, 60, 70]], dtype=object)
該串列的“轉置”:
In [278]: altlist = list(zip(*alist))
In [279]: altlist
Out[279]: [('John', 50), ('Alex', 60), ('Smith', 70)]
可用于使用structured array復合 dtype制作 a :
In [280]: np.array(altlist, dtype='U10,int')
Out[280]:
array([('John', 50), ('Alex', 60), ('Smith', 70)],
dtype=[('f0', '<U10'), ('f1', '<i8')])
或資料框:
In [281]: pd.DataFrame(altlist)
Out[281]:
0 1
0 John 50
1 Alex 60
2 Smith 70
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/391880.html
