【问题标题】:numpy genfromtxt strings int mixed data typesnumpy genfromtxt strings int 混合数据类型
【发布时间】:2017-12-12 21:40:13
【问题描述】:

我正在尝试将具有以下内容的 csv 文件读入 numpy 数组:

1,85,104,2,"C"
2,71,82,2,"C#"
3,67,73,2,"D"
4,105,108,2,"D#"
5,103,100,2,"E"

这是编码的尝试:

import numpy as np
twg=np.genfromtxt(r'./Documents/gears.txt', delimiter=',',dtype=(int,int,int,int,object))
print (twg)

但这会占用源中的#-符号:

[( 1,  85, 104,   2, b'"C"') ( 2,  71,  82,   2, b'"C')
 ( 3,  67,  73,   2, b'"D"') ( 4, 105, 108,   2, b'"D')
 ( 5, 103, 100,   2, b'"E"')]

【问题讨论】:

  • 关闭 cmets。引号不能防止这种情况

标签: python csv numpy


【解决方案1】:

# 被视为注释标志。引用没有区别:

In [345]: txt=b'''1,85,104,2,"C"
     ...: 2,71,82,2,"C#"
     ...: 3,67,73,2,"D"
     ...: 4,105,108,2,"D#"
     ...: 5,103,100,2,"E"'''
In [346]: 
In [346]: np.genfromtxt(txt.splitlines(),delimiter=',',dtype=None)
Out[346]: 
array([(1,  85, 104, 2, b'"C"'), (2,  71,  82, 2, b'"C'),
       (3,  67,  73, 2, b'"D"'), (4, 105, 108, 2, b'"D'),
       (5, 103, 100, 2, b'"E"')],
      dtype=[('f0', '<i4'), ('f1', '<i4'), ('f2', '<i4'), ('f3', '<i4'), ('f4', 'S3')])

关闭 cmets:

In [347]: np.genfromtxt(txt.splitlines(),delimiter=',',dtype=None, comments=None
     ...: )
Out[347]: 
array([(1,  85, 104, 2, b'"C"'), (2,  71,  82, 2, b'"C#"'),
       (3,  67,  73, 2, b'"D"'), (4, 105, 108, 2, b'"D#"'),
       (5, 103, 100, 2, b'"E"')],
      dtype=[('f0', '<i4'), ('f1', '<i4'), ('f2', '<i4'), ('f3', '<i4'), ('f4', 'S4')])

【讨论】:

    猜你喜欢
    • 2016-08-14
    • 2013-08-17
    • 2017-06-21
    • 1970-01-01
    • 1970-01-01
    • 2014-09-10
    • 1970-01-01
    • 2018-08-27
    • 2018-01-06
    相关资源
    最近更新 更多