在给定值的50天内用日期值绘制行

2024-10-03 23:23:03 发布

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

我有一个DataFrame(dataframeA)和一列日期,格式如下

日期
19960826年
19960826年
19970303年
19970320年
19970905年

以及一列值

100
35
11
37
... 你知道吗

以及一列组
团购
组L
组m
... 你知道吗

给定另一个数据帧dataframeB,它有两列:格式为yyyymmdd的日期和组。对于dataframeB中的每一行,如何绘制每个组的日期前后60天内的值。你知道吗

例如,如果dataframeB第一行是
20050101集团

图(在Y轴上)dataframeA中的值,其中日期在2005年1月1日之前或之后的50天内,组为groupM。你知道吗


Tags: 数据dataframe格式绘制集团yyyymmdddataframebdataframea
1条回答
网友
1楼 · 发布于 2024-10-03 23:23:03

以下是一些示例数据:

import pandas as pd
import numpy as np
import string

start_date = '20050101'
drange = pd.date_range(start_date, periods=100, freq='D')
possible_groups = ['A','B','C','D','E','F']
chosen = np.random.choice(possible_groups, len(drange), replace=True)
groups = pd.Series(chosen).apply(lambda x: 'group'+x)
values = np.random.randint(1, 100, len(drange))

dfA = pd.DataFrame({'date':drange, 'grp':groups, 'value':values})
dfB = pd.DataFrame({'date':drange, 'grp':groups})

注意:如果需要使datetime对象在视觉上看起来像YYYYMMDD,可以使用strftime()并根据需要切换回datetime,例如:

drange = pd.date_range(start_date, periods=100, freq='D').strftime('%Y%m%d')

现在,假设出于某种原因需要将这些数据帧分开(即不允许merge()),那么下面的方法应该可以工作。你知道吗

def plot_range(data, within):
    (
     dfA.set_index('date')
        .loc[dfA.grp.values == data.grp]
        .loc[data.date-pd.Timedelta(days=within):
             data.date+pd.Timedelta(days=within)]
        .plot(title=data.grp)
    )

within = 50 # set within to the desired range in days around a date
dfB.apply(plot_range, axis='columns', args=(within,))

以下是几天的子集的输出示例:

subset = 3
within = 10
dfB.sample(subset).apply(plot_range, axis='columns', args=(within,))  

time series plot

相关问题 更多 >