简体   繁体   中英

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:

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:

[50,60,70]

and then i want to get the following 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. This is due to how it searches for items in an array (for more information look for 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

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:

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:

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:

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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