Skip to content

Instantly share code, notes, and snippets.

View Bastien-Brd's full-sized avatar

Bastien Bourdon Bastien-Brd

  • Edgefolio
  • London
View GitHub Profile

Keybase proof

I hereby claim:

  • I am bastien-brd on github.
  • I am bastienbourdon (https://keybase.io/bastienbourdon) on keybase.
  • I have a public key ASDQOGyhQzHEuqjPiMoS_ddgNiAot5C7S_zeJwKsqvql2Ao

To claim this, I am signing this object:

@Bastien-Brd
Bastien-Brd / django_find_duplicate_objects.py
Created October 14, 2016 09:41
Django - ORM - Find duplicate objects based on a specific field
"""
Suppose you have a django model called MyModel with a field called 'name'.
If for some reason you did not set a "unique" constraint on that field but would still like to avoid duplicate objects with teh same name,
here is how to find all the duplicate objects based on that "name" field.
"""
duplicate_names = MyModel.objects.values('name', 'id').annotate(Count('name')).order_by().filter(name__count__gt=1)
# You can then retrieve all these duplicate objects using this query:
duplicate_objects = MyModel.objects.filter(id__in=[item['id'] for item in duplicate_names])
import pandas as pd
def rolling_apply_function_of_two_series(func, series1, series2, window=12):
'''
Pandas has a DataFrame.rolling() method, allowing to apply a function of a series/array on a rolling window of the data frame.
However, only functions of one argument (function of one array) are supported.
This is a workaround: allowing to apply a function of two series on a rolling window.
This assumes the two input series have the same index (or at least that the index of series1 overlaps the index of series2)
:param func: A function of two series, returning a scalar