【问题标题】:Deleting dataframe rows based on condition in datetime index根据日期时间索引中的条件删除数据框行
【发布时间】:2018-11-11 23:18:57
【问题描述】:

我有一个大小为 (43817, 6) 的大型数据框。我通过以下代码创建了一个包含过去两个月的较小数据框:

test_df = df1.last('3M')

之所以选择“3M”,是因为我在第三个月的第一天运行代码。 df 中的索引是 datetimeindex。

下面的示例数据:

                   Scheduled_Start_Date    CRQ Change Class 
Scheduled_Start_Date                                                      
2018-05-25 13:00:00   2018-05-25 13:00:00  CRQ000000114908     Standard   
2018-05-25 15:00:00   2018-05-25 15:00:00  CRQ000000115436     Standard   
2018-05-25 15:00:00   2018-05-25 15:00:00  CRQ000000115429     Standard   
2018-05-25 16:00:00   2018-05-25 16:00:00  CRQ000000115491     Standard   
2018-05-25 18:00:00   2018-05-25 18:00:00  CRQ000000115572     Standard   
2018-05-26 17:00:00   2018-05-26 17:00:00  CRQ000000115495    Emergency   
2018-05-29 11:00:00   2018-05-29 11:00:00  CRQ000000115240     Standard   
2018-05-29 21:00:00   2018-05-29 21:00:00  CRQ000000115507    Emergency   
2018-05-31 15:00:00   2018-05-31 15:00:00  CRQ000000115516     Standard   
2018-06-01 05:00:00   2018-06-01 05:00:00  CRQ000000115466     Standard   
2018-06-01 09:00:00   2018-06-01 09:00:00  CRQ000000115085       Normal

我想要做的是获得过去两个月所有日子的完整视图,无论我何时运行代码,我能想到的唯一方法是删除当前不需要的月份中的所有行两个月期间之外的日期时间索引。例如,如果我在 6 月 1 日运行小型数据帧的代码,它将在 6 月 1 日返回我需要删除的实例。

有没有更简单的方法可以从日期时间索引中获取最后两个(完整)月,无论您何时运行代码?

【问题讨论】:

  • 只是为了理解清楚,如果你在 6 月 1 日运行代码,你想要 5 月和 4 月而不是 6 月的条目?
  • 是的。我试图只对前两个月的数据进行切片。

标签: python-3.x pandas date datetime dataframe


【解决方案1】:

您可以从df 中删除当前月份的数据,然后查找最近 2 个月的数据。在查找过去 2 个月并删除当前月份然后再查找一个月可能会很混乱。:

import datetime as dt
current_month = dt.datetime.today().month
df.drop(df.loc[df.index.month==current_month].index).last('2M')

考虑下面的玩具示例:

i = pd.date_range(start='2018-04-01', freq='20D', end='2018-06-30')
df = pd.DataFrame({'A': [1, 10, 3, 4, 5]}, index=i)
print(df)

输出:

            A
2018-04-01  1
2018-04-21  10
2018-05-11  3
2018-05-31  4
2018-06-20  5

然后在查找最近的n 个月的数据之前删除当前月份的数据。

import datetime as dt
current_month = dt.datetime.today().month
df.drop(df.loc[df.index.month==current_month].index).last('2M')

输出:

            A
2018-04-01  1
2018-04-21  10
2018-05-11  3
2018-05-31  4

【讨论】:

  • @AlexCurtis 很高兴为您提供帮助。编码愉快。
猜你喜欢
  • 1970-01-01
  • 2021-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-14
  • 2016-06-01
  • 1970-01-01
  • 2018-06-04
相关资源
最近更新 更多