簡體   English   中英

將文本文件中的 x 和 y 坐標加載到 dataframe

[英]load x and y coordinates from a text file to a dataframe

我有一個如下所示的文本文件

Waypoints loaded from route:
  Nr   x coor   y coor       x coor   y coor  Direction
 ---  -------  -------      -------  -------  ---------
   1 (  -1400,    -920) -> (    900,    -920) Backwards
   2 (    900,    -920) -> (   2320,    -920) Backwards
   3 (   2320,    -920) -> (  10970,    -920) Forwards
   4 (  10970,    -920) -> (  -1400,    -920) Forwards

我想將這些 x 和坐標加載到 dataframe 中,它應該與文本文件中的表格具有相同的形狀,有 5 列

x coor start    y coor start    x coor end    y coor end    Direction

我嘗試用正則表達式分隔符自己做,但沒有成功

我為可怕的混亂道歉,但它有效。

試試這個。

import re
import pandas as pd
file = open('data.txt', 'r')


def ParseTerriblyFormattedFile(f):
    data = f.readlines()
    # Remove top 3 lines
    del data[:3]
    final_list = []
    for lines in data:
        lines = lines.strip()
        split_lines = re.split(r"[\(\)\,]", lines)
        split_lines.pop(3)
        split_lines.pop(0)
        final_list.append(split_lines)
    return final_list


output = ParseTerriblyFormattedFile(file)

df = pd.DataFrame(output, columns=['x coor start', 'y coor start', 'x coor end', 'y coor end', 'direction'])
print(df)

Output:

  x coor start y coor start x coor end y coor end   direction
0        -1400         -920        900       -920   Backwards
1          900         -920       2320       -920   Backwards
2         2320         -920      10970       -920    Forwards
3        10970         -920      -1400       -920    Forwards

Process finished with exit code 0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM