Home > OS >  How to convert a list into an np.array in Python?
How to convert a list into an np.array in Python?

Time:02-02

I have this type of list named "preds":

[False  True False  True  True  True  True  True  True  True  True  True
  True False False  True  True  True  True False  True  True False  True
 False False  True False  True  True  True  True  True False False False
 False  True False False  True  True  True  True False False False False
  True False  True False  True  True  True  True  True False  True False
  True]

It's the prediction i obtained with the logistic regression model. I need to convert it into an array containing 1 if the element in the list is "True" and 0 if the element is "False". I have already tried using np.array(preds) or np.asarray(preds) but it doesn't work.

Please can somebody help me finding a solution? I am sorry for the stupid question but I am very new to programming. Thanks in advance.

I already tried using the command of the numpy library like np.array(preds) or np.asarray(preds). I need to obtain a new vector with the same number of elements, in which 1 corresponds to True and 0 corresponds to False

CodePudding user response:

You can easily convert it into a regular Python list of 1s and 0s with [1 if p else 0 for p in preds], and then pass that to np.array or whatever, e.g.:

import numpy as np
preds = [False, True, False, True,  True,  True,  True,  True,  True,  True,
         True,  True, True,  False, False, True,  True,  True,  True,  False,
         True,  True, False, True,  False, False, True,  False, True,  True,
         True,  True, True,  False, False, False, False, True,  False, False,
         True,  True, True,  True,  False, False, False, False, True,  False,
         True, False, True,  True,  True,  True,  True,  False,  True, False,
         True]
np_preds = np.array([1 if p else 0 for p in preds])

CodePudding user response:

You can use a list comprehension to convert the preds list into a list of 1s and 0s:

converted_preds = [1 if x else 0 for x in preds]

This creates a new list, converted_preds, in which each element is either 1 if the corresponding element in preds is True, or 0 if the corresponding element in preds is False.

CodePudding user response:

Convert to integer before handing values to numpy:

arr = np.array(list(map(int, preds)))
  • Related