-1

I want to make a matrix whose elements are numbers in a few columns and strings in other columns. Then, I want to sort them based on numbers in one of the columns that contains numbers. I tried using numpy but it did not work. What's the easiest way to do so? Pandas, Tuple, or something else?

import numpy as np
a=np.array([[10,'b'],[2,'z'],[4,'r']])
print(a)
print(np.sort(a))

Output:

array([['10', 'b'],
       ['2', 'z'],
       ['4', 'r']], dtype='<U11')

array([['10', 'b'],
       ['2', 'z'],
       ['4', 'r']], dtype='<U11')

It seems that it has converted the numbers to strings.

3
  • you have matrix using numpy or netsted list? Commented Oct 11, 2019 at 18:13
  • @AkashPagar I have nothing. I want to make a data structure and fill out the elements with numbers and strings. Here, I just gave an example of what happens if I choose numpy array as data structure. Commented Oct 11, 2019 at 18:15
  • Read your documentation at docs.scipy.org/doc/numpy/reference/generated/numpy.array.html : a=np.array([(10,'b'),(2,'z'),(4,'r')],dtype='|i4, c') Commented Oct 11, 2019 at 18:29

2 Answers 2

2

-- Hi Albert,

Since you seem to have mixed data types, I would propose to use pandas.

df = pd.DataFrame(
    data=[[10,'b'],[2,'z'],[4,'r']]
    , columns=['numbers', 'characters']
)

df.sort_values('numbers', ascending=False)
Sign up to request clarification or add additional context in comments.

Comments

1

You can have matrix in nested list format also, so sorting can be done on first element. As in your case first element in matrix is string integer, so it needs to be typecasted in integer for sorting.

a = [['10', 'b'], ['2', 'z'], ['4', 'r']]
print(a)
a = sorted(a, key=lambda x: int(x[0]))
print(a)

Output:

[['10', 'b'], ['2', 'z'], ['4', 'r']]
[['2', 'z'], ['4', 'r'], ['10', 'b']]

else if you want to keep in numpy array then solution will be this.

a=np.array([[10,'b'],[2,'z'],[4,'r']])
print(a)
a = sorted(a, key=lambda x: int(x[0]))
a = np.array(a)
print(a)

output:

[['10' 'b']
 ['2' 'z']
 ['4' 'r']]
[['2' 'z']
 ['4' 'r']
 ['10' 'b']]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.