Home > Net >  Pandas Drop rows for current Year-month
Pandas Drop rows for current Year-month

Time:11-19

My dataframe has multiple years and months in "yyyy-mm-dd" format. I would like to dynamically drop all current Year-month rows from the df

enter image description here

CodePudding user response:

you could use a simple strftime method where the %Y%m is not equal to the year month of the current date.

df1 = df.loc[
 df['Date'].dt.strftime('%Y%m') != pd.Timestamp('today').strftime('%Y%m')]

Example

d = pd.date_range('01 oct 2021', '01 dec 2021',freq='d')      
df = pd.DataFrame(d,columns=['Date'])    


print(df)
         Date
0  2021-10-01
1  2021-10-02
2  2021-10-03
3  2021-10-04
4  2021-10-05
..        ...
57 2021-11-27
58 2021-11-28
59 2021-11-29
60 2021-11-30
61 2021-12-01

print(df1)

         Date
0  2021-10-01
1  2021-10-02
2  2021-10-03
3  2021-10-04
4  2021-10-05
5  2021-10-06
6  2021-10-07
7  2021-10-08
8  2021-10-09
9  2021-10-10
10 2021-10-11
11 2021-10-12
12 2021-10-13
13 2021-10-14
14 2021-10-15
15 2021-10-16
16 2021-10-17
17 2021-10-18
18 2021-10-19
19 2021-10-20
20 2021-10-21
21 2021-10-22
22 2021-10-23
23 2021-10-24
24 2021-10-25
25 2021-10-26
26 2021-10-27
27 2021-10-28
28 2021-10-29
29 2021-10-30
30 2021-10-31
61 2021-12-01
  • Related