logo
down
shadow

Filter data by last 3 months and by ID


Filter data by last 3 months and by ID

By : Steven Kelley
Date : October 25 2020, 07:10 PM
seems to work fine Use to_datetime first, sorting by both columns by DataFrame.sort_values, convert Month column back to original format by Series.dt.strftime and call GroupBy.tail:
code :
df['Month'] = pd.to_datetime(df['Month'], format='%b-%y')
df1 = (df.sort_values(['ID','Month'])
         .assign(Month=df['Month'].dt.strftime('%b-%y'))
         .groupby('ID')
         .tail(3))
print (df1)
    ID   Month
1    1  Dec-17
0    1  Jan-18
2    1  Feb-18
6    2  Jan-18
8    2  Feb-18
11   2  Mar-18
df['Month'] = pd.to_datetime(df['Month'], format='%b-%y').dt.to_period('m')
df1 = (df.sort_values(['ID','Month'])
         .groupby('ID')
         .tail(3))
print (df1)
    ID    Month
1    1  2017-12
0    1  2018-01
2    1  2018-02
6    2  2018-01
8    2  2018-02
11   2  2018-03


Share : facebook icon twitter icon
How to filter my results so it shows the last four months of data - sql

How to filter my results so it shows the last four months of data - sql


By : user2259153
Date : March 29 2020, 07:55 AM
this will help If you need to get whole months then you will need to get the first of the month 4 months ago.
You can get the first of the current month using:
code :
SELECT DATEADD(MONTH, DATEDIFF(MONTH, '19000101', GETDATE()), '19000101');
SELECT DATEADD(MONTH, DATEDIFF(MONTH, '19000101', GETDATE()) - 4, '19000101');
WHERE   EndDate >= DATEADD(MONTH, DATEDIFF(MONTH, '19000101', GETDATE()) - 4, '19000101')
WHERE   EndDate >= DATEADD(MONTH, DATEDIFF(MONTH, '19000101', GETDATE()) - @Number, '19000101')
How to do core data fetch predicate for NSDate in swift? i want to filter it by months

How to do core data fetch predicate for NSDate in swift? i want to filter it by months


By : Sherlock Holmes
Date : March 29 2020, 07:55 AM
Hope this helps You can do something like
Get the first date and last date of a month and then use it like
code :
let startDate = NSDate().startOfMonth()
let endDate = NSDate().endOfMonth()
request.predicate = NSPredicate(format: "dateField >= %@ AND dateField <= %@", startDate!, endDate!)
extension NSDate {

    func startOfMonth() -> NSDate? {

        let calendar = NSCalendar.currentCalendar()
        let currentDateComponents = calendar.components([.Year, .Month], fromDate: self)
        let startOfMonth = calendar.dateFromComponents(currentDateComponents)

        return startOfMonth
    }

    func dateByAddingMonths(monthsToAdd: Int) -> NSDate? {

        let calendar = NSCalendar.currentCalendar()
        let months = NSDateComponents()
        months.month = monthsToAdd

        return calendar.dateByAddingComponents(months, toDate: self, options: [])
    }

    func endOfMonth() -> NSDate? {

        let calendar = NSCalendar.currentCalendar()
        if let plusOneMonthDate = dateByAddingMonths(1) {
            let plusOneMonthDateComponents = calendar.components([.Year, .Month], fromDate: plusOneMonthDate)

            let endOfMonth = calendar.dateFromComponents(plusOneMonthDateComponents)?.dateByAddingTimeInterval(-1)

            return endOfMonth
        }

        return nil
    }
}
Filter CSV by month and create new csv with that months data

Filter CSV by month and create new csv with that months data


By : Allan Arsenal
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , Every time there is a new month in the "call resolve time" column I'd like to have a new csv file created with that month and year. And for all lines containing that month and year to be filtered into that new csv. , Try the following,
code :
# say, reader is the reader object
# do next(reader) to skip the headings
from itertools import groupby
def by_month(row):
    date = row[0] 
    month = int(date.split("/", 1)[0])
    return month

m_g = groupby(reader, by_month)

for month, group in m_g:
    group = list(group)
    # use a month to month_name map
    with open('{}.csv'.format(month), 'w') as fw:
        w = csv.writer(fw)
        w.writerows(group)
How to filter HadISST raster data in a range of months in R?

How to filter HadISST raster data in a range of months in R?


By : karen996
Date : March 29 2020, 07:55 AM
it should still fix some issue Ok, I've got a little something. Maybe you an use it to modify your function:
code :
## Generate your layer names (used for indexing later)

nms <- expand.grid(paste0('X',1969:2011),c("01","02","03","04","05","06","07","08","09","10","11","12"),'16')

nms <- apply(nms,1,function(x) paste0(x,collapse = '.'))

nms <- sort(nms)

## Generating fake raster brick

r <- raster()
r[] <- runif(ncell(r))

rst <- lapply(1:length(nms),function(x) r)

rst <- do.call(brick,rst)

names(rst) <- nms
for (ix in 1970:2011){


  sel <- rst[[c(grep(paste0(ix-1,'.12'),nms),sapply(paste0(0,1:4),function(x) grep(paste0(ix,'.',x),nms)))]]


  break ## in case you don't want to go through all iterations

  }
