我正在尝试将包含以下内容的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)
但这会消耗来源中的#-sign:
[( 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"')]
答案 0 :(得分: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')])
关闭评论:
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')])