Search code examples
pythoncsvreplaceconditional-statementscriteria

python - replace some values in a specific column from csv using a criteria (Kelvin to Celsius)


In the same column we have temperature data in Kelvin and Celsius. How can I make a new column in which I have the same type of date (Kelvin or Celsius). I have a lot of data in csv format. I tried to use something like: if initial_temperature > 50 write new_temperature = initial_temperature – 273.15, where I supposed that we cannot have a temperature in Celsius higher than 50.

Input_data =[37, 309.15, 38, 310.5]
Output_data = [37, 36, 38, 37.35] 

Thank you


Solution

  • If you have your data in csv file in one column like this:

    input_data.csv

    37
    309.15
    38
    310.5
    

    Then you can just read this data row by row from file and save it to another file with additional column.

    import csv
    
    with open('input_data.csv') as file:
        reader = csv.reader(file)
        output_file = open('output_data.csv', 'w')
        writer = csv.writer(output_file)
        for row in reader:
            row_values = []
            if float(row[0]) > 50:
                row_values.append(float(row[0]))  # Column A
                row_values.append(round(float(row[0]) - 273.15, 2))  # Column B
                writer.writerow(row_values)
            else:
                row_values.append(float(row[0]))  # Column A
                row_values.append(float(row[0]))  # Column B
                writer.writerow(row_values)
        output_file.close()
    

    Output in another file:

    output_data.csv

    37.0,37.0
    309.15,36.0
    38.0,38.0
    310.5,37.35