python - NumPy 的 : read data from CSV having numerals as string

标签 python csv numpy

我正在使用以下命令在 python 中读取 .csv 文件:

data = np.genfromtxt('home_data.csv', dtype=float, delimiter=',', names=True) 

此 csv 有一列包含邮政编码,邮政编码是数字,但采用字符串格式,例如“85281”。此列的值为 nan:

data['zipcode']
Output : array([ nan,  nan,  nan, ...,  nan,  nan,  nan])

如何将字符串中的这些值转换为整数,以便获得值数组而不是“nan”。

最佳答案

你必须帮助 genfromtxt 一点:

 data = np.genfromtxt('home_data.csv',
 dtype=[int,float],delimiter=',',names=True,
 converters={0: lambda b:(b.decode().strip('"'))})

每个字段都以字节为单位收集。 float(b'1\n') 返回 1.0 ,但 float(b'"8210"') 给出错误。 converters 选项允许为每个字段(此处为字段 0)定义一个函数以进行正确的转换,此处转换为字符串(解码)并删除(剥离)尾随 "

如果 home_data.csv 是:

zipcode,val
"8210",1
"8320",2
"14",3

您将获得:

data -> array([(8210, 1.0), (8320, 2.0), (14, 3.0)], dtype=[('zipcode', '<i4'), ('val', '<f8')])
data['zipcode'] -> array([8210, 8320,   14])

关于python - NumPy 的 : read data from CSV having numerals as string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34308786/

相关文章:

silverlight - 什么是好的 Silverlight CSV 阅读器?

python - 使用 Python 从网页中抓取表格

python - 使用 numpy ufuncs 与内置运算符

python - 为什么此命令 python manage.py shell 出现错误?

python - Pip 安装 Django Windows 10

python - Python 中的 azure.ai.translation.document - 无法使用当前权限访问源文档位置

python - 在 3D matplotlib 中显示地理引用 DEM 表面

python - 如何在同一文件中编写脚本/库?

java - 从数据框中的列中删除特殊字符

python - 在 numpy 数组上的紧密双 for 循环中高效使用 python 生成器