【问题标题】:Multiple time range selection in Pandas PythonPandas Python中的多个时间范围选择
【发布时间】:2023-03-11 18:25:01
【问题描述】:

我有 CSV 格式的时间序列数据。我想在脚本的单次运行中计算不同选定时间段的平均值,例如01-05-2017: 30-04-2018, 01-05-2018: 30-04-2019 等等。以下是样本数据

我有一个脚本,但它只需要一个给定的时间段。但我想给出上面提到的多个时间段。

from datetime import datetime  
import pandas as pd
df = pd.read_csv(r'D:\Data\RT_2015_2020.csv', index_col=[0],parse_dates=[0])

z = df['2016-05-01' : '2017-04-30']
# Want to make like this way 
#z = df[['2016-05-01' : '2017-04-30'], ['2017-05-01' : '2018-04-30']] 
# It will calculate the mean for the selected time period
z.mean() 

【问题讨论】:

标签: python pandas time-series


【解决方案1】:

如果使用日期作为索引,则可以将条件包含在所需范围内的数据提取出来。

import pandas as pd
import numpy as np
import io

data = '''
Date Mean
18-05-2016 0.31
07-06-2016 0.32
17-07-2016 0.50
15-09-2016 0.62
25-10-2016 0.63
04-11-2016 0.56
24-11-2016 0.56
14-12-2016 0.22
13-01-2017 0.22
23-01-2017 0.23
12-02-2017 0.21
22-02-2017 0.21 
'''

df = pd.read_csv(io.StringIO(data), delim_whitespace=True)

df['Date'] = pd.to_datetime(df['Date'])
df.set_index('Date', inplace=True)

df['2016'].head()
    Mean
Date    
2016-05-18  0.31
2016-07-06  0.32
2016-07-17  0.50
2016-09-15  0.62
2016-10-25  0.63

df.loc['2016-05-01':'2017-01-30']
    Mean
Date    
2016-05-18  0.31
2016-07-06  0.32
2016-07-17  0.50
2016-09-15  0.62
2016-10-25  0.63
2016-11-24  0.56
2016-12-14  0.22
2017-01-13  0.22
2017-01-23  0.23

df.loc['2016-05-01':'2017-01-30'].mean()
Mean    0.401111
dtype: float64

【讨论】:

    猜你喜欢
    • 2015-09-15
    • 1970-01-01
    • 2017-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多