繁体   English   中英

如何使用 numpy 在 python 的二维数组中按其索引对数组进行切片

[英]How to slice array by its index in 2D array in python using numpy

我写了以下代码:

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

如果我输入以下值,这将给出以下 output:

array([[1, 2, 3],
       [4, 5, 6]])

但我希望矩阵的第一行作为字符串值输入,例如:

["John","Alex","Smith"]

和矩阵的第二行作为 integer 值,如:

[50,60,70]

然后我想得到以下output:

Name: John , Marks: 50
Name: Alex , Marks: 60
Name: Smith, Marks: 70

Numpy 要求矩阵中的所有值都属于同一类型。 这是由于它如何搜索数组中的项目(有关更多信息,请查找strides

因此,如果您想要数组中的文本数据,您必须将整个数组的类型更改为支持字符串的类型。

另一种方法是为名称设置一个数组,为值设置一个单独的数组。 此外,您可以使用pandas.DataFrame直接解决您的问题

列表列表:

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)]

可用于制作具有复合 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')])

或 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM