【问题标题】:Reading in .dat files with the word "upper" included causes problems读取包含“upper”一词的 .dat 文件会导致问题
【发布时间】: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 函数中。然后,您必须将数据框中的所有单词替换为空值或数字,之后您可以转换为浮点数。
  • 我猜这是个玩笑。这只是因为我没有把它放在代码括号中。现在我做到了。

标签: python pandas file


【解决方案1】:

您可以通过在将数据传递给 pandas 之前从每行中删除任何前导文本来预解析数据,例如:

import pandas as pd
import re

with open('data.dat') as f_input:
    header = next(f_input).split()[1:]
    next(f_input)
    next(f_input)

    data = [line.strip().split() for line in f_input]

df = pd.DataFrame(data[:-1], dtype='float', columns=header)

此版本还可以从第一行中提取列名。


如果upper 只出现在第三行(而不是在整个文件中随机出现),您可以简单地使用skiprows 告诉Pandas 从第四行开始读取,因为您有#nx: 3在最后一行,使用skipfooter 也可以跳过:

import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv('data.dat', sep='\s+', skiprows=3, skipfooter=1, header=None)

在 Pandas 0.22.0 上测试

【讨论】:

  • 感谢您的回复。现在有一个新的错误 KeyError: 'yh_center[2]' 我猜是因为现在一切都是浮点数,我不能再引用 yh_center 了。
  • 尝试在data = 行之前添加两次next(f_input) 以跳过前两行。
  • 错误仍然存​​在。所以我想我的想法是错误的,为什么它不起作用。
  • 也试试我添加的skiprowsskipfooter 想法。您也可以将您的.dat 文件放在pastebin 之类的位置,并在此处添加指向它的链接,然后我们可以重现问题。
  • 感谢您帮助我。不幸的是,错误保持不变。这很奇怪。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-19
  • 1970-01-01
  • 1970-01-01
  • 2021-04-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多