【问题标题】:Issues importing datasets (txt file) with Python using numpy library genfromtxt function使用 numpy 库 genfromtxt 函数通过 Python 导入数据集(txt 文件)的问题
【发布时间】:2017-03-04 13:53:13
【问题描述】:

我正在尝试学习 Python,但是我正在尝试导入数据集但无法正常工作...

此数据集包含 16 列和 16 320 行,保存为 txt 文件。我使用 genfromtxt 函数如下:

import numpy as np  
dt=np.dtype([('name', np.str_, 16),('platform', np.str_, 16),('year', np.float_, (2,)),('genre', np.str_, 16),('publisher', np.str_, 16),('na_sales', np.float_, (2,)), ('eu_sales', np.float64, (2,)), ('jp_sales', np.float64, (2,)), ('other_sales', np.float64, (2,)), ('global_sales', np.float64, (2,)), ('critic_scores', np.float64, (2,)),('critic_count', np.float64, (2,)),('user_scores', np.float64, (2,)),('user_count', np.float64, (2,)),('developer', np.str_, 16),('rating', np.str_, 16)])  
data=np.genfromtxt('D:\\data3.txt',delimiter=',',names=True,dtype=dt)

我收到此错误:

ValueError: size of tuple must match number of fields.

但我的 dt 变量包含 16 种类型,每列一种。 我指定了数据类型,否则字符串会被 nan 替换。

任何帮助将不胜感激。

【问题讨论】:

  • 建议:从您的 data3.txt 文件中发布一些第一行。你确定它有 16 列吗?
  • 为什么 dtype 中的所有 (2,)?您定义了 16 个字段,但所有浮点数都加倍。您是否尝试过dtype=None 负载?这让它推断出最好的数据类型。

标签: python numpy dataset genfromtxt


【解决方案1】:

查看使用您的dt 制作的数组:

In [78]: np.ones((1,),dt)
Out[78]: 
array([ ('1', '1', [ 1.,  1.], '1', '1', [ 1.,  1.], [ 1.,  1.], [ 1.,  1.], 
      [ 1.,  1.], [ 1.,  1.], [ 1.,  1.], [ 1.,  1.], [ 1.,  1.], 
      [ 1.,  1.], '1', '1')], 
      dtype=[('name', '<U16'), ('platform', '<U16'), ('year', '<f8', (2,)), ('genre', '<U16'), ('publisher', '<U16'), ('na_sales', '<f8', (2,)), ('eu_sales', '<f8', (2,)), ('jp_sales', '<f8', (2,)), ('other_sales', '<f8', (2,)), ('global_sales', '<f8', (2,)), ('critic_scores', '<f8', (2,)), ('critic_count', '<f8', (2,)), ('user_scores', '<f8', (2,)), ('user_count', '<f8', (2,)), ('developer', '<U16'), ('rating', '<U16')])

我数 26 1s(字符串和浮点数),而不是您需要的 16 个。您是否认为 (2,) 表示双精度数?它表示一个 2 元素子字段。

取出所有那些 (2,)

In [80]: np.ones((1,),dt)
Out[80]: 
array([ ('1', '1',  1., '1', '1',  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1., '1', '1')], 
      dtype=[('name', '<U16'), ('platform', '<U16'), ('year', '<f8'), ('genre', '<U16'), ('publisher', '<U16'), ('na_sales', '<f8'), ('eu_sales', '<f8'), ('jp_sales', '<f8'), ('other_sales', '<f8'), ('global_sales', '<f8'), ('critic_scores', '<f8'), ('critic_count', '<f8'), ('user_scores', '<f8'), ('user_count', '<f8'), ('developer', '<U16'), ('rating', '<U16')])

现在我有 16 个字段可以正确解析您的 16 列。

但通常dtype=None 也同样有效。它让genfromtxt 推断出每个字段的最佳数据类型。在这种情况下,它将从列标题行(您的 names=True 参数)中获取字段名称。

在将复杂的代码行放入更大的脚本之前测试它们是个好主意。特别是如果你在学习的过程中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-17
    • 2015-10-04
    • 2011-04-15
    • 2019-04-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多