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

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

我有一个这样的数据框:

                      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()一样有用。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-