Home > Blockchain >  Numpy sort works oddly
Numpy sort works oddly

Time:10-24

I have a massive data = np.array([1000, 2500, 1400, 1800, 900, 4200, 2200, 1900, 3500]). I need to append an user input and sort data.

import numpy as np

data = np.array([1000, 2500, 1400, 1800, 900, 4200, 2200, 1900, 3500])

new_data = input()
data = np.append(data, new_data)
data = np.sort(data)
print(data)

Without append i have normal sorted array, but when i use it i have that

['1000' '1400' '1800' '1900' '2200' '2500' '3500' '4200' '654' '900']

I noticed that xxx number appear in the end of the list. xxxx digit as an input appears where it should be

['1000' '1400' '1800' '1900' '2200' '2222' '2500' '3500' '4200' '900']

CodePudding user response:

The data type of Input() is a string. This is why when you append it to the array, it considers each element as a string and sorts them by the first alphabet and then subsequent ones.

Check data type before and after -

#BEFORE APPENDING - 
>>type(data[3])
numpy.int64

#AFTER APPENDING - 
>>type(data[3])
numpy.str_

Instead, convert the input to int or float first -

import numpy as np

data = np.array([1000, 2500, 1400, 1800, 900, 4200, 2200, 1900, 3500])

new_data = int(input()) #<---- Look here!
data = np.append(data, new_data)
data = np.sort(data)
print(data)
2222
[ 900 1000 1400 1800 1900 2200 2222 2500 3500 4200]
  • Related