我正在使用Python解析一个ascii文件并创建一个.csv,其中包含三列' day'' time'和' z'
我能够填充“#day;' '时间'和' z'使用以下命令从input.txt解析值:
import numpy as np
f = open ('input.txt', 'r')
lines = f.readlines()
f.close()
day=[];time=[];z=[]
for line in lines:
lstrip = line.strip()
if not lstrip.startswith('#'):
words=lstrip.split(' ')
day.append(words[0])
time.append(words[1])
z.append(words[2])
然而,当我尝试以下内容时:
zipped = zip(day, time, z)
np.savetxt('output.csv', zipped, delimiter=",", header="day, time, z", comments="")
我收到以下错误:
TypeError: Mismatch between array dtype ('|S15') and format specifier ('%.18e,%.18e,%.18e')
有没有办法设置列表的数据类型以避免此错误?
谢谢!
答案 0 :(得分:0)
我可以用以下方式复制您的问题:
x=['one','two','three']
y=['a','b','c']
z=['1','2','3']
zz=list(zip(x,y,z)) # py3
zz
Out[58]: [('one', 'a', '1'), ('two', 'b', '2'), ('three', 'c', '3')]
za=np.array(zz) # make list an array; note the dtype
za
Out[60]:
array([['one', 'a', '1'],
['two', 'b', '2'],
['three', 'c', '3']],
dtype='<U5')
np.savetxt('test',zz)
-------------------------------------------------------------------
...
TypeError: Mismatch between array dtype ('<U5') and format specifier ('%.18e %.18e %.18e')
尝试将字符串写为浮点数时出现同样的错误。但是,如果我将格式更改为字符串1:
np.savetxt('test',za,fmt='%10s')
cat test
one a 1
two b 2
three c 3
如果您的输入确实是数字,那么您可以在构建列表时将字符串转换为数字。
另一种选择是直接将列表写入csv
(使用文件写入)或使用Python csv
模块。