簡體   English   中英

如何遍歷 pandas dataframe 並檢查日期時間索引中的日期

[英]How to iterate over pandas dataframe and check for the day in datetimeindex

我有一個帶有這個日期時間索引的大型 dataframe:

...   Date                 A       B

190   2019-09-13 21:50:00  1       2
191   2019-09-13 21:55:00  3       2
192   2019-09-13 22:00:00  1       2
193   2019-09-13 22:05:00  3       2
194   2019-09-13 22:10:00  1       2
195   2019-09-16 06:00:00  1       2
196   2019-09-16 06:05:00  1       2
197   2019-09-16 06:10:00  4       2
198   2019-09-16 06:15:00  1       2
199   2019-09-16 06:20:00  4       2
200   2019-09-16 06:25:00  1       2

.....
Name: Date, dtype: datetime64[ns]

現在我需要計算 A 是否大於或等於 B,但只需要每天第一次。 我怎樣才能實現這個列表只被每天的第一次點擊填充?

count = []

for i in df.index:
    if A[i] >= B[i]:
       count.append('A is larger than B' + f" on {df.Date[i]}")

根據此示例,我想要的 output 將是

A is larger than B on 2019-09-13 21:55:00  
A is larger than B on 2019-09-16 06:10:00  

您可以首先使用boolean indexingSeries.ge (大於或等於, >= )過濾行,然后通過Series.dt.dateGroupBy.first獲取第一個值:

df['Date'] = pd.to_datetime(df['Date'])
m = df['A'].ge(df['B'])

df1 = df[m].groupby(df['Date'].dt.date).first()
print (df1)
                          Date  A  B
Date                                
2019-09-13 2019-09-13 21:55:00  3  2
2019-09-16 2019-09-16 06:10:00  4  2

或者按日期創建輔助列,然后使用DataFrame.drop_duplicates

df['Date'] = pd.to_datetime(df['Date'])
df['d'] = df['Date'].dt.date

m = df['A'].ge(df['B'])

df1 = df[m].drop_duplicates('d')
print (df1)
                   Date  A  B           d
191 2019-09-13 21:55:00  3  2  2019-09-13
197 2019-09-16 06:10:00  4  2  2019-09-16

for d in df1.Date:
    print ('A is larger than B' + f" on {d}")
A is larger than B on 2019-09-13 21:55:00
A is larger than B on 2019-09-16 06:10:00

暫無
暫無

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

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