如何将Pandas DataFrame 转换为浮点数据类型的NumPy数组

huangapple go评论66阅读模式
英文:

how to convert pandas dataframe to numpy array of float data type

问题

我有一个.csv文件,我想将它转换为numpy数据类型('float64')

我的代码

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

df = read_csv('input.csv')
df = df['data']
df.to_numpy()  # 产生了一个对象数据类型的numpy数组,我希望它的数据类型是'float64'

希望专家们能帮助我。谢谢。

数据示例

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...
...
英文:

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...
       

                    ...                        

答案1

得分: 0

如果每行中的浮点数数量相同是可能的,可以使用 Series.str.split 来拆分,并将结果转换为浮点数,然后将 DataFrame 转换为 NumPy 数组:

df = read_csv('input.csv')

arr = df['data'].str.split(',', expand=True).astype(float).to_numpy()
英文:

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()

huangapple
  • 本文由 发表于 2023年1月9日 14:06:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/75053685.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定