解决pandas使用read_csv()读取文件遇到的问题

yipeiwu_com6年前Python基础

如下:

数据文件:

上海机场 (sh600009)
24.11 3.58
东风汽车 (sh600006) 74.25 1.74
中国国贸 (sh600007) 26.38 2.66
包钢股份 (sh600010) 61.01 2.35
武钢股份 (sh600005) 75.85 1.3
浦发银行 (sh600000) 6.65 0.96

在使用read_csv() API读取CSV文件时求取某一列数据比较大小时,

df=pd.read_csv(output_file,encoding='gb2312',names=['a','b','c'])
df.b>20

报错

TypeError:'>'not supported between instances of 'str' and 'int'

从返回的错误信息可知应该是数据类型错误,读回来的是‘str'

in : df.dtypes
out:
 a object
 b object
 c object
 dtype: object

由此可知 df.b 类型是 object

查阅read_csv()文档 配置:

dtype : Type name or dict of column -> type, default None
Data type for data or columns. E.g. {'a': np.float64, 'b': np.int32} (unsupported with engine='python'). Use str or object to preserve and not interpret dtype.

New in version 0.20.0: support for the Python parser.

可知默认使用‘str'或‘object'保存

因此在读取时只需要修改 'dtype' 配置就可以

df=pd.read_csv(output_file,encoding='gb2312',names=['a','b','c'],dtype={'b':np.folat64})

以上这篇解决pandas使用read_csv()读取文件遇到的问题就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

解决Python中定时任务线程无法自动退出的问题

python的线程有一个类叫Timer可以,用来创建定时任务,但是它的问题是只能运行一次,如果要重复执行,则只能在任务中再调用一次timer,但这样就存在新的问题了,就是在主进程退出后,...

python将字符串转换成数组的方法

python将字符串转换成数组的方法。分享给大家供大家参考。具体实现方法如下: #----------------------------------------- # N...

Python线程之定位与销毁的实现

Python线程之定位与销毁的实现

背景 开工前我就觉得有什么不太对劲,感觉要背锅。这可不,上班第三天就捅锅了。 我们有个了不起的后台程序,可以动态加载模块,并以线程方式运行,通过这种形式实现插件的功能。而模块更新时候,后...

python中的print()输出

1.普通的输出: print(str)#str是任意一个字符串,数字··· 2.格式化输出: print('1,2,%s,%d'%('asd',4)) 1,2,asd,4 与C语...

python运行时间的几种方法

最早见过手写的,类似于下面这种: import datetime def time_1(): begin = datetime.datetime.now() sum =...