0

Here's my code:

age=request.user.allusers.age
sex=request.user.allusers.sex
index_array = np.array(states)
index_array = [val-1 for val in index_array]
mask_array = np.zeros(193,dtype=float)
mask_array[index_array] = 1
mask_array=np.append(sex,mask_array)
mask_array=np.append(age,mask_array)
prob_array = clf.predict_proba([mask_array])

In the code sex is a string. So when compiling the value error is showing up. How can I append sex in the numpy array.

Here's the error:

ValueError: could not convert string to float: 'Female'
baduker
  • 19,152
  • 9
  • 33
  • 56
najmath
  • 261
  • 1
  • 3
  • 16
  • Show where the error occurs. What's the dtype of the arrray? Strings can only be added to string dtype arrays or structured arrays (compound dtype). What does `clf` accept? – hpaulj Mar 24 '18 at 15:24
  • That's a bad duplicate. We don't know that the OP needs a structured array. – hpaulj Mar 24 '18 at 15:49

1 Answers1

1
  • Simply insert the values inside the list
  • Give list as an argument to numpy array

    import numpy as np
    
    age=23
    sex="Female"
    
    info_list = [age, sex]
    print("This is list", info_list)
    
    numpy_info_list = np.array(info_list)
    print("This is numpy array", numpy_info_list)
    
  • Output:

    This is list [23, 'Female']
    This is numpy array ['23' 'Female']
    
  • Usually this is not good for predicting to give the data in the raw form

  • Instead you can convert Female to ===> 0 and Male to ====> 1
  • We should always try to convert the values to numbers
  • Sex is a type of categorical data which can take numerical values

  • One of the solution is to use scikitlearn label encoder for encoding the features if you have too may values for a particular features

  • I know its stupid to use a label encoder to encode the features but it's a solution
  • Here's an example... This is just an example related to sex

    le = preprocessing.LabelEncoder()
    >>> le.fit(["male", "female"])
    LabelEncoder()
    >>> list(le.classes_)
    ['male', 'female']
    >>> le.transform(["male", "male", "female"]) 
    array([1, 1, 2]...)
    
  • Other solution can be to use dictionary:

    age=23
    sex="female"
    sex_map = {"male": 1, "female": 2}
    
    info_list = [age, sex_map[sex]]
    print("This is list", info_list)
    
  • Output:

    This is list [23, 2]
    
Jai
  • 3,211
  • 2
  • 17
  • 26