Python genfromtxt 多种数据类型

标签 python python-2.7 numpy genfromtxt

我想使用 genfromtxt 读取一个 csv 文件。 我有六列是 float ,一列是字符串。

如何设置数据类型,以便将 float 列作为 float 读入,将 string 列作为字符串读入?我试过 dtype='void' 但这不起作用。

建议?

谢谢

.csv文件

999.9, abc, 34, 78, 12.3
1.3, ghf, 12, 8.4, 23.7
101.7, evf, 89, 2.4, 11.3



x = sys.argv[1]
f = open(x, 'r')
y = np.genfromtxt(f, delimiter = ',', dtype=[('f0', '<f8'), ('f1', 'S4'), (\
'f2', '<f8'), ('f3', '<f8'), ('f4', '<f8'), ('f5', '<f8'), ('f6', '<f8')])

ionenergy = y[:,0]
units = y[:,1]

错误:

ionenergy = y[:,0]
IndexError: invalid index

当我指定单一数据类型时,我没有收到此错误。

最佳答案

dtype=None告诉genfromtxt猜测合适的数据类型。

来自 the docs :

dtype: dtype, optional

Data type of the resulting array. If None, the dtypes will be determined by the contents of each column, individually.

(我的重点。)


由于您的数据是用逗号分隔的,因此请务必包含 delimiter=','否则 np.genfromtxt会将每一列(最后一列除外)解释为包含一个字符串字符(逗号),因此错误地为每一列分配一个字符串数据类型。

例如:

import numpy as np

arr = np.genfromtxt('data', dtype=None, delimiter=',')

print(arr.dtype)
# [('f0', '<f8'), ('f1', 'S4'), ('f2', '<i4'), ('f3', '<f8'), ('f4', '<f8')]

这显示了每一列的名称和数据类型。例如,('f3', <f8)表示第四列的名称为 'f3'并且是 dtype 'i意味着它是一个整数数据类型。如果您需要第三列是 float dtype,那么有几个选项。

  1. 您可以通过在数据中添加小数点来手动编辑数据 第三列强制 genfromtxt 解释该列中的值 是一个 float 据类型。
  2. 您可以在对 genfromtxt 的调用中明确提供 dtype

    arr = np.genfromtxt(
        'data', delimiter=',',
        dtype=[('f0', '<f8'), ('f1', 'S4'), ('f2', '<f4'), ('f3', '<f8'), ('f4', '<f8')])
    

print(arr)
# [(999.9, ' abc', 34, 78.0, 12.3) (1.3, ' ghf', 12, 8.4, 23.7)
#  (101.7, ' evf', 89, 2.4, 11.3)]

print(arr['f2'])
# [34 12 89]

错误信息IndexError: invalid index正在由行生成

ionenergy = y[:,0]

当你有混合数据类型时,np.genfromtxt返回 structured array .您需要阅读结构化数组,因为访问列的语法不同于用于同质数据类型的普通数组的语法。

而不是 y[:, 0] , 以访问结构化数组的第一列 y , 使用

y['f0']

或者,更好的是,提供 names np.genfromtxt 中的参数,因此您可以使用更相关的列名称,例如 y['ionenergy'] :

import numpy as np
arr = np.genfromtxt(
    'data', delimiter=',', dtype=None,
    names=['ionenergy', 'foo', 'bar', 'baz', 'quux', 'corge'])

print(arr['ionenergy'])
# [ 999.9    1.3  101.7]

关于Python genfromtxt 多种数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19622997/

相关文章:

python - Django Admin : change select box for foreign key to search autocomplete, 喜欢搜索对象

python - Kafka Consumer未获取所有消息

python - 循环返回整数之和

python-2.7 - 64 位 Windows 7 上的 Python 32 或 64?安装 easy_install 会有什么影响?

python - 使用带有间隔的 GridSearchCV

python - 为具有最小窗口长度的连续系列过滤 pandas 或 numpy 数组

Python 在删除重复的 python 安装后要求 mac 上的旧路径

java - 使用 Jpype 将 numpy 数组传递给 Java

python - 将 numpy.ndarray 转换为字符串

python - 如何在 Python OpenCV 中改进可变镜头模糊算法?