Pythonメモ--特定の場所でCSVファイルを修正


PhysioNet Challenge 2019の試合に出場しているため、その中でデータはテーマの要求に応じて前処理する必要があるため、pythonのCSVライブラリで約20万件のデータを規則的に修正した.修正のルールは、1行の末尾文字が「1.0」である、前の行の末尾文字が「0.0」であるデータを見つけ、その行の12行以上のデータの末尾文字を「1.0」に変更することである.
具体的な実装手順は、1修正するすべての行を探し出し、その行の特徴(行数、文字タグ)を辞書に格納する.②辞書に対して相応の処理をする.③新規ファイルを作成し、ソースファイルの各行を遍歴し、その行の特徴が辞書にない場合は新規ファイルに完全にコピーし、その行が辞書にちょうどある場合は、その行の最後の文字を「1.0」に変更し、新規ファイルにコピーする.④最後に生成された新規ファイルは、我々が処理する必要があるデータファイルである.
コードと注釈は以下の通りで、親測定は有効です.
import csv
import numpy as np
"""
import csv and numpy.
"""
dictOrig = {}
"""
Define a dict to store the characteristics of the file need to be modified.
"""
with open('C:/Users/Ethan/PycharmProjects/readcsv/Sepsis.csv', 'r') as csvfile:
"""
Open the file need to be modified, note that the file path must be correct.
"""
    reader = csv.reader(csvfile)
    rows = [rowTemp for rowTemp in reader]
    """
    rows = [['1.0','2.0','#','!'],['1.0','2.0','#','!'],['1.0','2.0','#','!'],[...],...]
    rows is a list collection of each row in the file.
    """
    for row in rows:
        if row[-1] == '1.0' and rows[rows.index(row)-1][-1] == '0.0':
            dictOrig[rows.index(row)] = row[-2]
        """
        Travers the rows to record the characteristics of the file need to be modified in the dict.
        In this code, the feature we want to modify is that the end string of the row is '1.0' and 
        the end string of the last row is '0.0'
        """
    for temp in list(dictOrig.values()):
    """
    Make some modifications to the feature, such as the code that we want to change the end string 
    of the uo 12 rows fo the target line to '1.0'
    """
        if float(temp) >= 13.0:
        """
        If the index of target row is larger than 13, we should change the end of the previous 12
        row to '1.0'
        """
            for i in range(12):
                dictOrig[list(dictOrig.keys())[list(dictOrig.values()).index(temp)]-1-i] = str(float(temp)-i-1)
                """
                list(dictOrig.keys())[list(dictOrig.values()).index(temp)] is the key of the values temp
                """
        if float(temp) < 13.0:
        """
        If the index of target row is smaller than 13, we should change all the previous row to '1.0'
        """
            for i in np.arange(0,float(temp),1.0):
            """
            np.arange() is the range of float number
            """
                dictOrig[list(dictOrig.keys())[list(dictOrig.values()).index(temp)]-1-i] = str(float(temp)-i-1)

    with open('C:/Users/Ethan/PycharmProjects/readcsv/New.csv', 'a', newline='') as newfile:
    """
    Open a new file that we want to write to. Note that we must add the "newline=''" to avoid to generate
    the blank lines. The parameter 'a' means that open for writing, appending to the end of the file if it 
    exists.
    """
        for row in rows:
        """
        Traverse the rows again.
        """
            if rows.index(row) in dictOrig.keys():
            """
            If we find the row we want to change, change it at the time of replication.
            """
                rowNew = row
                rowNew[-1] = '1.0'
                writer = csv.writer(newfile)
                writer.writerow(rowNew)
            else:
            """
            Or we should replicate it directly.
            """
                rowNew = row
                writer = csv.writer(newfile)
                writer.writerow(rowNew)
    newfile.close()
    csvfile.close()
    """
    Close the two files.
    """