1.题目:根据csv文件,按月份计算每个月的温度最值和均值
csv内容如图所示:第一列是月份,第二列是温度
2.技巧点:布尔型数组 作为索引删选数据
代码如下:
import numpy as np
import matplotlib.pyplot as plt
file = "./temp.csv"
month_list = ["1","2","3"]
# 构造月份布尔型数组 做索引筛选
def collect_process_data():
data_array = np.loadtxt(file,delimiter=',',dtype="str",skiprows=1)
for month in month_list:
month_array = month == data_array[:, 0]
# print(month_array)
#筛数据
month_temp_array = data_array[month_array][:,1]
# 去除'C'
clean_array = np.core.defchararray.replace(month_temp_array, "C", "")
# print(clean_array)
# 将str转为float
float_array = clean_array.astype(float)
#取最值
max_temp = np.max(float_array)
min_temp = np.min(float_array)
mean_temp = np.mean(float_array)
print('第{}月份气温最低为:{:.2f}'.format(month, min_temp))
print('第{}月份气温最高为:{:.2f}'.format(month, max_temp))
print('第{}月份气温平均为:{:.2f}'.format(month, mean_temp))
print("===================================================================")
collect_process_data()
结果如下: