[英]Check that any of three columns is within a column date range
我有一個包含三個datetime列的DataFrame:
tp.loc[:, ['Arrival1', 'Arrival2', 'Departure']].head()
Arrival1 Arrival2 Departure
0 2018-11-26 05:45:00 2018-11-26 12:00:00 2018-1-26 08:00:00
1 2018-11-26 22:00:00 2018-11-27 00:00:00 2018-11-26 23:00:00
2 2018-11-26 05:45:00 2018-11-26 08:15:00 2018-11-26 06:45:00
3 2018-11-26 07:30:00 2018-11-26 10:15:00 2018-11-26 08:30:00
4 2018-12-02 07:30:00 2018-12-02 21:30:00 2018-12-02 08:00:00
我只想獲取其到達1,到達2或出發(三個中的任何一個)在以下列范圍內(任何行)的tp行:
db.loc[db['country'] == 'AT']
country banStartDate banEndDate
102 AT 2018-12-01 14:00:00 2018-12-01 22:59:00
161 AT 2018-12-01 23:00:00 2018-12-02 21:00:00
51 AT 2018-12-07 23:00:00 2018-12-08 22:59:00
在此示例中,由於Arrival2在db的日期范圍內,我只希望從tp檢索第4行。
有一個簡單的方法嗎?
在使用pd.read_csv()
讀取數據幀之后,可以將pd.concat()
與布爾掩碼和列表理解一起使用,然后是drop_duplicates()
:
from io import StringIO
import pandas as pd
df1 = StringIO('''
Arrival1 Arrival2 Departure
0 2018-11-26 05:45:00 2018-11-26 12:00:00 2018-1-26 08:00:00
1 2018-11-26 22:00:00 2018-11-27 00:00:00 2018-11-26 23:00:00
2 2018-11-26 05:45:00 2018-11-26 08:15:00 2018-11-26 06:45:00
3 2018-11-26 07:30:00 2018-11-26 10:15:00 2018-11-26 08:30:00
4 2018-12-02 07:30:00 2018-12-02 21:30:00 2018-12-02 08:00:00
''')
df2 = StringIO('''
country banStartDate banEndDate
102 AT 2018-12-01 14:00:00 2018-12-01 22:59:00
161 AT 2018-12-01 23:00:00 2018-12-02 21:00:00
51 AT 2018-12-07 23:00:00 2018-12-08 22:59:00
''')
tp = pd.read_csv(df1, sep=r'\s{2,}', engine='python', parse_dates=[0,1,2])
db = pd.read_csv(df2, sep=r'\s{2,}', engine='python', parse_dates=[1,2]).reset_index()
pd.concat([tp.loc[((tp>db.loc[i,'banStartDate']) & (tp<db.loc[i,'banEndDate'])).any(axis=1)] for i in range(db.shape[0])]).drop_duplicates()
返回:
Arrival1 Arrival2 Departure
4 2018-12-02 07:30:00 2018-12-02 21:30:00 2018-12-02 08:00:00
您可以將pandas.DataFrame.any與axis ='row'(或1)一起使用,以查找日期在開始和結束之間的位置。 無論數據庫中有多少“國家”列,您都需要其中3個或一個for循環。
另外,我相信(我可能錯了),您將需要將這些字符串轉換為python datetime變量。 該代碼看起來與此類似;
tp[(datetime.strptime(Start_Date, '%Y-%d-%m %H:%M:%S')> tp >datetime.strptime(End_Date, '%Y-%d-%m %H:%M:%S')).any(axis=1)]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.