Home > Enterprise >  Convert DMS values stored in a list to csv file using python
Convert DMS values stored in a list to csv file using python

Time:04-21

I have a long list of DMS values that look like below.

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']

I want to write this data as a csv file in the following format:

enter image description here

CodePudding user response:

You can use numpy and 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)
 )

Output file (as text):

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

CodePudding user response:

If lst is the list from your question, you can do:

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)

this writes 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

screenshot from LibreOffice:

enter image description here

  • Related