Python:read_csv into dataframe无法在中转换对象

2024-09-30 01:26:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我输入read_csv的csv文件是一对列,有百分比变化,但它有一些隐藏字符。来自repr(data2)

enter image description here

我尝试了以下方法:

data2 = pd.read_csv('C:/Users/nnayyar/Documents/MonteCarlo2.csv', "\n", delimiter = ",", dtype = float)

得到以下错误:

^{pr2}$

我试了几件事:

float(data2.replace('/n',''))
map(float, data2.strip().split('\r\n'))

但分别收到了各种各样的错误 TypeError:float()参数必须是字符串或数字 AttributeError:“DataFrame”对象没有属性“strip”

任何将CSV对象类型转换为float类型的帮助都会很有帮助!谢谢!!在


Tags: 文件csv对象方法read错误float字符
1条回答
网友
1楼 · 发布于 2024-09-30 01:26:12

如果您的整个csv都有百分号,则以下操作将起作用:

In [203]:
import pandas as pd
import io
t="""0   1   2  3
1.5%  2.5%   6.5%   0.5%"""
# load some dummy data
df = pd.read_csv(io.StringIO(t), delim_whitespace=True)
df

Out[203]:
      0     1     2     3
0  1.5%  2.5%  6.5%  0.5%

In [205]:
# apply a lambda that replaces the % signs and cast to float    
df.apply(lambda x: x.str.replace('%','')).astype(float)

Out[205]:
     0    1    2    3
0  1.5  2.5  6.5  0.5

因此,这将对每个调用向量化str.replace的列应用lambda来删除%符号,然后我们可以使用astype将类型转换为float

因此,在您的情况下,以下方法应该有效:

^{pr2}$

相关问题 更多 >

    热门问题