【问题标题】:Change day to specific entries in pandas dataframe将日期更改为熊猫数据框中的特定条目
【发布时间】:2019-07-20 08:14:11
【问题描述】:

我在 pandas 中有一个数据框,它的索引中有一个错误:23:00:00 到 23:59:59 之间的每个条目都有一个错误的日期。我需要在这两次之间的每个条目中减去一天(即 24 小时)。

我知道我可以获得这两次之间的条目df[df.hour == 23],其中df 是我的数据框。但是,我可以只为数据框索引的那些特定条目修改日期吗?

重置会花费我更多的时间,因为我的数据帧索引不是均匀分布的,如下图所示(两个连续条目之间的间隔为 15 分钟和 30 分钟)。还要注意图中最后三个条目中的错误日期:应该是 2018-02-05 而不是 2018-02-06。

我试过这样做

df[df.index.hour == 23].index.day = df[df.index.hour == 23].index.day - 1

但我得到AttributeError: can't set attribute

样本数据:

2018-02-05 22:00:00    271.8000
2018-02-05 22:30:00    271.5600
2018-02-05 22:45:00    271.4400
2018-02-06 23:15:00    271.3750
2018-02-06 23:30:00    271.3425
2018-02-06 00:00:00    271.2700
2018-02-06 00:15:00    271.2300
2018-02-06 00:45:00    271.1500
2018-02-06 01:00:00    271.1475
2018-02-06 01:30:00    271.1425
2018-02-06 01:45:00    271.1400

预期输出:

2018-02-05 22:00:00    271.8000
2018-02-05 22:30:00    271.5600
2018-02-05 22:45:00    271.4400
2018-02-05 23:15:00    271.3750
2018-02-05 23:30:00    271.3425
2018-02-06 00:00:00    271.2700
2018-02-06 00:15:00    271.2300
2018-02-06 00:45:00    271.1500
2018-02-06 01:00:00    271.1475
2018-02-06 01:30:00    271.1425
2018-02-06 01:45:00    271.1400

【问题讨论】:

  • 请提供code-formatted 示例数据、您尝试过的内容以及预期的输出结果。
  • 我用请求的信息编辑了问题

标签: python pandas datetime dataframe


【解决方案1】:

我自己使用this answer 解决了这个问题。这是我的代码:

as_list = df.index.tolist()
new_index = []
for idx,entry in enumerate(as_list):
    if entry.hour == 23:
        if entry.day != 1:            
            new_index.append(as_list[idx].replace(day = as_list[idx].day - 1))
        else:
            new_day = calendar.monthrange(as_list[idx].year, as_list[idx].month -1)[1]
            new_index.append(as_list[idx].replace(day = new_day, month = entry.month -1))
    else:
        new_index.append(entry)
df.index = new_index

【讨论】:

    【解决方案2】:

    你可以试试TimeDeltas

    如果您的数据框有日期时间索引,您应该可以直接从中减去。

    df[df.hour == 23] - pd.Timedelta('1 days')

    如果 df.index 类型是字符串,那么你应该先改变类型,然后减去: df.index = pd.to_datetime(df.index)

    df.index - pd.Timedelta('1 days')

    【讨论】:

    • 这行不通,因为df 没有hour 属性,甚至通过df[df.index.hour == 23] - pd.Timedelta('1 days') 也行不通
    猜你喜欢
    • 1970-01-01
    • 2017-05-21
    • 2019-06-21
    • 1970-01-01
    • 2018-04-25
    • 1970-01-01
    • 2020-03-30
    • 1970-01-01
    • 2023-02-03
    相关资源
    最近更新 更多