代码之家  ›  专栏  ›  技术社区  ›  CES

使用python将存储在列表中的DMS值转换为csv文件

  •  1
  • CES  · 技术社区  · 2 年前

    我有一长串DMS值,如下所示。

    lst = ['9', '22', '26.9868', 'N',
           '118', '23', '48.876', 'E',
           '9', '22', '18.6132', 'N',
           '118', '23', '5.2188', 'E',
           '9', '19', '41.4804', 'N',
           '118', '19', '23.1852', 'E']
    

    我想以以下格式将此数据写入csv文件:

    enter image description here

    2 回复  |  直到 2 年前
        1
  •  2
  •   mozway    2 年前

    你可以用 numpy pandas :

    lst = ['9', '22', '26.9868', 'N',
           '118', '23', '48.876', 'E',
           '9', '22', '18.6132', 'N',
           '118', '23', '5.2188', 'E',
           '9', '19', '41.4804', 'N',
           '118', '19', '23.1852', 'E']
    
    import numpy as np
    import pandas as pd
    (pd.DataFrame(np.array(lst).reshape(-1,4),
                  columns=['deg', 'min', 'sec', 'direction'])
       .to_csv('filename.csv', index=False)
     )
    

    输出文件(作为文本):

    deg,min,sec,direction
    9,22,26.9868,N
    118,23,48.876,E
    9,22,18.6132,N
    118,23,5.2188,E
    9,19,41.4804,N
    118,19,23.1852,E
    
        2
  •  2
  •   Andrej Kesely    2 年前

    如果 lst 这是你的问题清单,你可以做:

    import csv
    
    with open("data.csv", "w") as f_out:
        csv_writer = csv.writer(f_out)
        i = iter(lst)
        csv_writer.writerow(["deg", "min", "sec", "direction"])
        for t in zip(*[i] * 4):
            csv_writer.writerow(t)
    

    这写着 data.csv :

    deg,min,sec,direction
    9,22,26.9868,N
    118,23,48.876,E
    9,22,18.6132,N
    118,23,5.2188,E
    9,19,41.4804,N
    118,19,23.1852,E
    

    LibreOffice截图:

    enter image description here