Home > Software engineering >  how to convert pandas dataframe to numpy array of float data type
how to convert pandas dataframe to numpy array of float data type

Time:01-09

I have a .csv file and I want to convert it to numpy dtype('float64')

my code

import pandas as pd
import numpy as np
from pandas import read_csv

df=read_csv('input.csv')
df=df['data']
df.to_numpy() ---> produces numpy array of object data type and i want it to be dtype('float64')

Hope experts may help me.Thanks.

Data sample

0        -3.288733e-08, 1.648743e-09, 2.202711e-08, 2.7...
1        2.345769e-07, 2.054583e-07, 1.610073e-07, 1.14...
2        -1.386798e-07, -8.212822e-08, -4.192486e-08, -...
3        -4.234607e-08, 2.526512e-10, 2.222485e-08, 3.3...
4        3.899913e-08, 5.349818e-08, 5.65899e-08, 5.424...
       

                    ...                        

CodePudding user response:

If same number of floats in each row is possible use Series.str.split with cast to floats and then convert DataFrame to numpy array:

df=read_csv('input.csv')

arr = df['data'].str.split(', ', expand=True).astype(float).to_numpy()
  • Related