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

yipeiwu_com7年前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设计】。

相关文章

TensorFlow2.0:张量的合并与分割实例

** 一 tf.concat( ) 函数–合并 ** In [2]: a = tf.ones([4,35,8]) In [3]:...

opencv3/Python 稠密光流calcOpticalFlowFarneback详解

opencv3/Python 稠密光流calcOpticalFlowFarneback详解

光流是由物体或相机的运动引起的图像对象在两个连续帧之间的视在运动模式.光流方法计算在t和 t+Δtt+Δt时刻拍摄的两个图像帧之间的每个像素的运动位置。这些方法被称为差分,因为它们基于图...

在Python中使用dict和set方法的教程

在Python中使用dict和set方法的教程

dict Python内置了字典:dict的支持,dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度。 举个例子,假设要...

Python 自动补全(vim)

Python 自动补全(vim)

一、vim python自动补全插件:pydiction 可以实现下面python代码的自动补全: 1.简单python关键词补全 2.python 函数补全带括号 3.pytho...

python 定义类时,实现内部方法的互相调用

每次调用内部的方法时,方法前面加 self. 举例: 例子参考百度知道里面的回答 class MyClass: def __init__(self): pass de...