Python Forum
change item in column based on the item before[solved]
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
change item in column based on the item before[solved]
#5
I have also tried
import os
from pathlib import Path
import pandas as pd
import datetime

def convert_file():
    # Set start directory same as script
    os.chdir(os.path.abspath(os.path.dirname(__file__)))

    infile = Path('.') / 'gauga20211_19790101-20120101.txt'
    outfile = Path('.') / 'newfile.csv'

    with infile.open() as fp, outfile.open('w') as fout:
        startdate = None
        starttime = None
        nexttime = 0
        for line in fp:
            line = line.strip().split()
            # extract header
            if line[0] == '1':
                startdate = pd.to_datetime(line[1], format='%Y%m%d')
                starttime = pd.to_datetime(line[2], format='%H%M')
                nexttime = starttime
            else:
                for item in line:
                    data = f"{startdate}-{starttime},{item}\n"
                    fout.write(data)
                    nexttime += datetime.timedelta(minutes=2)
if __name__ == '__main__':
    convert_file()
The date format is however not as i try to format it, and the desired deltatime is not added
Output:
1979-01-11 00:00:00-1900-01-01 10:07:00,3.333 1979-01-11 00:00:00-1900-01-01 10:07:00,3.333 1979-01-11 00:00:00-1900-01-01 10:07:00,3.333 1979-01-11 00:00:00-1900-01-01 10:07:00,0.556 1979-01-11 00:00:00-1900-01-01 10:07:00,0.556 1979-01-11 00:00:00-1900-01-01 10:07:00,0.556 1979-01-11 00:00:00-1900-01-01 10:07:00,0.556 1979-01-11 00:00:00-1900-01-01 10:07:00,0.556 1979-01-11 00:00:00-1900-01-01 10:07:00,0.556 1979-01-11 00:00:00-1900-01-01 10:07:00,3.333 1979-01-11 00:00:00-1900-01-01 10:07:00,0.370 1979-01-11 00:00:00-1900-01-01 10:07:00,0.370 1979-01-11 00:00:00-1900-01-01 10:07:00,0.370

Attached Files

.txt   gauga20211_19790101-20120101.txt (Size: 198.98 KB / Downloads: 90)
Reply


Messages In This Thread
RE: change item in column based on the item before[solved] - by amdi40 - Jan-11-2022, 04:50 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  removing item pastakipp 3 1,926 Oct-25-2020, 09:15 PM
Last Post: deanhystad
  Python Adding +1 to a list item cointained in a dict ElReyZero 1 2,101 Apr-30-2020, 05:12 AM
Last Post: deanhystad
  need help removing an item from a list jhenry 4 4,225 Oct-13-2017, 08:15 AM
Last Post: buran
  Determine if a list contains a specific number of an item flannel_man 3 4,956 Nov-12-2016, 04:46 PM
Last Post: micseydel

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020