简体   繁体   中英

Filtering a pandas data frame using a column of months to keep the most recent n months

I have a pandas datframe with month as one column. I have given a small sample below:

   df 

 ColA     ColB    ColC   MonthCol

   XY      AA      12      Apr
   XY      BG      15      Apr
   XY      BG      16      Mar
   XY      AD      13      Feb
   XA      AA      15.5    Apr
   XA      AA      16.2    Mar
   XA      AA      13.1    Jan
   XA      AA      13      Feb
   TX      AC      11      Mar
   TX      AX      12      Feb

Now what I want is to filter the datframe and keep rows only for the two recent months based on the current month.

I was trying a apply function of the sort as follows ( keeping 1 & 0 and then removing 0's) but it is not working:

      def filtermon(mCol):

          currmon = datetime.datetime.now().strftime("%m")

          if currmon == mCol or currmon - mCol = 1
               val =1 
          else:
                val = 0 
          return val  

After that I was creating a new column from the datframe as :

       df[filtCol] = df[MonthCol].apply(filtermon)

We're now in the month of April, so we have,

mth = pd.to_datetime('today').month
mth
# 4

df[(pd.to_datetime(df['MonthCol'], format='%b').dt.month - mth).isin([0, -1])]

  ColA ColB  ColC MonthCol
0   XY   AA  12.0      Apr
1   XY   BG  15.0      Apr
2   XY   BG  16.0      Mar
4   XA   AA  15.5      Apr
5   XA   AA  16.2      Mar
8   TX   AC  11.0      Mar

Different layout by using date_range + isin

s=pd.date_range(end='2019-04-02',periods=2,freq='MS').strftime('%b')
df[df.MonthCol.isin(s)]
  ColA ColB  ColC MonthCol
0   XY   AA  12.0      Apr
1   XY   BG  15.0      Apr
2   XY   BG  16.0      Mar
4   XA   AA  15.5      Apr
5   XA   AA  16.2      Mar
8   TX   AC  11.0      Mar

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM