【问题标题】:Retrieve data for a particular date and 7days ago value using Pandas使用 Pandas 检索特定日期和 7 天前值的数据
【发布时间】:2021-02-04 10:25:34
【问题描述】:

我想在 pandas 中同时提取提到日期的数据和 7 天前的数据。 尝试自动化 7 天前的部分,但无法使用 dt.timedelta(days=7).

结果: 我想要它:

【问题讨论】:

标签: python pandas datetime


【解决方案1】:

在您的示例中,7 天前的日期比 6 天前...一切正常,为简单起见,我创建了可复制的 DF 版本作为转置。

import datetime as dt
import pandas as pd
import numpy as np
dr = pd.date_range(dt.date(2020,6,25),dt.date(2020,7,8))
df = pd.DataFrame({
"dotdate":dr,
    "impressions":np.random.randint(200000,400000, len(dr)),
    "impressions":np.random.randint(200000,400000, len(dr)),
    "link_clicks":np.random.randint(200000*150,400000*150, len(dr)),
})

df = df.set_index("dotdate").T
mydate = dt.date(2020,7,7)
df.loc[:,[c for c in df.columns if c==mydate or c==(mydate-pd.Timedelta(days=7))]]
2020-06-30 00:00:00 2020-07-07 00:00:00
impressions 274529 247155
link_clicks 4.61249e+07 3.26222e+07

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多