> sel
class       : RasterStack 
dimensions  : 180, 360, 64800, 5  (nrow, ncol, ncell, nlayers)
resolution  : 1, 1  (x, y)
extent      : -180, 180, -90, 90  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0 
names       :  X1969.12.16,  X1970.01.16,  X1970.02.16,  X1970.03.16,  X1970.04.16 
min values  : 5.988637e-06, 5.988637e-06, 5.988637e-06, 5.988637e-06, 5.988637e-06 
max values  :    0.9999771,    0.9999771,    0.9999771,    0.9999771,    0.9999771 
hadSSTmean <- function(x, years, first.range = 11:12, second.range = 1:4){

  nms <- names(x)

  mts <- c("01","02","03","04","05","06","07","08","09","10","11","12")

  xMeans <- vector(length = length(years)-1,mode='list')

  for (ix in 2:length(years){

    xMeans[[ix-1]] <- mean(x[[c(sapply(first.range,function(x) grep(paste0(years[ix-1],'.',mts[x]),nms)),sapply(1:4,function(x) grep(paste0(years[ix],'.',mts[x]),nms)))]])

  }

  return(do.call(brick,xMeans))
  # you could also return the list instead of a single brick
}
Filter data in function of say 12 months ago depending on the month before the one we may be in without manually typing

Filter data in function of say 12 months ago depending on the month before the one we may be in without manually typing


By : Billy Xu
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further You can use the functions DateAdd and DateSerial.
Imagine today is 2019-01-23. Then …
code :
DateSerial(Year(Date), Month(Date), 1)
LastDayOfPreviousMonth = DateAdd("d", -1, DateSerial(Year(Date), Month(Date), 1))
StartDate = DateAdd("m", -12, LastDayOfPreviousMonth)
Sub filter_()

    MsgBox "12 months filter"

    Dim LastDayOfPreviousMonth As Date
    LastDayOfPreviousMonth = DateAdd("d", -1, DateSerial(Year(Date), Month(Date), 1))

    Dim StartDate As Date
    StartDate = DateAdd("m", -12, LastDayOfPreviousMonth)

    Sheets("RBT-RAT ").ListObjects("Tableau1").Range.AutoFilter Field:=30, _
        Criteria1:=">=" & StartDate, _
        Operator:=xlAnd, _
        Criteria2:="<=" & LastDayOfPreviousMonth
End Sub
Related Posts Related Posts :
  • Percent signs in windows path
  • How to add a random number to a subsection of a numpy array?
  • How to generate all the values of an iterable besides the last few?
  • Searching by both class and range in XPath
  • Python code execution in Perl interpreter
  • Best Way to Include Variable in Python3
  • Serialize the @property methods in a Python class
  • What is the most platform- and Python-version-independent way to make a fast loop for use in Python?
  • Good way to edit the previous defined class in ipython
  • Bounced email on Google App Engine
  • Search jpeg files using python
  • Dynamically create class attributes
  • python unichr problem
  • Python beginner, strange output problem
  • Python: Finding a value in 1 list and finding that corresponding index in another list
  • can't install mysqlclient on mac os x mojave
  • Error indicates flattened dimensions when loading pre-trained network
  • how to replace underlines with words?
  • Adding through iteration
  • Use OpenCV on deployed Flask app (Heroku)
  • How to skip interstitial in a django view if a user hits the back button?
  • Any Naive Bayesian Classifier in python?
  • Python 2.5.2: remove what found between two lines that contain two concrete strings
  • Python 2.5.2 script that add "The function starts here" to all the functions of the files of a directory
  • HttpResponseRedirect question
  • Python socket error on UDP data receive. (10054)
  • Encoding issues with cloud ml
  • numpy.where - Weird behaviour: new elements spawning from nowhere?
  • I can't move my player in pygame, can you figure why?
  • Weird error I receive from Tkinter in Python
  • Using a Zapier Custom Request Webhook with JSON Web Tokens
  • Keras: Use categorical_crossentropy without one-hot encoded array of targets
  • Does python's httplib.HTTPConnection block?
  • Do alternate python implementation version numbers imply that they provide the same syntax?
  • Searching for specific HTML string using Python
  • python sax error "junk after document element"
  • MySql: How to know if an entry is compressed or not
  • Return a list of imported Python modules used in a script?
  • Returning a list in this recursive coi function in python
  • Python2.6 Decimal to Octal
  • Appengine Apps Vs Google bot web crawler
  • Changing models in django results in broken database?
  • Global variable functions
  • Using lambda inside a function
  • How to open a file, replace some strings, and save updates to the same file?
  • How to move the beginning of an input to the and?
  • If else fill variable if empty list
  • Pandas: Find and print all floats in column
  • sqlite3.OperationalError: database is locked - non-threaded application
  • How to implement mib module in net-snmp with python?
  • Does Python/Scipy have a firls( ) replacement (i.e. a weighted, least squares, FIR filter design)?
  • sorl-thumbnail and file renaming
  • Python -- what is NOT in 2.7 that IS in 3.1? So many things have been back-ported, what is NOT?
  • How to make a Django model fields calculated at runtime?
  • Django - Threading in views without hanging the server
  • Python: Why is my POST requests not working?
  • Tried to add a value to a while condition, but it doesn't go back
  • How do I exit a while-true loop after 5 tries?
  • win python3 Multithreading
  • Compare 2 dictionaries in python
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk