【问题标题】:Problem in reading text file with negative numbers读取带有负数的文本文件时出现问题
【发布时间】:2021-06-20 17:15:34
【问题描述】:

文本文件: 我有一个包含超过 87,000 个数据点的文本文件。文本文件格式如下:

  • X坐标-----Y坐标-----参数1 ------参数2--------
  • 2.744596610E-02 1.247197202E+00 7.121462841E-03 2.467938066E-05
  • 2.732558411E-02 1.242196291E+00 1.365028508E-02 6.262368697E-05
  • 2.713870635E-02 1.227254209E+00 1.958976965E-03-3.179617352E-06

两个以粗体突出显示的数字之间没有没有空格,因为前面有 -(减号) 符号,因此生成的 csv/pandas 数据帧会产生一些结果如下所示。

输出:

| X Coordinate    | Y Coordinate    | Parameter 1     | Parameter 2     | 
| --------------  | --------------  | --------------- | ------------    |
| 2.744596610E-02 | 1.247197202E+00 | 7.121462841E-03 | 2.467938066E-05 |
| 2.732558411E-02 | 1.242196291E+00 | 1.365028508E-02 | 6.262368697E-05 |
| 2.713870635E-02 | 1.227254209E+00 | 1.958976965E-03-3.179617352E-06|  |

必填:

| X Coordinate    | Y Coordinate    | Parameter 1     | Parameter 2     | 
| --------------  | --------------  | --------------- | ------------    |
| 2.744596610E-02 | 1.247197202E+00 | 7.121462841E-03 | 2.467938066E-05 |
| 2.732558411E-02 | 1.242196291E+00 | 1.365028508E-02 | 6.262368697E-05 |
| 2.713870635E-02 | 1.227254209E+00 | 1.958976965E-03 |-3.179617352E-06 |

我对 python/pandas 很熟悉,所以任何编程技术都会有很大帮助。

【问题讨论】:

  • 使用准确的输入文件样本编辑您的问题。 Pandas as read_fwf()(读取固定宽度文件),所以如果列完全对齐,这就是您需要的功能。
  • 嗨!以下任何一个答案是否有效?如果是这样并且如果您愿意,您可以考虑accepting 其中之一向其他人发出问题已解决的信号。如果没有,您可以提供反馈,以便改进(或完全删除)。

标签: python pandas dataframe csv


【解决方案1】:
import re

DATAPOINT = re.compile(r'-?\d{1}\.\d{9}E[+-]\d{2}')

data = []
with open("data.txt") as fp:
    next(fp) # Ignore header (1st line)
    for l in fp.readlines():
        data.append(DATAPOINT.findall(l))

df = pd.DataFrame(data, columns=['X Coordinate', 'Y Coordinate', 'Parameter 1', 'Parameter 2'])
>>> df
      X Coordinate     Y Coordinate      Parameter 1       Parameter 2
0  2.744596610E-02  1.247197202E+00  7.121462841E-03   2.467938066E-05
1  2.732558411E-02  1.242196291E+00  1.365028508E-02   6.262368697E-05
2  2.713870635E-02  1.227254209E+00  1.958976965E-03  -3.179617352E-06

【讨论】:

    【解决方案2】:

    regex 可以在其中放置空格:

    import re
    
    with open("current.txt") as fh, open("new.txt", "w") as gh:
        # skip the first line
        fh.readline()
    
        # for other lines..
        for line in fh:
           gh.write(re.sub(r"(E[+-]\d+)(\S)(\d|\.)", r"\1 -\3", line))
    

    然后

    # you can include the header, I didn't paste
    df = pd.read_csv("new.txt", sep=" ", header=None)
    

    给我

    >>> df
    
              0         1         2         3
    0  0.027446  1.247197  0.007121  0.000025
    1  0.027326  1.242196 -0.013650  0.000063
    2  0.027139 -1.227254  0.001959 -0.000003
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-18
      • 1970-01-01
      • 2016-05-08
      • 1970-01-01
      • 2021-09-11
      相关资源
      最近更新 更多