簡體   English   中英

如何使用涉及日期的邏輯表達式對熊貓時間序列進行切片

[英]How to slice a Pandas Time Series using a logical expression involving dates

我想了解在Pandas中按時間序列進行切片的方法,並且我正在研究是否可以合並涉及日期的邏輯語句(合並和,或非操作數)條件。

因此,這是一個可重現的示例:

HAO_10
Date         Price
2018-01-02  30.240000
2018-01-03  30.629999
2018-01-04  30.860001
2018-01-05  31.010000
2018-01-08  31.389999
2018-01-09  31.309999
2018-01-10  31.400000
2018-01-11  31.580000
2018-01-12  31.680000
2018-01-16  31.200001

HAO_10.iloc[((HAO_10.index < datetime.strptime('2018-01-04', '%Y-%m-%d')) | 

             ((HAO_10.index > datetime.strptime('2018-01-08', '%Y-%m-%d')) & 
        (HAO_10.index  != datetime.strptime('2018-01-12', '%Y-%m-%d')))), ]

這是嘗試切出與2018年1月4日之前和2018年1月1日之后的日期相對應的值,而不是與2018年1月12日的日期相對應的值。

有用。

有沒有更優雅的方法可以實現相同目的?

首先使用pd.to_datetime轉換為datetime。 然后,您可以在loc語句中使用日期字符串:

df['Date'] = pd.to_datetime(df['Date'])

# This says: find where date is not between your range and not equal to 01-12
df.loc[(~df['Date'].between('2018-01-04','2018-01-08')) & (df['Date'] != '2018-01-12')]

        Date      Price
0 2018-01-02  30.240000
1 2018-01-03  30.629999
5 2018-01-09  31.309999
6 2018-01-10  31.400000
7 2018-01-11  31.580000
9 2018-01-16  31.200001

首先使用date_rangeunion創建刪除值的DatetimeIndex ,然后僅選擇與原始索引的difference

idx = pd.date_range('2018-01-04','2018-01-08').union(['2018-01-12'])
df = HAO_10.loc[HAO_10.index.difference(idx)]
#another similar solutions
#df = HAO_10.drop(idx, errors='ignore')
#df = HAO_10[~HAO_10.index.isin(idx)]

如果只想使用date s並且index也包含time s floor ,那么您是您的朋友:

df = HAO_10.loc[HAO_10.index.floor('d').difference(idx)]
#another similar solutions
#df = HAO_10[~HAO_10.index.floor('d').isin(idx)]

print (df)
                Price
2018-01-02  30.240000
2018-01-03  30.629999
2018-01-09  31.309999
2018-01-10  31.400000
2018-01-11  31.580000
2018-01-16  31.200001

您的解決方案應簡化:

df = HAO_10[((HAO_10.index < '2018-01-04') | ((HAO_10.index > '2018-01-08') & 
                  (HAO_10.index  != '2018-01-12')))]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM