【发布时间】:2018-03-06 13:32:13
【问题描述】:
这是我用来读取 .dat 文件的代码:
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv('data.dat', sep='\s+')
plt.figure()
plt.plot(df['yh_center[2]'], df['tot_scale01[4]'], 'ro')
plt.xlabel('yh_center')
plt.ylabel('tot_scale01[4]')
plt.savefig('name.pdf')
plt.show()
当 dat 中没有单独的单词“upper”时,它会正确读取。文件。 但是,我将有许多 .dat 文件包含“upper”一词,这会导致错误。
.dat 文件如下所示:
#labels: yh_lower[1] yh_center[2] yh_upper[3] tot_scale01[4]
#neval: 200000
#overflow:lower center upper 0.0000000000E+000 0.0000000000E+000 0.0000000000E+000 0.0000000000E+000
然后在第 4 行输入实际数据
-4.4000000000E+000 -4.3000000000E+000 -4.2000000000E+000 0.0000000000E+000
然后我还有 43 行数据,最后一行是
#nx: 3
(实际上有100多列数据,但这应该会改变......原理应该以前4列显示)
完整的错误报告是
Traceback (most recent call last):
File "<ipython-input-1-00512d6cb966>", line 1, in <module>
runfile('Private, so deleted that one here')
File "/usr/lib/python3.4/site-packages/spyderlib/widgets/externalshell/sitecustomize.py", line 685, in runfile
execfile(filename, namespace)
File "/usr/lib/python3.4/site-packages/spyderlib/widgets/externalshell/sitecustomize.py", line 85, in execfile
exec(compile(open(filename, 'rb').read(), filename, 'exec'), namespace)
File "/home/ttp/manbrunn/Documents/NNLOJETexe/HJtest/funktioniert.py", line 15, in <module>
plt.plot(df['yh_center[2]'], df['tot_scale01[4]'], 'ro')
File "/usr/lib64/python3.4/site-packages/matplotlib/pyplot.py", line 3099, in plot
ret = ax.plot(*args, **kwargs)
File "/usr/lib64/python3.4/site-packages/matplotlib/axes/_axes.py", line 1374, in plot
self.add_line(line)
File "/usr/lib64/python3.4/site-packages/matplotlib/axes/_base.py", line 1504, in add_line
self._update_line_limits(line)
File "/usr/lib64/python3.4/site-packages/matplotlib/axes/_base.py", line 1515, in _update_line_limits
path = line.get_path()
File "/usr/lib64/python3.4/site-packages/matplotlib/lines.py", line 874, in get_path
self.recache()
File "/usr/lib64/python3.4/site-packages/matplotlib/lines.py", line 575, in recache
x = np.asarray(xconv, np.float_)
File "/usr/lib64/python3.4/site-packages/numpy/core/numeric.py", line 462, in asarray
return array(a, dtype, copy=False, order=order)
ValueError: could not convert string to float: 'upper'
【问题讨论】:
-
请edit问题包含一些失败的CSV文件的文本示例。
-
我发现问题不在于主题标签。它也适用于主题标签。但是当我不删除“上”这个词时,它不适用于上面的错误。
-
我无法用您提供的少量“数据”进行复制。读取包含您给出的行的单行不会导致错误。一般来说,Pandas 通常足够聪明,可以在有字符串的情况下将数据读取为“对象”。
-
在任何情况下,您都可以尝试将参数
dtype='object'添加到read_csv函数中。然后,您必须将数据框中的所有单词替换为空值或数字,之后您可以转换为浮点数。 -
我猜这是个玩笑。这只是因为我没有把它放在代码括号中。现在我做到了。