H
H
hudozhnin2016-02-06 14:50:17
Python
hudozhnin, 2016-02-06 14:50:17

How to convert in python an array of type object to a normal array like nparray?

There is a CSV file that I am loading into a pandas dataframe.
The data in the target column in the original file looks like this, for example:
"[1 2 3 4 42]"
The numbers separated by spaces should eventually be separate elements of the array, that is, this occurrence should result in an array of the form [1, 2, 3, 4, 42] and the corresponding type (nparray or any other that can be passed as a matrix of factors in the sklearn model).
They are loaded into the pandas frame as a result just like [1 2 3 4 42] and are elements of type object (I don’t really understand what this means, I’m new to python).
Tell me, please, how to convert this to an array, sorry, if it's quite simple, I honestly spent several hours on Google, I despaired.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
sim3x, 2016-02-06
@hudozhnin

use iPython/Jupiter for
experiments

In [1]: x = "[1 2 3 4 42]"

In [2]: type(x)
Out[2]: builtins.str

In [3]: help(type(x))

# хелп дает описание того что внутри находится

Help on class str in module builtins:

class str(object)
 |  str(object='') -> str
 |  str(bytes_or_buffer[, encoding[, errors]]) -> str
 |  
 |  Create a new string object from the given object. If encoding or
 |  errors is specified, then the object must expose a data buffer
 |  that will be decoded using the given encoding and error handler.
 |  Otherwise, returns the result of object.__str__() (if defined)
 |  or repr(object).
 |  encoding defaults to sys.getdefaultencoding().
 |  errors defaults to 'strict'.
####################

# убрали скобки и разсплитили строку в массив
In [4]: y = x.replace('[', '').replace(']', '').split()

In [5]: y
Out[5]: ['1', '2', '3', '4', '42']
# прошлись по массиву и правратили строки в интеджер
In [6]: z = [int(n) for n in y]

In [7]: z
Out[7]: [1, 2, 3, 4, 42]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question