如何在时间序列中循环?

2024-06-11 05:53:46 发布

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

我有这样一个数据帧:

                      datetime type   d13C  ...  dayofyear week         dmy
1       2018-01-05 15:22:30  air  -8.88  ...          5    1    5-1-2018
2       2018-01-05 15:23:30  air  -9.08  ...          5    1    5-1-2018
3       2018-01-05 15:24:30  air -10.08  ...          5    1    5-1-2018
4       2018-01-05 15:25:30  air  -9.51  ...          5    1    5-1-2018
5       2018-01-05 15:26:30  air  -9.61  ...          5    1    5-1-2018
                    ...  ...    ...  ...        ...  ...         ...
341543  2018-12-17 12:42:30  air  -9.99  ...        351   51  17-12-2018
341544  2018-12-17 12:43:30  air  -9.53  ...        351   51  17-12-2018
341545  2018-12-17 12:44:30  air  -9.54  ...        351   51  17-12-2018 
341546  2018-12-17 12:45:30  air  -9.93  ...        351   51  17-12-2018
341547  2018-12-17 12:46:30  air  -9.66  ...        351   51  17-12-2018

此处的完整数据:https://drive.google.com/file/d/1KmOwnpvrG2Edz1AlLyD0CKZlBpaFervM/view?usp=sharing

我在Y轴上画出d13C柱,在X轴上画出总co2的倒数,然后在数据中拟合每天的回归线。然后,根据回归线的r^2值是否为>;0.8这样:

import pandas as pd
from numpy.polynomial.polynomial import polyfit
import numpy as np
from scipy import stats

df = pd.read_csv('dataset.txt', usecols = ['datetime', 'type', 'total_co2', 'd13C', 'day','month','year','dayofyear','week','hour'], dtype = {'total_co2':
np.float64, 'd13C':np.float64, 'day':str, 'month':str, 'year':str,'week':str, 'hour': str, 'dayofyear':str}) 
    
df['dmy'] = df['day'] +'-'+ df['month'] +'-'+ df['year'] # adding a full date column to make it easir to filter through
# the rows, ie. each day
# window18 = df[((df['year']=='2018'))] # selecting just the data from the year 2018

accepted_dates_list = [] # creating an empty list to store the dates that we're interested in
for d in df['dmy'].unique(): # this will pass through each day, the .unique() ensures that it doesnt go over the same days  
    acceptable_date = {} # creating a dictionary to store the valid dates
    period = df[df.dmy==d] # defining each period from the dmy column
    p = (period['total_co2'])**-1
    q = period['d13C']
    c,m = polyfit(p,q,1) # intercept and gradient calculation of the regression line
    slope, intercept, r_value, p_value, std_err = stats.linregress(p, q) # getting some statistical properties of the regression line
    
    
    if r_value**2 >= 0.8:
        acceptable_date['period'] = d # populating the dictionary with the accpeted dates and corresponding other values
        acceptable_date['r-squared'] = r_value**2
        acceptable_date['intercept'] = intercept
        accepted_dates_list.append(acceptable_date) # sending the valid stuff in the dictionary to the list
    else:
        pass


accepted_dates18 = pd.DataFrame(accepted_dates_list) # converting the list to a df
print(accepted_dates18)

但是现在我想做同样的事情,只是在三天的时间里,我试着从一年中的一天列中选择(不确定这是否是最好的方式)。例如,我希望使用dayofyear=5、dayofyear=6、dayofyear=7的所有行拟合回归线,然后在接下来的三天内拟合,直到数据结束。缺少了一些天,但基本上我只需要在数据中每隔3天做一次

然后,我尝试获取的输出数据帧将具有三天间隔的列表,并带有r^2>;0.8,因此任何类似的内容都将显示有效的日期范围:

  Accepted dates
