迭代日期以计算差异

2024-06-13 10:06:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在与以下df合作:

              date/time wind (°) wind (kt) temp (C°) humidity(%) currents (°) currents (kt) stemp (C°) stemp_diff
0   2017-04-27 11:21:54    180.0      14.0      27.0      5000.0        200.0           0.4       25.4        2.6
1   2017-05-04 20:31:12    150.0      15.0      22.0      5000.0         30.0           0.2       26.5       -1.2
2   2017-05-08 05:00:52    110.0       6.0      25.0      5000.0         30.0           0.2       27.0       -1.7
3   2017-05-09 05:00:55    160.0      13.0      23.0      5000.0         30.0           0.6       27.0       -2.0
4   2017-05-10 16:39:16    160.0      20.0      22.0      5000.0         30.0           0.6       26.5       -1.8
5                   ...      ...       ...       ...         ...          ...           ...        ...        ...
6   2020-10-25 00:00:00   5000.0    5000.0      21.0        81.0       5000.0        5000.0       23.0       -2.0
7   2020-10-26 00:00:00   5000.0    5000.0      21.0        77.0       5000.0        5000.0       23.0       -2.0
8   2020-10-27 00:00:00   5000.0    5000.0      21.0        80.0       5000.0        5000.0       23.0       -2.0
9   2020-10-31 00:00:00   5000.0    5000.0      22.0        79.0       5000.0        5000.0       23.0       -2.0
10  2020-11-01 00:00:00   5000.0    5000.0      19.0        82.0       5000.0        5000.0       23.0       -2.0

我想找到一种方法来迭代我的date/time列中的年份和月份(即2017年4月,一直到2020年11月),并针对每个独特的时间段,计算stemp列的平均差异作为起点(因此2017年4月、2017年5月等的平均值,甚至仅使用月份)

我正在尝试使用这类代码,但不太确定如何将其转换为有效的代码:

for '%MM' in australia_in['date/time']:
    australia_in['stemp_diff'] = australia_in['stemp (C°)'] - australia_out['stemp (C°)'] 
    australia_in

有什么想法吗


Tags: 方法代码indfdatetimedifftemp
1条回答
网友
1楼 · 发布于 2024-06-13 10:06:53

让我们首先确保date/time列是datetime类型,并将其设置为index:

df['date/time'] = pd.to_datetime(df['date/time'])
df = df.set_index('date/time')

那么你有几个选择

使用^{}

>>> df.groupby(pd.Grouper(freq='M'))['stemp (C°)'].mean().dropna()
date/time
2017-04-30    25.40
2017-05-31    26.75
2020-10-31    23.00
2020-11-30    23.00
Name: stemp (C°), dtype: float64

使用年份和月份:

>>> df.groupby([df.index.year, df.index.month])['stemp (C°)'].mean()
date/time  date/time
2017       4            25.40
           5            26.75
2020       10           23.00
           11           23.00
Name: stemp (C°), dtype: float64

如果不希望将日期/时间作为索引,可以改用列:

df.groupby([df['date/time'].dt.year, df['date/time'].dt.month])['stemp (C°)'].mean()

最后,为年度和月份取个好名字:

(df.groupby([df['date/time'].dt.year.rename('year'),
             df['date/time'].dt.month.rename('month')])
   ['stemp (C°)'].mean()
)


output:
year  month
2017  4        25.40
      5        26.75
2020  10       23.00
      11       23.00
Name: stemp (C°), dtype: float64

stemp_diff应用相同的计算:

year  month
2017  4        2.600
      5       -1.675
2020  10      -2.000
      11      -2.000
Name: stemp_diff, dtype: float64

相关问题 更多 >