numpy.loadtxt 值错误:要解包的值太多

3
import matplotlib 
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import matplotlib.dates as mdates
import numpy as np
import time

dt = 'i4,i4,i4,a5,f9'
month,day,year,time,price = np.loadtxt('spyTestTest.txt', 
delimiter='  ',dtype = dt)

我正在尝试在以下示例数据上运行此代码

8 18 2014 9:30 196.79

8 18 2014 9:31 196.8249

8 18 2014 9:32 196.825

8 18 2014 9:33 196.88

8 18 2014 9:34 196.887

8 18 2014 9:35 196.835

8 18 2014 9:36 196.81

8 18 2014 9:37 196.81

8 18 2014 9:38 196.81

然而,我遇到了一个错误:

值错误:拆包的值太多。

我在网上看到说当你有更多的变量要解析时,就会出现这种情况,但是在我看来,我有5个变量和5列文本。有什么建议吗?


如果您的文字看起来像您发布的那样,中间带有空格,那么np.loadtext将读取\n并尝试将其拆分为5个值并失败。但是,如果这只是由于格式不佳,请进一步编辑您的问题以准确表示其实际情况。 - ljetibo
请不要使用 time 作为变量名。这会覆盖你正在导入的 time 模块。 - Marcin
你也可以使用struct库来完成这种操作,避免使用numpy https://docs.python.org/2/library/struct.html - qwwqwwq
你有检查下面的答案吗? - Saullo G. P. Castro
1个回答

4
作为您的输入文件已经格式化,使用unpack=True,这应该可以解决您的问题。
month,day,year,time_k,price = np.loadtxt('spyTestTest.txt', delimiter=' ',dtype = dt, unpack=True);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接