0  23-08-2018 - 25-08-2018
1  26-08-2018 - 28-08-2018
2  31-08-2018 - 02-09-2018
3  15-09-2018 - 17-09-2018
4  24-09-2018 - 26-09-2018

我不太确定每三天迭代一次该做什么。任何帮助都会有很大帮助,谢谢


Tags: theto数据dfdateairyearlist
2条回答

这里有一种方法。据我所知,主要目标是从当前观测值(每天多次)到3天移动平均值。首先,我创建了一个更小、更简单的数据集:

import pandas as pd
df = pd.DataFrame({'counter': [*range(100)],
                  'date': pd.date_range('2020-01-01', periods=100, freq='7H')})
df = df.set_index('date')
print(df.head())

                     counter
date                        
2020-01-01 00:00:00        0
2020-01-01 07:00:00        1
2020-01-01 14:00:00        2
2020-01-01 21:00:00        3
2020-01-02 04:00:00        4

第二,我每天重新取样:

df2 = df['counter'].resample('1D').mean()  # <  called df2
print(df2.head())

date
2020-01-01     1.5
2020-01-02     5.0
2020-01-03     8.5
2020-01-04    12.0
2020-01-05    15.5
Freq: D, Name: counter, dtype: float64

第三,我计算了3天移动窗口的平均值:

print(df2.rolling(3).mean().head())

date
2020-01-01     NaN
2020-01-02     NaN
2020-01-03     5.0
2020-01-04     8.5
2020-01-05    12.0
Freq: D, Name: counter, dtype: float64

似乎重采样().mean()和滚动().mean()在这种情况下很有用

您的代码在唯一日期列表中循环,并在每次迭代中过滤数据帧

熊猫通过df.groupby()实现了这一点。它可以用于循环和获取每个组,也可以与聚合、函数应用程序和转换相结合。你可以在user guide上阅读更多关于它的信息。此函数可以根据df中的任何列(或列集)、索引级别或任何其他与df长度相同的外部列表(我们正在对行进行分组,但请注意,它也可以对列进行分组)返回组。它甚至实现了最常见的统计聚合,如mean、stdev和corr等

现在谈谈你的问题。您不仅需要相关性,还需要等式,因此确实需要循环。为了得到三天的小组,你可以使用dayofyear

以这些数据为例

import io
fo = io.StringIO(
'''datetime,d13C
2018-01-05 15:22:30,-8.88
2018-01-05 15:23:30,-9.08
2018-01-06 15:24:30,-10.0
2018-01-06 15:25:30,-9.51
2018-01-07 15:26:30,-9.61
2018-01-07 15:27:30,-9.61
2018-01-08 15:28:30,-9.61
2018-01-08 15:29:30,-9.61
2018-01-09 15:26:30,-9.61
2018-01-09 15:27:30,-9.61
''')
df = pd.read_csv(fo)
df.datetime = pd.to_datetime(df.datetime)
fo.close()

使用分组和循环的代码

first_day = 5
days_to_group = 3
for doy, gdf in df.groupby((df.datetime.dt.dayofyear.sub(first_day) // days_to_group)
        * days_to_group + first_day):
    print(gdf, '\n')
    print(doy, '\n')

输出

             datetime   d13C
0 2018-01-05 15:22:30  -8.88
1 2018-01-05 15:23:30  -9.08
2 2018-01-06 15:24:30 -10.00
3 2018-01-06 15:25:30  -9.51
4 2018-01-07 15:26:30  -9.61
5 2018-01-07 15:27:30  -9.61

5

             datetime  d13C
6 2018-01-08 15:28:30 -9.61
7 2018-01-08 15:29:30 -9.61
8 2018-01-09 15:26:30 -9.61
9 2018-01-09 15:27:30 -9.61

8

现在,您可以将代码插入这个循环并获得所需的内容


PS

你也可以使用df.datetime.dt.floor('3d')作为石斑鱼,但我不知道如何控制第一天,所以要小心使用

相关问题 更多 >