gpt4 book ai didi

python - 在 pandas 中计算数据集的每月天值

转载 作者:行者123 更新时间:2023-12-01 01:08:51 25 4
gpt4 key购买 nike

我是 Pandas 新手。我有一个很大的数据集,其中包含每日的温度值。我需要按月计算温度,即

enter image description here

这是我的数据集 csv 结构: enter image description here

我需要转换为以下 csv 结构: enter image description here

我正在考虑以下方法:

for(year=2012;year<=2018;year++)
for(month=1;month<=12;month++)
for(day=1;day<=31;day++)
summax+=Temp_max[day]
summin+=Temp_min[day]
summax/=day
summin/=day
print(summax,summin)

但我不知道如何在 pandas/python 中执行此操作,如何在循环中获取列值,也不知道如何处理二月天(如 28 天、30 天、31 天)并带来预期的输出或类似的输出输出。任何帮助,将不胜感激。谢谢!!

最佳答案

在 pandas 中使用 read_csv 读取 csv 文件

适合您的平均使用情况groupby

import pandas as pd

data = {'year': [*np.repeat(2012, 9), 2018],
'month': [*np.repeat(1, 4), *np.repeat(2, 3), *np.repeat(3, 2), 12],
'day': [1, 2, 3, 31, 1, 2, 28, 1, 2, 31],
'Temp max': [28, 26, 27, 26, 27, 26, 26, 26, 25, 26],
'Temp min': [19, 18, 17, 19, 18, 18, 18, 18, 18, 28]}

df = pd.DataFrame(data)
# df = pd.read_csv('file.csv')

df2 = df.groupby(['year', 'month'])['Temp max', 'Temp min'].mean()
print(df2)

输出:

             Temp max  Temp min
year month
2012 1 26.750000 18.25
2 26.333333 18.00
3 25.500000 18.00
2018 12 26.000000 28.00

如果你想全年使用:

df2 = df.groupby(['year', 'month'])['Temp max', 'Temp min'].mean().reset_index()

year month Temp max Temp min
0 2012 1 26.750000 18.25
1 2012 2 26.333333 18.00
2 2012 3 25.500000 18.00
3 2018 12 26.000000 28.00

关于python - 在 pandas 中计算数据集的每月天值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55061375/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com