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

问题描述 投票:0回答:1

在同一列中,我们有开尔文和摄氏的温度数据。我怎样才能建立一个新的列,其中我有相同类型的日期(开尔文或摄氏度).我有很多数据在csv格式.我试图使用这样的东西:if initial_temperature > 50写new_temperature。我有很多数据在csv格式.我试图使用类似的东西:如果初始_temperature > 50写new_temperature = initial_temperature - 273.15,我想,我们不能有一个温度在摄氏度高于50。

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

谢谢你的建议

python csv replace conditional-statements criteria
1个回答
0
投票

如果你有你的数据在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

0
投票

如果你只有值的列表,你可以使用列表理解来获得结果。

>>> 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])
© www.soinside.com 2019 - 2024. All rights reserved.