如何遍历大熊猫分组的时间序列?

问题描述

我有一个这样的数据框:

                      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上绘制total_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

我不太确定每三天要重复做些什么。任何帮助都将大有帮助,谢谢!

解决方法

您的代码遍历唯一的日期列表,并在每次迭代时过滤数据框。

Pandas通过df.groupby()实现了这一目标。它可以用于循环并获取每个组,也可以与聚合,函数应用程序和转换结合使用。您可以在user guide上阅读有关它的更多信息。此函数可以根据df中的任何列(或一组列),索引级别或任何其他与df长度相同的外来列表(如对行进行分组,但请注意,它也可以对列进行分组)返回组)。它甚至还具有针对最常见的统计聚合(例如均值,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')用作石斑鱼,但是我不知道如何控制第一天,因此请谨慎使用。

,

这是一种方法。据我了解,主要目标是从当前观察值(每天多次)达到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,dtype: float64

在这种情况下,像resample()。mean()和rolling()。mean()一样有用。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...