Home > Mobile >  How to convert dataframe column of str to float numpy.ndarray?
How to convert dataframe column of str to float numpy.ndarray?

Time:09-26

I have column of str values which I want to convert to float numpy array, is there any built in function to do this? If not, How do I do this?

Dataframe looks as follows: enter image description here

Feature column has all values as str:

'[0. 0. 0. ... 0. 2.40159345 0. ],' 
'[0. 0. 0. ... 0. 8.59722424 0. ]', 
'[0. 0. 0. ... 0. 0. 0.]', 
'[0. 0. 0. ... 0. 0. 0.]', 
'[0. 0. 0. ... 0. 1.38265193 0. ]', 
'[0. 0. 0. ... 0. 0. 0.]',

I want it to become of type numpy array - numpy.ndarray of floats:

[0.         0.         0.         ... 0.         8.59722424 0.        ],
[0. 0. 0. ... 0. 0. 0.]', '[0. 0. 0. ... 0. 0. 0.],
[0.         0.         0.         ... 0.         1.38265193 0.        ],
[0. 0. 0. ... 0. 0. 0.],```

CodePudding user response:

AFAIK you'll have to do it manually:

rows = []
for row in df["Feature"]:
    rows.append([float(x) for x in row.split(" ")])
arr = np.Array(rows)

CodePudding user response:

You can use astype() function.

Convert dataframe as :

df = df.astype('int32')

Check this documentation of pandas.DataFrame.astype

  • Related