【问题标题】:How to resampling a data series with date time indexing in pandas如何在熊猫中使用日期时间索引重新采样数据系列
【发布时间】:2013-09-19 20:56:29
【问题描述】:

在 pandas 中使用日期时间索引重新采样数据系列

我是 python 新手,我正在研究 pandas。我有一个 GW2test.csv 文件,其中包含日期、时间和其他列,每 30 分钟收集一次数据。我需要对每日平均值的数据进行重新采样。 CVS 看起来像:

Date        time     P    P3W   P3W1      P2W
04/18/12    15:00   0   1.334           1.006
04/18/12    15:30   0   1.336           1.003
04/18/12    16:00   0   1.323           0.985
04/18/12    16:30   0   1.316           0.977
04/18/12    17:00   0   1.312  1.231    0.97

P 是降水,并不总是为零,P3W 有一些非测量值。 我所做的是:

`

import pandas as pd

import numpy as np

import matplotlib.pyplot as plt

import pylab as pl

df = pd.read_csv('GW2test.csv', parse_dates=[['Date','time']])

f = pd.DataFrame(df, columns=[ 'Date_time','P','P3E','P1W1', 'P1W', 'P2W'])

f.describe()

df1 = df.set_index('Date_time')

Daily= df1.resample('D', how=np**.mean)

Sel = Daily.ix[0:,['P']]

Sel.plot()

Sel = Daily.ix[0:,['P3W1']]

Sel.plot()

`

到目前为止一切顺利,我的绘图显示 X 中的每日频率,但 Y 中的值是错误的。降水量应该高达 140,它只上升到 3.5(作为 30 分钟值),我的 P3W 值是正确的,但显示出一条不连续的线,尽管我在整个期间都有测量值。他们看起来像这样

请帮忙!

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    为什么不将Datetime 保留为单独的列,然后在Date 上执行groupby 并使用np.mean 聚合每个组?这将产生一个仅由包含平均值的Date 索引的结果。同样的方法可用于按time 分组并取各个日期的平均值,因此您可以轻松查看所有15:00 观察值的平均值。

    df.groupby("Date").agg(np.mean) 
    

    time 列的平均值可以忽略,也可以省略。

    【讨论】:

    • 感谢您的回答,非常有帮助
    • 如果问题能够满足您的需求,请随时投票或接受答案。
    猜你喜欢
    • 1970-01-01
    • 2014-04-06
    • 1970-01-01
    • 2016-10-16
    • 2020-06-08
    • 1970-01-01
    • 2021-03-11
    • 1970-01-01
    相关资源
    最近更新 更多