[英]How to slice array by its index in 2D array in python using numpy
I have written the following code:我写了以下代码:
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
if i input the following values this will give the following output:如果我输入以下值,这将给出以下 output:
array([[1, 2, 3],
[4, 5, 6]])
but i want first row of matrix to enter as string values like:但我希望矩阵的第一行作为字符串值输入,例如:
["John","Alex","Smith"]
and 2nd row of matrix as integer values like:和矩阵的第二行作为 integer 值,如:
[50,60,70]
and then i want to get the following output:然后我想得到以下output:
Name: John , Marks: 50
Name: Alex , Marks: 60
Name: Smith, Marks: 70
Numpy requires that all values in a matrix are of the same type. Numpy 要求矩阵中的所有值都属于同一类型。 This is due to how it searches for items in an array (for more information look for strides
)这是由于它如何搜索数组中的项目(有关更多信息,请查找strides
)
Therefore, if You want text data in Your array, You must change the type of an entire array to a type which supports strings.因此,如果您想要数组中的文本数据,您必须将整个数组的类型更改为支持字符串的类型。
An alternative would be to have an array for names and a separate ones for values.另一种方法是为名称设置一个数组,为值设置一个单独的数组。 Also, You could use pandas.DataFrame
as it a direct solution to Your problem此外,您可以使用pandas.DataFrame
直接解决您的问题
A list of lists:列表列表:
In [274]: alist = [["John","Alex","Smith"],[50,60,70]]
In [275]: alist
Out[275]: [['John', 'Alex', 'Smith'], [50, 60, 70]]
Simply calling np.array
makes an array that contains the strings, the minimal common dtype:只需调用np.array
创建一个包含字符串的数组,这是最小的常见 dtype:
In [276]: np.array(alist)
Out[276]:
array([['John', 'Alex', 'Smith'],
['50', '60', '70']], dtype='<U21')
We can also specify object
, but such an array is virtually the same as the original list:我们也可以指定object
,但这样的数组实际上与原始列表相同:
In [277]: np.array(alist, dtype=object)
Out[277]:
array([['John', 'Alex', 'Smith'],
[50, 60, 70]], dtype=object)
A "transpose" of that list:该列表的“转置”:
In [278]: altlist = list(zip(*alist))
In [279]: altlist
Out[279]: [('John', 50), ('Alex', 60), ('Smith', 70)]
that can be used to make a structured array
with a compound dtype:可用于制作具有复合 dtype 的structured array
:
In [280]: np.array(altlist, dtype='U10,int')
Out[280]:
array([('John', 50), ('Alex', 60), ('Smith', 70)],
dtype=[('f0', '<U10'), ('f1', '<i8')])
or a dataframe:或 dataframe:
In [281]: pd.DataFrame(altlist)
Out[281]:
0 1
0 John 50
1 Alex 60
2 Smith 70
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.