python - 使用标准(开尔文到摄氏度)从 csv 中替换特定列中的一些值

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

在同一列中,我们有以开尔文和摄氏度为单位的温度数据。如何创建一个新列,其中我有相同类型的日期(开尔文或摄氏度)。我有很多 csv 格式的数据。 我尝试使用类似的东西:if initial_temperature > 50 write new_temperature = initial_temperature – 273.15,我认为我们的摄氏温度不能高于 50。

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

谢谢

如果您只有值列表,您可以使用列表理解来获得结果:

>>> Input_data =[37, 309.15, 38, 310.5]
>>> Output_data = [round((x - 273.15),2) if x > 50 else x for x in Input_data]
>>> Output_data
[37, 36.0, 38, 37.35]

既然你提到了列,我想你有某种数据框。对于 pandas 数据框,您可以使用 lambda 函数:

>>> import pandas as pd
>>> df = pd.DataFrame({'Input_data':[37, 309.15, 38, 310.5]})
>>> df
   Input_data
0       37.00
1      309.15
2       38.00
3      310.50
>>> df['Output_data'] = df['Input_data'].apply(lambda x: x - 273.15 if x > 50 else x)
>>> df
   Input_data  Output_data
0       37.00        37.00
1      309.15        36.00
2       38.00        38.00
3      310.50        37.35

对于 numpy 数组,它是这样的:

>>> import numpy as np
>>> x = np.array([37, 309.15, 38, 310.5])
>>> x
array([ 37.  , 309.15,  38.  , 310.5 ])
>>>
>>> y = np.where(x > 50, x - 273.15, x)
>>> y
array([37.  , 36.  , 38.  , 37.35])

如果您的数据位于 csv 文件中的一列中,如下所示:

input_data.csv

37
309.15
38
310.5

然后您可以从文件中逐行读取此数据并将其保存到具有附加列的另一个文件中。

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_data.csv

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