【问题标题】:How to slice array by its index in 2D array in python using numpy如何使用numpy在python中的二维数组中按索引对数组进行切片
【发布时间】:2022-01-24 06:53:00
【问题描述】:

我写了以下代码:

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

【问题讨论】:

    标签: python numpy


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

      列表列表:

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

      或数据框:

      In [281]: pd.DataFrame(altlist)
      Out[281]: 
             0   1
      0   John  50
      1   Alex  60
      2  Smith  70
      

      【讨论】:

        猜你喜欢
        • 2014-04-04
        • 2018-11-07
        • 1970-01-01
        • 2020-01-20
        • 1970-01-01
        • 1970-01-01
        • 2020-12-03
        • 1970-01-01
        • 2022-10-04
        相关资源
        最近更新 更多