├── MANIFEST.in ├── anonymizer ├── docs │ ├── Transparence_sante.html │ ├── Transparence_santé.html │ └── pycco.css ├── __init__.py ├── config_anonymizer.example.ini ├── config_anonymizer.py ├── comparison.py ├── diversity.py ├── anonymity.py ├── anonymDF.py └── transformations.py ├── examples ├── Transparence Santé │ ├── README.md │ ├── import_insee.py │ └── Transformation_santé.py └── equidés │ ├── Equidés.py │ └── Equidés.ipynb ├── doc ├── anonymization.md └── guide_anonymisation.md ├── tests ├── generate_tab.py ├── _test_transformations.py ├── _test_anonymisation.py ├── _test_AnonymDF.py └── data │ └── iris.csv ├── .gitignore ├── setup.py ├── README.md ├── docs ├── pycco.css ├── Equidés.html └── Transformation_santé.html └── LICENSE /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include *.md 2 | -------------------------------------------------------------------------------- /anonymizer/docs/Transparence_sante.html: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /anonymizer/docs/Transparence_santé.html: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /anonymizer/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Un module qui permet d'anonymiser une base de données à caractère personnel. 4 | """ 5 | 6 | __version__ = "0.0.7" 7 | 8 | 9 | -------------------------------------------------------------------------------- /anonymizer/config_anonymizer.example.ini: -------------------------------------------------------------------------------- 1 | [PATH] 2 | TRANSPARENCE = D:\data\transparence\declaration_avantage_2016_05_23_04_00.csv 3 | INSEE = D:\data\transparence\insee_sante.csv 4 | EQUIDES = D:\data\equides.csv -------------------------------------------------------------------------------- /anonymizer/config_anonymizer.py: -------------------------------------------------------------------------------- 1 | import os 2 | import configparser 3 | 4 | config = configparser.ConfigParser() 5 | config.read(os.path.join(os.path.abspath(os.path.dirname(__file__)), 'config_anonymizer.ini')) 6 | -------------------------------------------------------------------------------- /examples/Transparence Santé/README.md: -------------------------------------------------------------------------------- 1 | Le fichier Transparence.ipynb se veut pédagogique, c'est probablement lui que vous devez lire en premier. 2 | 3 | Le fichier Transformation_santé.py a servi et sert au développement de l'exemple. 4 | 5 | Enfin, Le fichier import_insee.py sert pour utiliser les données aggrégées de l'Insee. 6 | 7 | Pour faire tourner les programmes vous pouvez vous référez au [guide d'installation](https://github.com/SGMAP-AGD/anonymisation) 8 | -------------------------------------------------------------------------------- /doc/anonymization.md: -------------------------------------------------------------------------------- 1 | ### Anonymisation 2 | 3 | Obtenir le niveau de [k-anonymat](https://en.wikipedia.org/wiki/K-anonymity) d'un dataframe en utilisant la fonction `get_k`: 4 | 5 | ```python 6 | from agd_tools import anonymization 7 | 8 | iris_anonymized = iris[['Name']] 9 | k = anonymization.get_k(iris_anonymized) 10 | ``` 11 | 12 | K-anonymiser de façon locale un dataframe en utilisant la fonction `local_aggregation` : 13 | 14 | ```python 15 | from agd_tools import anonymization 16 | 17 | k = 5 18 | var = dataframe.columns.tolist() 19 | local_aggregation(dataframe.copy(), k, var, method = 'regroup') 20 | ``` 21 | -------------------------------------------------------------------------------- /tests/generate_tab.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Wed Jan 20 11:26:08 2016 4 | 5 | @author: Alexis Eidelman 6 | """ 7 | 8 | import numpy as np 9 | import pandas as pd 10 | 11 | def random_table_test_anonym(size, nb_groups, nb_sensible_level): 12 | group = np.random.randint(nb_groups, size=size) 13 | sensible = np.random.randint(nb_sensible_level, size=len(group)) 14 | if isinstance(size, int): 15 | return pd.DataFrame({ 16 | 'identifiant': group, 17 | 'sensible': sensible 18 | }) 19 | else: 20 | output = pd.DataFrame(group) 21 | output.columns = ['ident_' + str(k) for k in range(size[1])] 22 | output['sensible'] = sensible 23 | return output 24 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | 27 | # PyInstaller 28 | # Usually these files are written by a python script from a template 29 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 30 | *.manifest 31 | *.spec 32 | 33 | # Installer logs 34 | pip-log.txt 35 | pip-delete-this-directory.txt 36 | 37 | # Unit test / coverage reports 38 | htmlcov/ 39 | .tox/ 40 | .coverage 41 | .coverage.* 42 | .cache 43 | nosetests.xml 44 | coverage.xml 45 | *,cover 46 | .hypothesis/ 47 | 48 | # Translations 49 | *.mo 50 | *.pot 51 | 52 | # Django stuff: 53 | *.log 54 | 55 | # Sphinx documentation 56 | docs/_build/ 57 | 58 | # PyBuilder 59 | target/ 60 | *.spyderproject 61 | 62 | .ipynb_checkpoints 63 | 64 | anonymizer/config_anonymizer.ini 65 | -------------------------------------------------------------------------------- /tests/_test_transformations.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Wed Jan 20 15:02:50 2016 4 | 5 | @author: Alexis Eidelman 6 | """ 7 | 8 | import string 9 | import random 10 | 11 | import numpy as np 12 | import pandas as pd 13 | 14 | from anonymizer.transformations import * 15 | 16 | # define a test data frame 17 | def id_generator(size=6, chars=string.ascii_uppercase + string.digits): 18 | return ''.join(random.choice(chars) for _ in range(size)) 19 | 20 | size = 1000 21 | _num = pd.Series(np.random.rand(size)) 22 | _str = [id_generator() for x in range(size)] 23 | __date = pd.Series(np.random.randint(1000000000, 2000000000, size)) 24 | _date = pd.to_datetime(__date, unit='s') 25 | 26 | df = pd.DataFrame({'num': _num, 'str': _str, 'date': _date}) 27 | 28 | ## test drop 29 | df_dropped = df.copy() 30 | df_dropped['num'] = num_drop(df['num']) 31 | df_dropped['str'] = str_drop(df['str']) 32 | df_dropped['date'] = date_drop(df['date']) 33 | 34 | for col in df_dropped.columns: 35 | assert(df_dropped[col].nunique() == 1) 36 | 37 | 38 | # 1 test numbers transfo 39 | 40 | 41 | # 2 test string transfo 42 | _str = df['str'] 43 | assert all(first_letters(_str).str.len() == 1) 44 | assert all(first_letters(_str, k = 3).str.len() == 3) 45 | 46 | 47 | # 3 test date transfo 48 | 49 | 50 | -------------------------------------------------------------------------------- /tests/_test_anonymisation.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | import unittest 5 | 6 | import pandas as pd 7 | 8 | from anonymizer.anonymity import get_k 9 | from anonymizer.diversity import (get_l, get_diversities, diversity_distribution, 10 | less_diverse_groups) 11 | 12 | __author__ = "Alexis, Paul" 13 | 14 | class TestAnonymisationMethods(unittest.TestCase): 15 | 16 | def test_get_k(self): 17 | iris = pd.read_csv("data/iris.csv") 18 | k = get_k(iris, ['Name']) 19 | self.assertEqual(k, 50) 20 | 21 | def test_get_distinct_l(self): 22 | iris = pd.read_csv("data/iris.csv") 23 | l_diversity = get_l(iris, groupby=['Name'], column='PetalLength') 24 | self.assertEqual(l_diversity, 9) 25 | 26 | def test_get_distinct_l_with_nulls(self): 27 | iris = pd.read_csv("data/iris.csv") 28 | iris = iris.append(pd.DataFrame([[1, 1, None, 1, "Iris-Test"], 29 | [1, 1, None, 1, "Iris-Test"], 30 | [1, 1, 2, 1, "Iris-Test"]], 31 | columns=iris.columns.values)) 32 | l_diversity = get_l(iris, groupby=['Name'], column='PetalLength') 33 | self.assertEqual(l_diversity, 3) 34 | 35 | if __name__ == '__main__': 36 | unittest.main() 37 | 38 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | from setuptools import setup, find_packages 5 | 6 | 7 | import anonymizer 8 | 9 | 10 | setup( 11 | 12 | # le nom de votre bibliothèque, tel qu'il apparaitre sur pypi 13 | name='anonymizer', 14 | 15 | # la version du code 16 | version=anonymizer.__version__, 17 | 18 | 19 | packages=find_packages(), 20 | 21 | 22 | author="SGMAP-AGD", 23 | 24 | 25 | author_email="plbithorel@gmail.com", 26 | 27 | # Une description courte 28 | description="Module de k-anonymisation", 29 | 30 | 31 | long_description=open('README.md').read(), 32 | 33 | include_package_data=True, 34 | 35 | 36 | url='https://github.com/SGMAP-AGD/anonymisation', 37 | 38 | # Il est d'usage de mettre quelques metadata à propos de sa lib 39 | # Pour que les robots puissent facilement la classer. 40 | # La liste des marqueurs autorisées est longue: 41 | # https://pypi.python.org/pypi?%3Aaction=list_classifiers. 42 | # 43 | # Il n'y a pas vraiment de règle pour le contenu. Chacun fait un peu 44 | # comme il le sent. Il y en a qui ne mettent rien. 45 | classifiers=[ 46 | "Programming Language :: Python", 47 | "Development Status :: 1 - Planning", 48 | "License :: OSI Approved :: GNU General Public License (GPL)", 49 | "Natural Language :: French", 50 | "Operating System :: OS Independent", 51 | "Programming Language :: Python :: 3", 52 | ], 53 | 54 | 55 | entry_points = { 56 | 'console_scripts': [ 57 | 'local_agregation = anonymizer.anonymity:local_agregation', 58 | 'get_k = anonymizer.anonymity:get_k', 59 | ], 60 | }, 61 | 62 | 63 | ) 64 | -------------------------------------------------------------------------------- /tests/_test_AnonymDF.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Wed Jan 20 11:37:34 2016 4 | 5 | @author: Alexis Eidelman 6 | """ 7 | 8 | #TODO: import unittest 9 | 10 | from anonymizer.anonymDF import AnonymDataFrame 11 | import anonymizer.transformations as transfo 12 | from generate_tab import random_table_test_anonym 13 | 14 | tab = random_table_test_anonym(1000, 8, 5) 15 | 16 | test = AnonymDataFrame(tab, ['identifiant'], 'sensible') 17 | 18 | test.get_k() 19 | test.get_l() 20 | 21 | 22 | nb_cols = 4 23 | tab = random_table_test_anonym((1000, nb_cols), 8, 5) 24 | nom_cols = ['ident_' + str(k) for k in range(nb_cols)] 25 | tab = tab.astype(str) 26 | 27 | test = AnonymDataFrame(tab, nom_cols, 'sensible') 28 | 29 | test.get_k() 30 | test.get_l() 31 | 32 | def transfo_0(x): 33 | return transfo.local_aggregation(x, 5, 'with_closest', unknown='') 34 | 35 | def transfo_1(x): 36 | return transfo.local_aggregation(x, 5, 'regroup_with_smallest', unknown='') 37 | 38 | list_transfo = [('ident_0', transfo_0), ('ident_1', transfo_0), 39 | ('ident_2', transfo_0), ('ident_3', transfo_0)] 40 | 41 | list_transfo2= [('ident_0', transfo_1), ('ident_1', transfo_0), 42 | ('ident_2', transfo_0)] 43 | 44 | transfo1 = test.transform(list_transfo) 45 | transfo2 = test.local_transform(list_transfo, 5) 46 | 47 | transfo1 = test.transform([]) 48 | 49 | from anonymizer.comparison import batterie_de_test 50 | 51 | anonymisation1 = test.transform(list_transfo) 52 | anonymisation2 = test.transform(list_transfo2) 53 | batterie_de_test(anonymisation1, anonymisation2) 54 | 55 | xxx 56 | 57 | anonymisation1 = test.transform(list_transfo) 58 | anonymisation2 = test.transform(list_transfo) 59 | batterie_de_test(anonymisation1, anonymisation2) 60 | 61 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Anonymisation 2 | 3 | Le répertoire anonymisation fournit une méthode, des outils et des références sur l'anonymisation des données à caractère personnel. 4 | 5 | ## Objectifs et usages 6 | 7 | Ce projet a pour objectif : 8 | 9 | + D'introduire l'utilisateur et le producteur de données aux enjeux de l'anonymisation, d'un point de vue juridique, scientifique et technique. 10 | + De construire un espace collaboratif autour de ce thème. 11 | + De proposer une méthode robuste et testée de k-anonymisation de données. 12 | 13 | ## Contenu 14 | 15 | Plus précisément, cet espace est constitué : 16 | 17 | * D'un [wiki](https://github.com/SGMAP-AGD/anonymisation/wiki) qui détaille la démarche, les outils et [l'exemple de Transparence Santé](https://github.com/SGMAP-AGD/anonymisation/wiki/Transparence-Sant%C3%A9). 18 | * Du code qui formalise le traitement de k-anonymisation. 19 | * De deux exemples d'application à [Transparence Santé](Transparence-Santé) et à [Équides](Transparence-Santé). 20 | 21 | ## Données à télécharger 22 | 23 | Les données exploitées pour tester notre algorithme peuvent être téléchargées aux endroits suivants : 24 | * [Transparence Santé](https://www.data.gouv.fr/fr/datasets/transparence-sante-1/) (data.gouv.fr) 25 | * [Données INSEE pour l'enrichissement des données](http://www.insee.fr/fr/themes/detail.asp?reg_id=99&ref_id=equip-serv-medical-para) (INSEE) 26 | * [Fichier des équidés](https://www.data.gouv.fr/fr/datasets/fichier-des-equides/) (data.gouv.fr) 27 | 28 | ## Installation 29 | 30 | pip install anonymizer 31 | 32 | Pour l'application des exemples, pensez à bien renseigner vos répertoires de travail dans le fichiers config-anonymizer.ini selon l'exemple de config_anonymizer.ini.exemple. 33 | 34 | ## Voir aussi 35 | 36 | * [Consultation sur les logiciels d'anonymisation](https://forum.etalab.gouv.fr/search?q=anonymisation) 37 | -------------------------------------------------------------------------------- /anonymizer/comparison.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Recueil de méthode pour comparer deux anonymisations 4 | 5 | Created on Wed Aug 24 18:20:24 2016 6 | 7 | @author: aeidelman 8 | """ 9 | 10 | from anonymizer.anonymDF import AnonymDataFrame 11 | 12 | 13 | def _identical_transformation(transfo1, transfo2): 14 | if len(transfo1) != len(transfo2): 15 | return False 16 | for k in range(len(transfo1)): 17 | if transfo1[k][0] != transfo2[k][0] or transfo1[k][1] != transfo2[k][1]: 18 | return False 19 | return True 20 | 21 | def compare_ce_qui_est_comparable(anonymisation1, anonymisation2): 22 | ''' verifie que les deux objets peuvent être comparés ''' 23 | assert isinstance(anonymisation1, AnonymDataFrame) 24 | assert isinstance(anonymisation2, AnonymDataFrame) 25 | 26 | assert all(anonymisation1.df == anonymisation2.df) 27 | 28 | if _identical_transformation(anonymisation1.transformation, 29 | anonymisation2.transformation): 30 | assert all(anonymisation1.anonymized_df == anonymisation2.anonymized_df) 31 | raise Exception("a priori, c'est la même anonymisation") 32 | 33 | 34 | def batterie_de_test(anonymisation1, anonymisation2): 35 | 36 | compare_ce_qui_est_comparable(anonymisation1, anonymisation2) 37 | 38 | df = anonymisation1.df # = anonymisation2.df 39 | df1 = anonymisation1.anonymized_df 40 | transfo1 = anonymisation1.transformation 41 | df2 = anonymisation2.anonymized_df 42 | transfo2 = anonymisation2.transformation 43 | 44 | if len(df) != len(df1) or len(df) != len(df2): 45 | print('le nombre de lignes de la table initiale est ', len(df)) 46 | print(len(df1), 'lignes ont été supprimées dans la première anonymisation') 47 | print(len(df2), 'lignes ont été supprimées dans la seconde anonymisation') 48 | 49 | 50 | print((df1 == df2).sum()) 51 | 52 | -------------------------------------------------------------------------------- /examples/Transparence Santé/import_insee.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | 3 | # Nouvelle fonction pour expand la base insee, afin de pouvoir l'intégrer ensuite à la base transparence 4 | 5 | # Prend en arguments : 6 | # - les données INSEE sous forme de dataframe, groupées par département 7 | # - annuaire de correspondances entre les professions INSEE et les professions Transparence Santé 8 | 9 | def expand_insee (df_groupby_dept, annuaire, avantages) : 10 | effectif_sante_dept = df_groupby_dept.sum() 11 | départements = effectif_sante_dept.index.tolist() 12 | pro = effectif_sante_dept.columns.tolist() 13 | expand_insee = pd.DataFrame() 14 | ligne = [] 15 | 16 | for départmt in départements : 17 | for profession in pro : 18 | if annuaire[profession][0] == 'benef_specialite_code' : 19 | ligne = ['non renseigné', 20 | '[PRS]', 'Médecin', '[FR]', '[DR]', annuaire[profession][1], '[RPPS]', 21 | 'non renseigné', 'non renseigné', 'non renseigné', départmt, 'non renseigné', 22 | 'non renseigné'] 23 | 24 | elif annuaire[profession][0] == 'qualite' : 25 | ligne = ['non renseigné', 26 | '[PRS]', annuaire[profession][1], '[FR]', 'non renseigné', 'non renseigné', 'non renseigné', 27 | 'non renseigné', 'non renseigné', 'non renseigné', départmt, 'non renseigné', 28 | 'non renseigné'] 29 | 30 | nombre_total = effectif_sante_dept.loc[départmt, profession] 31 | nombre_déjà_présent = len(avantages[(avantages['benef_dept']==départmt)&(avantages[annuaire[profession][0]]==annuaire[profession][1])]) 32 | nombre_ajoutés = nombre_total - nombre_déjà_présent 33 | 34 | expand_insee = pd.concat([expand_insee, pd.DataFrame(nombre_ajoutés*[ligne])]) 35 | 36 | return(expand_insee) 37 | 38 | 39 | # Fonction pour calculer le nombre de modifications apportées 40 | # Arguments : 41 | # - Result : dataframe, anonymisée 42 | # - Base : dataframe brute, intput de l'anonymisation 43 | # - insee = 'oui' ou insee = 'non' : la base inclut les données INSEE (oui) ou pas (non) 44 | def nbre_modif (result, base, insee = 'non'): 45 | if insee == 'oui' : 46 | nombre_modifications = (result[result['ligne_type']=='[A]'] != base[base['ligne_type']=='[A]']).sum().sum() 47 | else : 48 | nombre_modifications = (result != base).sum().sum() 49 | return(nombre_modifications) 50 | -------------------------------------------------------------------------------- /anonymizer/diversity.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Wed Jan 20 10:55:46 2016 4 | 5 | @author: Alexis Eidelman, Paul 6 | """ 7 | 8 | 9 | def _l_diversity(x): 10 | """ 11 | A simple implementation of l-diversity counting na as distinct values 12 | 13 | Aggarwal, Charu C.; Yu, Philip S. (2008): 14 | "A General Survey of Privacy" 15 | http://charuaggarwal.net/generalsurvey.pdf 16 | Springer. ISBN 978-0-387-70991-8 17 | """ 18 | nb_distinct_without_na = x.nunique(dropna=True) 19 | nb_of_na = sum(x.isnull()) 20 | return nb_distinct_without_na + nb_of_na 21 | 22 | 23 | def get_diversities(df, groupby, column): 24 | """ 25 | Return the diversities levels of a column in a dataframe. 26 | 27 | This implementation takes Nan values as distinct modalities. 28 | 29 | You should replace all invalid, unknown and false rows by 30 | the numpy nan type before using this function. 31 | 32 | :param df: A pandas dataframe 33 | :param column: The sensible data column 34 | :param groupby: The columns to group by 35 | :type df: pandas.core.frame.DataFrame 36 | :type column: str 37 | :type groupby: list 38 | :return: diversities for each group 39 | :rtype: pandas.core.frame.DataFrame 40 | 41 | :Example: 42 | 43 | >>> iris = pd.read_csv("tests/iris.csv") 44 | >>> diversities = anonymization.get_diversities(iris, 45 | groupby=['Name'], 46 | column='PetalLength') 47 | """ 48 | grp = df.groupby(groupby) 49 | res = grp[column].agg({'l_diversity' : _l_diversity }) 50 | return res 51 | 52 | 53 | def get_l(df, groupby, column): 54 | """ 55 | Return the l-diversity value as an integer. 56 | 57 | Calls the get_diversities and extract the minimum l-diversity level. 58 | 59 | :param df: The dataframe to get l from 60 | :param column: The sensible data column 61 | :param groupby: The columns to group by 62 | :type df: pandas.core.frame.DataFrame 63 | :type column: str 64 | :type groupby: list 65 | :return: l-diversity 66 | :rtype: int 67 | 68 | 69 | """ 70 | return min(get_diversities(df, groupby, column)['l_diversity']) 71 | 72 | 73 | def diversity_distribution(df, groupby, column): 74 | """ 75 | Return the l-diversity distribution of a dataframe. 76 | """ 77 | diversity = get_diversities(df, groupby, column)['l_diversity'] 78 | return diversity.value_counts().sort_index() 79 | 80 | 81 | def less_diverse_groups(df, groupby, column): 82 | """ 83 | Return the less diverse groups. 84 | """ 85 | grp = df.groupby(groupby) 86 | res = grp[column].agg({'l_diversity' : _l_diversity }) 87 | diversity = res['l_diversity'] 88 | select = diversity[diversity == min(diversity)] 89 | results = [] 90 | for group_index in select.index: 91 | results += [grp.get_group(group_index)] 92 | return results 93 | -------------------------------------------------------------------------------- /anonymizer/anonymity.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Wed Jan 20 10:55:39 2016 4 | 5 | @author: Alexis Eidelman 6 | """ 7 | import numpy as np 8 | import pandas as pd 9 | 10 | from anonymizer.transformations import local_aggregation 11 | 12 | def _remove_unknown(tab, groupby, unknown): 13 | if unknown is not None: 14 | cond_unknown = (tab[groupby] == unknown).any(axis=1) 15 | tab = tab[~cond_unknown] 16 | return tab 17 | 18 | def get_k(df, groupby, unknown=None): 19 | """ 20 | Return the k-anonymity level of a df, grouped by the specified columns. 21 | 22 | :param df: The dataframe to get k from 23 | :param groupby: The columns to group by 24 | :type df: pandas.DataFrame 25 | :type groupby: Array 26 | :return: k-anonymity 27 | :rtype: int 28 | """ 29 | df = _remove_unknown(df, groupby, unknown) 30 | size_group = df.groupby(groupby).size() 31 | if len(size_group) == 0: 32 | return np.Infinity 33 | return min(size_group) 34 | 35 | 36 | def get_anonymities(df, groupby, unknown=None): 37 | df = _remove_unknown(df, groupby, unknown) 38 | return df.groupby(groupby).size() 39 | 40 | 41 | def less_anonym_groups(df, groupby, unknown=None): 42 | df = _remove_unknown(df, groupby[:-1], unknown) 43 | df = _remove_unknown(df, groupby, unknown) 44 | grp = df.groupby(groupby) 45 | size_group = grp.size() 46 | select = size_group[size_group == min(size_group)] 47 | results = [] 48 | for group_index in select.index: 49 | results += [grp.get_group(group_index)] 50 | return results 51 | 52 | 53 | def all_local_aggregation(tab, k, variables, method, unknown=''): 54 | ''' 55 | retourne une table k-anonymisée par aggrégation locale 56 | 57 | tab: la table à anonymiser 58 | k: un entier est le k-anonymat recherché 59 | variables est une liste de variable de tab : 60 | on traitera les données dans cet ordre et 61 | la première variable sera celle dont on est le plus 62 | prêt à sacrifier l'aggrégation 63 | method : voir local_aggregation 64 | 65 | Remarque: si pour un groupe donné, plusieurs modalité ont moins de k 66 | éléments, on les remplace toutes par "dropped", on peut ainsi avoir un 67 | groupe avec dropped d'une taille supérieure à k. 68 | Si ensuite on a une modalité plus grande que k à l'intérieur du groupe 69 | hétéroclyte avec dropped, on peut afficher cette variable 70 | ''' 71 | assert(isinstance(k, int)) 72 | assert(all([var in tab.columns for var in variables])) 73 | assert(all(tab[variables].dtypes == 'object')) 74 | 75 | if get_k(tab, variables) >= k: 76 | return tab 77 | 78 | variable_a_aggreger = variables[-1] 79 | if len(variables) == 1: 80 | new_serie = local_aggregation(tab[variable_a_aggreger], 81 | k, method, unknown) 82 | tab[variable_a_aggreger] = new_serie 83 | return tab 84 | 85 | if get_k(tab, variables[:-1]) < k: 86 | tab = all_local_aggregation(tab, k, variables[:-1], method, unknown) 87 | # on a une table k-anonymisée lorsqu'elle est restreinte aux 88 | # len(variables) - 1 premières variables 89 | 90 | # on applique l'aggrégation locale d'une variable par groupe 91 | grp = tab.groupby(variables[:-1]) 92 | new_serie = grp[variable_a_aggreger].apply( 93 | lambda x: local_aggregation(x, k, method, unknown) 94 | ) 95 | tab[variable_a_aggreger] = new_serie 96 | 97 | assert get_k(tab, variables, unknown) >= k 98 | 99 | return tab 100 | 101 | -------------------------------------------------------------------------------- /doc/guide_anonymisation.md: -------------------------------------------------------------------------------- 1 | # Guide pratique de l'anonymisation 2 | 3 | L'anonymisation est un processus mis en oeuvre lors de certains traitements de données personnelles. Il vise, dans un jeu de donné publié, à empêcher de: 4 | 5 | * Distinguer un individu. 6 | * Lier des informations relatives à un individu. 7 | * Inférer des informations concernant un individu. 8 | 9 | L'anonymisation ne se limite pas à la suppression des champs identifiants d'un jeu de données, comme le nom ou l'adresse d'un individu. D'autres variables, qualifiées de réidentifiantes, peuvent être utilisées pour identifier un individu au sein d'un jeu de données. Il est donc nécessaire de mettre en oeuvre des techniques plus avancées d'anonymisation, comme la généralisation. 10 | 11 | ## Classement des variables 12 | 13 | Une des première étapes du processus d'anonymisation consiste à classer les variables en 3 catégories: 14 | 15 | * **Variables (directement) identifiantes** : nom, prénom, identifiant utilisateur, numéro de Sécurité Sociale, etc. 16 | * **Variables quasi-identifiantes** : une variable est quasi-identifiante, si, une fois combinée avec d'autres variables, elle permet l'identification d'un individu. Exemple : l'identité de vos parents et votre âge. 17 | * **Variables sensibles** : une variable est dite sensible si elle révèle une information personnelle, privée ou confidentielle à propos d'un individu. Exemple : la personne est malade ou non. 18 | Notons que la frontière entre ces différents types est parfois assez poreuse : on peut tout à la fois considérer l'adresse d'un individu comme une variable identifiante, quasi-identifiante et sensible. 19 | 20 | ## Variables identifiantes 21 | 22 | Les variables identifiantes sont obfusquées ou tout simplement retirées lors de l'anonymisation. 23 | On parle alors de **pseudonymisation** une fois cette étape passée. Le jeu de données n'est à ce stade pas encore anonymisé. 24 | 25 | ### Obfuscation 26 | 27 | Parfois, certaines variables identifiantes ne doivent pas être retirées du jeu de données anonymisé. C'est par exemple le cas lorsque le jeu données servira à analyser des parcours utilisateur et qu'un identifiant individuel apparaitra plusieurs fois dans le jeu de données anonymisé. Il convient alors d'obfusquer cet identifiant pour ne pas le dévoiler tout en préservant son caractère particulier. 28 | 29 | La méthode retenue dans ce cas est celle du hachage des champs concernés. Les champs concernés doivent être hachés en utilisant un algorithme issu de la famille SHA-2 ou SHA-3 http://csrc.nist.gov/publications/fips/fips180-4/fips-180-4.pdf, les plus robustes à l'heure actuelle. Ces fonctions sont disponibles dans toutes les blibliothèques cryptographiques des langages de programmation. 30 | 31 | R: digest 32 | Python: hashlib 33 | SAS 34 | Java 35 | 36 | 37 | ## Anonymisation par généralisation 38 | 39 | Lors d'une anonymisation par aggrégation, les variables sont modifiées de telle sorte à rendre la ré-identification impossible. Ces modifications peuvent prendre plusieurs formes. 40 | + On peut appliquer un changement d'échelle, en passant, par exemple, d'un code communal (75001) à un code départemental (75). 41 | + On peut aussi fusionner plusieurs modalités, soit de façon générale (sur toute la base), soit de manière locale (seules les modalités des lignes qui posent problème seront modifiées). Exemple : deux lignes qui prennent comme code postal "75001" et "75014" prennent comme nouvelle modalité "75001 ou 75014". 42 | 43 | ### K-anonymat 44 | On considère qu'une base de données est k-anonymisée, si et seulement si à chaque combinaison de modalités de variables quasi-identifiantes qui composent la base correspond un *minimum* de k d'individus. 45 | 46 | ### L-Diversité 47 | On considère qu'une base de données est l-diverse : 48 | + si à chaque combinaison de modalités de variables quasi-identifiantes qui composent la base correspond un groupe composé *d'au moins* k individus et, 49 | + si ce groupe présente *au moins* l modalités différentes en ce qui concerne la (ou les) variable(s) sensible(s). 50 | 51 | ### Mesurer la perte d'informations 52 | 53 | ARTICLE 29 DATA PROTECTION WORKING PARTY 54 | http://ec.europa.eu/justice/data-protection/article-29/documentation/opinion-recommendation/files/2014/wp216_en.pdf 55 | -------------------------------------------------------------------------------- /examples/equidés/Equidés.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | #!/usr/bin/env python 4 | 5 | 6 | """ 7 | A partir des fonctions du dépôt anonymizer, ce fichier va notamment vous permettre de : 8 | 9 | 1. **Importer** les données de la base équidés. 10 | 2. **Nettoyer** les variables et sélectionner celles à anonymiser 11 | 3. **Anonymiser** les données selon un procédé de K-anonymisation 12 | 13 | The file can be downloaded here: 14 | https://www.data.gouv.fr/fr/datasets/fichier-des-equides/ 15 | or directly : 16 | https://www.data.gouv.fr/s/resources/fichier-des-equides/20141201-185229/Equides.csv 17 | 18 | Le fichier de 200 Mo contient autours de 3 millions de lignes 19 | 20 | """ 21 | 22 | import csv 23 | import numpy as np 24 | import pandas as pd 25 | import matplotlib 26 | import matplotlib.pyplot as plt 27 | 28 | from anonymizer.anonymity import (get_k, get_anonymities, 29 | less_anonym_groups, 30 | all_local_aggregation) 31 | from anonymizer.diversity import (get_l, 32 | get_diversities, 33 | diversity_distribution, 34 | less_diverse_groups 35 | ) 36 | from anonymizer.transformations import (first_letters, 37 | last_letters, 38 | local_aggregation) 39 | from anonymizer.transformations import str_drop 40 | from anonymizer.anonymDF import AnonymDataFrame 41 | 42 | from anonymizer.config_anonymizer import config 43 | import os 44 | import io 45 | 46 | 47 | # ## I. Nettoyage de la base de données 48 | path_data = config['PATH']['EQUIDES'] 49 | equides = pd.read_csv(path_data, sep = ";", encoding = "ISO-8859-1", 50 | nrows = 50000, header=None, low_memory = False) 51 | 52 | nom_de_colonnes = ['Race', 53 | 'Sexe', 54 | 'Robe', 55 | 'Date de naissance', 56 | 'Pays de naissance', 57 | 'Nom', 58 | 'Destiné à la consommation humaine', 59 | 'Date de mort'] 60 | equides.columns = nom_de_colonnes 61 | 62 | 63 | # On supprime la date de mort puisque cela nous fournirait un indice sur l'âge du cheval, 64 | # qu'il faudrait veiller à anonymiser. 65 | 66 | variables_supprimees = ['Date de mort', 'Destiné à la consommation humaine'] 67 | equides = equides.drop(variables_supprimees,1) 68 | 69 | # La variable "date de naissance" doit être recodée. On choisit de ne garder que l'année. 70 | equides['Date de naissance'] = last_letters(equides['Date de naissance'],6) 71 | 72 | # On remplace les modalités vides ou non renseignées par des "non renseigné" 73 | equides = equides.fillna('non renseigné') 74 | equides = equides.applymap(lambda x: x.strip()) 75 | equides.replace('', 'non renseigné', inplace=True) 76 | 77 | 78 | 79 | # On convertit tous les noms de races en minuscules afin de mieux pouvoir uniformiser 80 | # et on normalise afin de n'obtenir plus qu'une modalité inconnu, anglo-arabe, weslh ou aa compl. 81 | 82 | equides['Race'] = equides['Race'].str.lower() 83 | liste_races = equides['Race'].unique().tolist() 84 | 85 | for word in ['inconnu', 'anglo-arabe', 'welsh', 'aa compl.']: 86 | for race in liste_races : 87 | if word in race: 88 | print(word, race) 89 | equides['Race'] = equides['Race'].replace(race, word) 90 | 91 | equides.replace('inconnu', 'non renseigné', inplace=True) 92 | liste_races = equides['Race'].unique().tolist() 93 | len(liste_races) 94 | 95 | 96 | # ## II. Anonymisation 97 | 98 | # On définit les variables à anonymiser 99 | 100 | ordre_aggregation = ['Race', 101 | 'Sexe', 102 | 'Robe', 103 | 'Pays de naissance', 104 | 'Destiné à la consommation humaine', 105 | 'Date de naissance'] 106 | 107 | 108 | Equides = AnonymDataFrame(equides, ordre_aggregation, unknown='non renseigné') 109 | 110 | def aggregation_serie(x): 111 | return(local_aggregation(x, 5, 'regroup_with_smallest', 'non renseigné')) 112 | method_anonymisation = [(name, aggregation_serie) for name in ordre_aggregation[:-1]] 113 | 114 | def aggregation_year(x): 115 | return(local_aggregation(x, 5, 'with_closest', 'non renseigné')) 116 | method_anonymisation += [('Date de naissance', aggregation_year)] 117 | 118 | Equides.local_transform(method_anonymisation, 5) 119 | 120 | Equides.df = Equides.anonymized_df 121 | 122 | Equides.get_k() 123 | -------------------------------------------------------------------------------- /tests/data/iris.csv: -------------------------------------------------------------------------------- 1 | SepalLength,SepalWidth,PetalLength,PetalWidth,Name 2 | 5.1,3.5,1.4,0.2,Iris-setosa 3 | 4.9,3.0,1.4,0.2,Iris-setosa 4 | 4.7,3.2,1.3,0.2,Iris-setosa 5 | 4.6,3.1,1.5,0.2,Iris-setosa 6 | 5.0,3.6,1.4,0.2,Iris-setosa 7 | 5.4,3.9,1.7,0.4,Iris-setosa 8 | 4.6,3.4,1.4,0.3,Iris-setosa 9 | 5.0,3.4,1.5,0.2,Iris-setosa 10 | 4.4,2.9,1.4,0.2,Iris-setosa 11 | 4.9,3.1,1.5,0.1,Iris-setosa 12 | 5.4,3.7,1.5,0.2,Iris-setosa 13 | 4.8,3.4,1.6,0.2,Iris-setosa 14 | 4.8,3.0,1.4,0.1,Iris-setosa 15 | 4.3,3.0,1.1,0.1,Iris-setosa 16 | 5.8,4.0,1.2,0.2,Iris-setosa 17 | 5.7,4.4,1.5,0.4,Iris-setosa 18 | 5.4,3.9,1.3,0.4,Iris-setosa 19 | 5.1,3.5,1.4,0.3,Iris-setosa 20 | 5.7,3.8,1.7,0.3,Iris-setosa 21 | 5.1,3.8,1.5,0.3,Iris-setosa 22 | 5.4,3.4,1.7,0.2,Iris-setosa 23 | 5.1,3.7,1.5,0.4,Iris-setosa 24 | 4.6,3.6,1.0,0.2,Iris-setosa 25 | 5.1,3.3,1.7,0.5,Iris-setosa 26 | 4.8,3.4,1.9,0.2,Iris-setosa 27 | 5.0,3.0,1.6,0.2,Iris-setosa 28 | 5.0,3.4,1.6,0.4,Iris-setosa 29 | 5.2,3.5,1.5,0.2,Iris-setosa 30 | 5.2,3.4,1.4,0.2,Iris-setosa 31 | 4.7,3.2,1.6,0.2,Iris-setosa 32 | 4.8,3.1,1.6,0.2,Iris-setosa 33 | 5.4,3.4,1.5,0.4,Iris-setosa 34 | 5.2,4.1,1.5,0.1,Iris-setosa 35 | 5.5,4.2,1.4,0.2,Iris-setosa 36 | 4.9,3.1,1.5,0.1,Iris-setosa 37 | 5.0,3.2,1.2,0.2,Iris-setosa 38 | 5.5,3.5,1.3,0.2,Iris-setosa 39 | 4.9,3.1,1.5,0.1,Iris-setosa 40 | 4.4,3.0,1.3,0.2,Iris-setosa 41 | 5.1,3.4,1.5,0.2,Iris-setosa 42 | 5.0,3.5,1.3,0.3,Iris-setosa 43 | 4.5,2.3,1.3,0.3,Iris-setosa 44 | 4.4,3.2,1.3,0.2,Iris-setosa 45 | 5.0,3.5,1.6,0.6,Iris-setosa 46 | 5.1,3.8,1.9,0.4,Iris-setosa 47 | 4.8,3.0,1.4,0.3,Iris-setosa 48 | 5.1,3.8,1.6,0.2,Iris-setosa 49 | 4.6,3.2,1.4,0.2,Iris-setosa 50 | 5.3,3.7,1.5,0.2,Iris-setosa 51 | 5.0,3.3,1.4,0.2,Iris-setosa 52 | 7.0,3.2,4.7,1.4,Iris-versicolor 53 | 6.4,3.2,4.5,1.5,Iris-versicolor 54 | 6.9,3.1,4.9,1.5,Iris-versicolor 55 | 5.5,2.3,4.0,1.3,Iris-versicolor 56 | 6.5,2.8,4.6,1.5,Iris-versicolor 57 | 5.7,2.8,4.5,1.3,Iris-versicolor 58 | 6.3,3.3,4.7,1.6,Iris-versicolor 59 | 4.9,2.4,3.3,1.0,Iris-versicolor 60 | 6.6,2.9,4.6,1.3,Iris-versicolor 61 | 5.2,2.7,3.9,1.4,Iris-versicolor 62 | 5.0,2.0,3.5,1.0,Iris-versicolor 63 | 5.9,3.0,4.2,1.5,Iris-versicolor 64 | 6.0,2.2,4.0,1.0,Iris-versicolor 65 | 6.1,2.9,4.7,1.4,Iris-versicolor 66 | 5.6,2.9,3.6,1.3,Iris-versicolor 67 | 6.7,3.1,4.4,1.4,Iris-versicolor 68 | 5.6,3.0,4.5,1.5,Iris-versicolor 69 | 5.8,2.7,4.1,1.0,Iris-versicolor 70 | 6.2,2.2,4.5,1.5,Iris-versicolor 71 | 5.6,2.5,3.9,1.1,Iris-versicolor 72 | 5.9,3.2,4.8,1.8,Iris-versicolor 73 | 6.1,2.8,4.0,1.3,Iris-versicolor 74 | 6.3,2.5,4.9,1.5,Iris-versicolor 75 | 6.1,2.8,4.7,1.2,Iris-versicolor 76 | 6.4,2.9,4.3,1.3,Iris-versicolor 77 | 6.6,3.0,4.4,1.4,Iris-versicolor 78 | 6.8,2.8,4.8,1.4,Iris-versicolor 79 | 6.7,3.0,5.0,1.7,Iris-versicolor 80 | 6.0,2.9,4.5,1.5,Iris-versicolor 81 | 5.7,2.6,3.5,1.0,Iris-versicolor 82 | 5.5,2.4,3.8,1.1,Iris-versicolor 83 | 5.5,2.4,3.7,1.0,Iris-versicolor 84 | 5.8,2.7,3.9,1.2,Iris-versicolor 85 | 6.0,2.7,5.1,1.6,Iris-versicolor 86 | 5.4,3.0,4.5,1.5,Iris-versicolor 87 | 6.0,3.4,4.5,1.6,Iris-versicolor 88 | 6.7,3.1,4.7,1.5,Iris-versicolor 89 | 6.3,2.3,4.4,1.3,Iris-versicolor 90 | 5.6,3.0,4.1,1.3,Iris-versicolor 91 | 5.5,2.5,4.0,1.3,Iris-versicolor 92 | 5.5,2.6,4.4,1.2,Iris-versicolor 93 | 6.1,3.0,4.6,1.4,Iris-versicolor 94 | 5.8,2.6,4.0,1.2,Iris-versicolor 95 | 5.0,2.3,3.3,1.0,Iris-versicolor 96 | 5.6,2.7,4.2,1.3,Iris-versicolor 97 | 5.7,3.0,4.2,1.2,Iris-versicolor 98 | 5.7,2.9,4.2,1.3,Iris-versicolor 99 | 6.2,2.9,4.3,1.3,Iris-versicolor 100 | 5.1,2.5,3.0,1.1,Iris-versicolor 101 | 5.7,2.8,4.1,1.3,Iris-versicolor 102 | 6.3,3.3,6.0,2.5,Iris-virginica 103 | 5.8,2.7,5.1,1.9,Iris-virginica 104 | 7.1,3.0,5.9,2.1,Iris-virginica 105 | 6.3,2.9,5.6,1.8,Iris-virginica 106 | 6.5,3.0,5.8,2.2,Iris-virginica 107 | 7.6,3.0,6.6,2.1,Iris-virginica 108 | 4.9,2.5,4.5,1.7,Iris-virginica 109 | 7.3,2.9,6.3,1.8,Iris-virginica 110 | 6.7,2.5,5.8,1.8,Iris-virginica 111 | 7.2,3.6,6.1,2.5,Iris-virginica 112 | 6.5,3.2,5.1,2.0,Iris-virginica 113 | 6.4,2.7,5.3,1.9,Iris-virginica 114 | 6.8,3.0,5.5,2.1,Iris-virginica 115 | 5.7,2.5,5.0,2.0,Iris-virginica 116 | 5.8,2.8,5.1,2.4,Iris-virginica 117 | 6.4,3.2,5.3,2.3,Iris-virginica 118 | 6.5,3.0,5.5,1.8,Iris-virginica 119 | 7.7,3.8,6.7,2.2,Iris-virginica 120 | 7.7,2.6,6.9,2.3,Iris-virginica 121 | 6.0,2.2,5.0,1.5,Iris-virginica 122 | 6.9,3.2,5.7,2.3,Iris-virginica 123 | 5.6,2.8,4.9,2.0,Iris-virginica 124 | 7.7,2.8,6.7,2.0,Iris-virginica 125 | 6.3,2.7,4.9,1.8,Iris-virginica 126 | 6.7,3.3,5.7,2.1,Iris-virginica 127 | 7.2,3.2,6.0,1.8,Iris-virginica 128 | 6.2,2.8,4.8,1.8,Iris-virginica 129 | 6.1,3.0,4.9,1.8,Iris-virginica 130 | 6.4,2.8,5.6,2.1,Iris-virginica 131 | 7.2,3.0,5.8,1.6,Iris-virginica 132 | 7.4,2.8,6.1,1.9,Iris-virginica 133 | 7.9,3.8,6.4,2.0,Iris-virginica 134 | 6.4,2.8,5.6,2.2,Iris-virginica 135 | 6.3,2.8,5.1,1.5,Iris-virginica 136 | 6.1,2.6,5.6,1.4,Iris-virginica 137 | 7.7,3.0,6.1,2.3,Iris-virginica 138 | 6.3,3.4,5.6,2.4,Iris-virginica 139 | 6.4,3.1,5.5,1.8,Iris-virginica 140 | 6.0,3.0,4.8,1.8,Iris-virginica 141 | 6.9,3.1,5.4,2.1,Iris-virginica 142 | 6.7,3.1,5.6,2.4,Iris-virginica 143 | 6.9,3.1,5.1,2.3,Iris-virginica 144 | 5.8,2.7,5.1,1.9,Iris-virginica 145 | 6.8,3.2,5.9,2.3,Iris-virginica 146 | 6.7,3.3,5.7,2.5,Iris-virginica 147 | 6.7,3.0,5.2,2.3,Iris-virginica 148 | 6.3,2.5,5.0,1.9,Iris-virginica 149 | 6.5,3.0,5.2,2.0,Iris-virginica 150 | 6.2,3.4,5.4,2.3,Iris-virginica 151 | 5.9,3.0,5.1,1.8,Iris-virginica -------------------------------------------------------------------------------- /anonymizer/anonymDF.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Sun Nov 01 19:28:44 2015 4 | 5 | @author: Alexis 6 | """ 7 | 8 | import pandas as pd 9 | 10 | from anonymizer.anonymity import (get_k, get_anonymities, less_anonym_groups, 11 | all_local_aggregation) 12 | from anonymizer.diversity import (get_l, get_diversities, diversity_distribution, 13 | less_diverse_groups) 14 | 15 | 16 | class AnonymDataFrame(object): 17 | 18 | def __init__(self, df, var_identifiantes, var_sensibles=None, 19 | unknown=None): 20 | assert isinstance(df, pd.DataFrame) 21 | self.df = df 22 | self.transformation = None 23 | self.anonymized_df = None 24 | 25 | columns = df.columns 26 | for var in [var_identifiantes]: 27 | assert isinstance(var, list) 28 | if not all([x in columns for x in var_identifiantes]): 29 | not_in_columns = [x for x in var_identifiantes if x not in columns] 30 | raise Exception(not_in_columns, ' not in df.columns') 31 | 32 | if var_sensibles is not None: 33 | assert isinstance(var_sensibles, str) 34 | assert var_sensibles in columns 35 | assert var_sensibles not in var_identifiantes 36 | 37 | self.identifiant = var_identifiantes 38 | self.sensible = var_sensibles 39 | self.unknown = unknown 40 | 41 | def copy(self): 42 | copy = AnonymDataFrame(self.df, 43 | self.identifiant, 44 | self.sensible, 45 | self.unknown 46 | ) 47 | copy.anonymized_df = self.anonymized_df 48 | copy.transformation = self.transformation 49 | return copy 50 | 51 | def list_valeurs_identifiantes(self): 52 | for var in self.identifiant: 53 | print(self.df[var].unique()) 54 | 55 | def get_k(self): 56 | return get_k(self.df, self.identifiant, self.unknown) 57 | 58 | def get_final_k(self): 59 | return get_k(self.anonymized_df, self.identifiant, self.unknown) 60 | 61 | def get_anonymities(self, force_unknown=None): 62 | if force_unknown is None: 63 | force_unknown = self.unknown 64 | return get_anonymities(self.df, self.identifiant, force_unknown) 65 | 66 | def less_anonym_groups(self, force_unknown=None): 67 | if force_unknown is None: 68 | force_unknown = self.unknown 69 | return less_anonym_groups(self.df, self.identifiant, force_unknown) 70 | 71 | def final_less_anonym_groups(self, force_unknown=None): 72 | if force_unknown is None: 73 | force_unknown = self.unknown 74 | return less_anonym_groups(self.anonymized_df, self.identifiant, force_unknown) 75 | 76 | def get_l(self): 77 | return get_l(self.df, self.identifiant, self.sensible) 78 | 79 | def get_diversities(self): 80 | return get_diversities(self.df, self.identifiant, self.sensible) 81 | 82 | def diversity_distribution(self): 83 | return diversity_distribution(self.df, self.identifiant, self.sensible) 84 | 85 | def less_diverse_groups(self): 86 | return less_diverse_groups(self.df, self.identifiant, self.sensible) 87 | 88 | def transform(self, transformation): 89 | ''' 90 | return a new AnonymDataFrame with a transformed self.df 91 | df is modified by application of transformation 92 | - transformation can be 93 | - a list of tuple with: 94 | - first element is the name the column 95 | - second element is the transformation 96 | Note: it has no effect here but transformation are applied 97 | in the self.variables order or in the order of list when 98 | transformation is a list 99 | ''' 100 | self.transformation = transformation 101 | assert isinstance(transformation, list) 102 | assert all([len(x) == 2 for x in transformation]) 103 | assert all([x[0] in self.df.columns for x in transformation]) 104 | anonymized_df = self.df.copy() 105 | for colname, transfo in transformation: 106 | anonymized_df[colname] = transfo(anonymized_df[colname]) 107 | 108 | self.anonymized_df = anonymized_df 109 | return self.copy() 110 | 111 | def local_transform(self, transformation, k, force_unknown=None): 112 | ''' 113 | return a new AnonymDataFrame with a transformed self.df 114 | df is modified by application of transformation 115 | 116 | The main difference with transformation is that here 117 | tranformation are applied by each group only if needed. 118 | 119 | - transformation: can be 120 | - a list of tuple with: 121 | - first element is the name the column 122 | - second element is the transformation 123 | - no dict here as order counts 124 | 125 | - k: un entier est le k-anonymat recherché 126 | 127 | Note: it does have effect here but transformation are applied 128 | in the self.variables order or in the order of list when 129 | transformation is a list 130 | 131 | ''' 132 | 133 | if force_unknown is None: 134 | force_unknown = self.unknown 135 | self.transformation = transformation 136 | assert isinstance(transformation, list) 137 | assert all([len(x) == 2 for x in transformation]) 138 | assert all([x[0] in self.df.columns for x in transformation]) 139 | variables = [x[0] for x in transformation] 140 | derniere_transfo = transformation[-1] 141 | anonymized_df = self.df.copy() 142 | 143 | if get_k(anonymized_df, variables, force_unknown) >= k: 144 | self.anonymized_df = anonymized_df 145 | return self.copy() 146 | 147 | if len(transformation) == 1: 148 | colname = transformation[0][0] 149 | transfo = transformation[0][1] 150 | anonymized_df[colname] = transfo(anonymized_df[colname]) 151 | self.anonymized_df = anonymized_df 152 | return self.copy() 153 | 154 | if get_k(anonymized_df, variables[:-1], force_unknown) < k: 155 | anonymized_df = self.local_transform(transformation[:-1], k).anonymized_df 156 | # on a une table k-anonymisée lorsqu'elle est restreinte aux 157 | # len(variables) - 1 premières variables 158 | 159 | # on applique l'aggrégation locale d'une variable par groupe 160 | grp = anonymized_df.groupby(variables[:-1]) 161 | fonction = derniere_transfo[1] 162 | variable = derniere_transfo[0] 163 | anonymized_df[variable] = grp[variable].apply(fonction) 164 | #assert get_k(anonymized_df, variables, force_unknown) >= k 165 | 166 | self.anonymized_df = anonymized_df 167 | return self.copy() 168 | -------------------------------------------------------------------------------- /anonymizer/transformations.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Wed Jan 20 14:40:36 2016 4 | 5 | @author: Alexis Eidelman 6 | 7 | 8 | List of transformation to aggregate a column 9 | There is four parts in that file. 10 | 1 - deals with numeral values 11 | 2 - deals with string values 12 | 3 - deals with date values 13 | 4 - deals with special function, not always aggregating 14 | """ 15 | 16 | import numpy as np 17 | import pandas as pd 18 | 19 | ### 1 - numbers 20 | def num_drop(x): 21 | return x.mean() 22 | 23 | ### 2 - string 24 | def str_drop(x): 25 | return 'dropped' 26 | 27 | def first_letters(x, k=1): 28 | return x.str[:k] 29 | 30 | def last_letters(x, k=1): 31 | return x.str[k:] 32 | 33 | ### 3 - date 34 | def date_drop(x): 35 | return x.min() 36 | 37 | def period_by_hours(x, separation): 38 | ''' aggrege le x par intervale d'heure. 39 | Le calcul pourrait être simple si on interdisait 40 | le chevauchement de jour. 41 | ''' 42 | print(separation) 43 | assert isinstance(separation, list) 44 | assert all([sep < 24 for sep in separation]) 45 | separation.sort() 46 | 47 | if 0 in separation: 48 | separation.append(24) 49 | hour_categ = pd.cut(x.dt.hour, separation, right=False) 50 | date_categ = x.dt.date 51 | return date_categ.astype(str) + ' ' + hour_categ.astype(str) 52 | else: 53 | hour = x.dt.hour 54 | hour_categ = pd.cut(hour, separation, right=False).astype(str) 55 | night_categ = '[' + str(separation[-1]) + ', ' + str(separation[0]) + ')' 56 | hour_categ[(hour < separation[0]) | (hour >= separation[-1])] = night_categ 57 | assert hour_categ.nunique(dropna=False) == len(separation) 58 | date_categ = x.dt.date.astype(str) 59 | # décalage d'un jour pour les premières heures 60 | decale = x.dt.date[x.dt.hour < separation[1]] + pd.DateOffset(days=-1) 61 | date_categ[x.dt.hour < separation[1]] = decale.astype(str) 62 | assert all(date_categ.str.len() == 10) 63 | return date_categ + ' ' + hour_categ 64 | 65 | 66 | ### 4 - special 67 | 68 | def _name_aggregation(list_of_values): 69 | list_of_values.sort() 70 | return ' ou '.join(list_of_values) 71 | 72 | 73 | def local_aggregation(serie_init, k, method, unknown=''): 74 | ''' 75 | réalise l'aggregation locale sur une seule variable 76 | 77 | ''' 78 | assert serie_init.dtype == 'object' 79 | assert method in ['into_unknown', 'remove', 80 | 'regroup_with_smallest', 81 | 'regroup_with_biggest', 82 | 'with_closest'] 83 | 84 | serie_without_null = serie_init[serie_init != unknown] 85 | serie = serie_without_null 86 | counts = serie.value_counts() 87 | counts_to_change = counts[counts < k] 88 | index_to_change = counts_to_change.index.tolist() 89 | 90 | # si pas de groupe inférieur à k, on a fini 91 | if len(index_to_change) == 0: 92 | return serie_init 93 | 94 | if len(serie) < k: 95 | return pd.Series(unknown, index=serie_init.index) 96 | 97 | if method == 'into_unknown': 98 | # si on a que deux valeurs alors le non renseigné devient 99 | # facile à retrouver : c'est l'autre valeur 100 | # si remplace k et sur plus d'une modalité on sait que 101 | # c'est bien anonymisé. sinon, il faut faire autre chose. 102 | if counts_to_change.sum() >= k or serie_init.nunique() > 2: 103 | return serie_init.replace(index_to_change, unknown) 104 | else: 105 | return pd.Series(unknown, index=serie_init.index) 106 | 107 | if method == 'remove': 108 | return serie_init[~serie_init.isin(index_to_change)] 109 | 110 | if 'regroup' in method: 111 | # on regroupe en priorité les petits groupes entre eux 112 | # si ça ne suffit pas on va chercher un autre groupe 113 | # on cherche donc un groupe, par construction de taille supérieure 114 | # à k, avec qui regrouper. 115 | if counts_to_change.sum() >= k: 116 | pass # rien à faire 117 | 118 | if counts_to_change.sum() < k: 119 | clients_pour_regrouper = counts[counts >= k] 120 | if len(clients_pour_regrouper) == 0: 121 | # ne doit pas se produire parce que ça veut dire 122 | # qu'on a moins de k petit et pas de gros, ça veut 123 | # dire qu'on a moins de k lignes 124 | raise Exception('Ca ne doit pas arriver') 125 | # on cherche un groupe, par construction de taille supérieure 126 | # à k, avec qui regrouper. 127 | # on recommander plutôt de ne pas déteriorer la plus grande modalité 128 | # et de prendre la plus petite possible 129 | if method == 'regroup_with_smallest': 130 | pour_regrouper = clients_pour_regrouper.index[-1] 131 | if method == 'regroup_with_biggest': 132 | pour_regrouper = clients_pour_regrouper.index[0] 133 | 134 | index_to_change.append(pour_regrouper) 135 | 136 | # le nom de la nouvelle modalité 137 | new_name = _name_aggregation(index_to_change) 138 | return serie_init.replace(index_to_change, new_name) 139 | 140 | if method == 'with_closest': 141 | # on regroupe les nombres qui ne sont pas k-anonymisés avec 142 | # la valeur la plus proche 143 | df = pd.DataFrame(counts) 144 | df.columns = ['count'] 145 | df['name'] = df.index 146 | 147 | def _to_float(str_expression): 148 | if ' ou ' in str_expression: 149 | splittage = str_expression.split(' ou ') 150 | barycentre = np.mean([float(k) for k in splittage]) 151 | return barycentre 152 | else: 153 | return float(str_expression) 154 | 155 | df['value'] = df['name'].apply(_to_float) 156 | 157 | modifications = [] 158 | while df['count'].min() < k: 159 | valeur_a_remplacer = df.iloc[-1,:] 160 | distance = (df['value'] - valeur_a_remplacer['value'])**2 161 | idxmin = distance[distance > 0].idxmin() 162 | 163 | pour_regrouper = [valeur_a_remplacer['name'], idxmin] 164 | 165 | #calcul de la nouvelle modalité 166 | new_name = _name_aggregation(pour_regrouper) 167 | new_count = df.loc[pour_regrouper]['count'].sum() 168 | # introduit un biais quand on agregre deux valeurs 169 | # puis une troisième, on tire vers la troisième 170 | new_value = df.loc[pour_regrouper]['value'].mean() 171 | df.loc[new_name] = [new_count, new_name, new_value] 172 | df.drop(pour_regrouper, inplace=True) 173 | df.sort_values('count', ascending=False, 174 | inplace=True) 175 | 176 | modifications.append((pour_regrouper, new_name)) 177 | 178 | for modification in modifications: 179 | serie_init.replace(modification[0], modification[1], inplace=True) 180 | return serie_init 181 | -------------------------------------------------------------------------------- /docs/pycco.css: -------------------------------------------------------------------------------- 1 | /*--------------------- Layout and Typography ----------------------------*/ 2 | body { 3 | font-family: 'Palatino Linotype', 'Book Antiqua', Palatino, FreeSerif, serif; 4 | font-size: 16px; 5 | line-height: 24px; 6 | color: #252519; 7 | margin: 0; padding: 0; 8 | background: #f5f5ff; 9 | } 10 | a { 11 | color: #261a3b; 12 | } 13 | a:visited { 14 | color: #261a3b; 15 | } 16 | p { 17 | margin: 0 0 15px 0; 18 | } 19 | h1, h2, h3, h4, h5, h6 { 20 | margin: 40px 0 15px 0; 21 | } 22 | h2, h3, h4, h5, h6 { 23 | margin-top: 0; 24 | } 25 | #container { 26 | background: white; 27 | } 28 | #container, div.section { 29 | position: relative; 30 | } 31 | #background { 32 | position: absolute; 33 | top: 0; left: 580px; right: 0; bottom: 0; 34 | background: #f5f5ff; 35 | border-left: 1px solid #e5e5ee; 36 | z-index: 0; 37 | } 38 | #jump_to, #jump_page { 39 | background: white; 40 | -webkit-box-shadow: 0 0 25px #777; -moz-box-shadow: 0 0 25px #777; 41 | -webkit-border-bottom-left-radius: 5px; -moz-border-radius-bottomleft: 5px; 42 | font: 10px Arial; 43 | text-transform: uppercase; 44 | cursor: pointer; 45 | text-align: right; 46 | } 47 | #jump_to, #jump_wrapper { 48 | position: fixed; 49 | right: 0; top: 0; 50 | padding: 5px 10px; 51 | } 52 | #jump_wrapper { 53 | padding: 0; 54 | display: none; 55 | } 56 | #jump_to:hover #jump_wrapper { 57 | display: block; 58 | } 59 | #jump_page { 60 | padding: 5px 0 3px; 61 | margin: 0 0 25px 25px; 62 | } 63 | #jump_page .source { 64 | display: block; 65 | padding: 5px 10px; 66 | text-decoration: none; 67 | border-top: 1px solid #eee; 68 | } 69 | #jump_page .source:hover { 70 | background: #f5f5ff; 71 | } 72 | #jump_page .source:first-child { 73 | } 74 | div.docs { 75 | float: left; 76 | max-width: 500px; 77 | min-width: 500px; 78 | min-height: 5px; 79 | padding: 10px 25px 1px 50px; 80 | vertical-align: top; 81 | text-align: left; 82 | } 83 | .docs pre { 84 | margin: 15px 0 15px; 85 | padding-left: 15px; 86 | } 87 | .docs p tt, .docs p code { 88 | background: #f8f8ff; 89 | border: 1px solid #dedede; 90 | font-size: 12px; 91 | padding: 0 0.2em; 92 | } 93 | .octowrap { 94 | position: relative; 95 | } 96 | .octothorpe { 97 | font: 12px Arial; 98 | text-decoration: none; 99 | color: #454545; 100 | position: absolute; 101 | top: 3px; left: -20px; 102 | padding: 1px 2px; 103 | opacity: 0; 104 | -webkit-transition: opacity 0.2s linear; 105 | } 106 | div.docs:hover .octothorpe { 107 | opacity: 1; 108 | } 109 | div.code { 110 | margin-left: 580px; 111 | padding: 14px 15px 16px 50px; 112 | vertical-align: top; 113 | } 114 | .code pre, .docs p code { 115 | font-size: 12px; 116 | } 117 | pre, tt, code { 118 | line-height: 18px; 119 | font-family: Monaco, Consolas, "Lucida Console", monospace; 120 | margin: 0; padding: 0; 121 | } 122 | div.clearall { 123 | clear: both; 124 | } 125 | 126 | 127 | /*---------------------- Syntax Highlighting -----------------------------*/ 128 | td.linenos { background-color: #f0f0f0; padding-right: 10px; } 129 | span.lineno { background-color: #f0f0f0; padding: 0 5px 0 5px; } 130 | body .hll { background-color: #ffffcc } 131 | body .c { color: #408080; font-style: italic } /* Comment */ 132 | body .err { border: 1px solid #FF0000 } /* Error */ 133 | body .k { color: #954121 } /* Keyword */ 134 | body .o { color: #666666 } /* Operator */ 135 | body .cm { color: #408080; font-style: italic } /* Comment.Multiline */ 136 | body .cp { color: #BC7A00 } /* Comment.Preproc */ 137 | body .c1 { color: #408080; font-style: italic } /* Comment.Single */ 138 | body .cs { color: #408080; font-style: italic } /* Comment.Special */ 139 | body .gd { color: #A00000 } /* Generic.Deleted */ 140 | body .ge { font-style: italic } /* Generic.Emph */ 141 | body .gr { color: #FF0000 } /* Generic.Error */ 142 | body .gh { color: #000080; font-weight: bold } /* Generic.Heading */ 143 | body .gi { color: #00A000 } /* Generic.Inserted */ 144 | body .go { color: #808080 } /* Generic.Output */ 145 | body .gp { color: #000080; font-weight: bold } /* Generic.Prompt */ 146 | body .gs { font-weight: bold } /* Generic.Strong */ 147 | body .gu { color: #800080; font-weight: bold } /* Generic.Subheading */ 148 | body .gt { color: #0040D0 } /* Generic.Traceback */ 149 | body .kc { color: #954121 } /* Keyword.Constant */ 150 | body .kd { color: #954121; font-weight: bold } /* Keyword.Declaration */ 151 | body .kn { color: #954121; font-weight: bold } /* Keyword.Namespace */ 152 | body .kp { color: #954121 } /* Keyword.Pseudo */ 153 | body .kr { color: #954121; font-weight: bold } /* Keyword.Reserved */ 154 | body .kt { color: #B00040 } /* Keyword.Type */ 155 | body .m { color: #666666 } /* Literal.Number */ 156 | body .s { color: #219161 } /* Literal.String */ 157 | body .na { color: #7D9029 } /* Name.Attribute */ 158 | body .nb { color: #954121 } /* Name.Builtin */ 159 | body .nc { color: #0000FF; font-weight: bold } /* Name.Class */ 160 | body .no { color: #880000 } /* Name.Constant */ 161 | body .nd { color: #AA22FF } /* Name.Decorator */ 162 | body .ni { color: #999999; font-weight: bold } /* Name.Entity */ 163 | body .ne { color: #D2413A; font-weight: bold } /* Name.Exception */ 164 | body .nf { color: #0000FF } /* Name.Function */ 165 | body .nl { color: #A0A000 } /* Name.Label */ 166 | body .nn { color: #0000FF; font-weight: bold } /* Name.Namespace */ 167 | body .nt { color: #954121; font-weight: bold } /* Name.Tag */ 168 | body .nv { color: #19469D } /* Name.Variable */ 169 | body .ow { color: #AA22FF; font-weight: bold } /* Operator.Word */ 170 | body .w { color: #bbbbbb } /* Text.Whitespace */ 171 | body .mf { color: #666666 } /* Literal.Number.Float */ 172 | body .mh { color: #666666 } /* Literal.Number.Hex */ 173 | body .mi { color: #666666 } /* Literal.Number.Integer */ 174 | body .mo { color: #666666 } /* Literal.Number.Oct */ 175 | body .sb { color: #219161 } /* Literal.String.Backtick */ 176 | body .sc { color: #219161 } /* Literal.String.Char */ 177 | body .sd { color: #219161; font-style: italic } /* Literal.String.Doc */ 178 | body .s2 { color: #219161 } /* Literal.String.Double */ 179 | body .se { color: #BB6622; font-weight: bold } /* Literal.String.Escape */ 180 | body .sh { color: #219161 } /* Literal.String.Heredoc */ 181 | body .si { color: #BB6688; font-weight: bold } /* Literal.String.Interpol */ 182 | body .sx { color: #954121 } /* Literal.String.Other */ 183 | body .sr { color: #BB6688 } /* Literal.String.Regex */ 184 | body .s1 { color: #219161 } /* Literal.String.Single */ 185 | body .ss { color: #19469D } /* Literal.String.Symbol */ 186 | body .bp { color: #954121 } /* Name.Builtin.Pseudo */ 187 | body .vc { color: #19469D } /* Name.Variable.Class */ 188 | body .vg { color: #19469D } /* Name.Variable.Global */ 189 | body .vi { color: #19469D } /* Name.Variable.Instance */ 190 | body .il { color: #666666 } /* Literal.Number.Integer.Long */ 191 | -------------------------------------------------------------------------------- /anonymizer/docs/pycco.css: -------------------------------------------------------------------------------- 1 | /*--------------------- Layout and Typography ----------------------------*/ 2 | body { 3 | font-family: 'Palatino Linotype', 'Book Antiqua', Palatino, FreeSerif, serif; 4 | font-size: 16px; 5 | line-height: 24px; 6 | color: #252519; 7 | margin: 0; padding: 0; 8 | background: #f5f5ff; 9 | } 10 | a { 11 | color: #261a3b; 12 | } 13 | a:visited { 14 | color: #261a3b; 15 | } 16 | p { 17 | margin: 0 0 15px 0; 18 | } 19 | h1, h2, h3, h4, h5, h6 { 20 | margin: 40px 0 15px 0; 21 | } 22 | h2, h3, h4, h5, h6 { 23 | margin-top: 0; 24 | } 25 | #container { 26 | background: white; 27 | } 28 | #container, div.section { 29 | position: relative; 30 | } 31 | #background { 32 | position: absolute; 33 | top: 0; left: 580px; right: 0; bottom: 0; 34 | background: #f5f5ff; 35 | border-left: 1px solid #e5e5ee; 36 | z-index: 0; 37 | } 38 | #jump_to, #jump_page { 39 | background: white; 40 | -webkit-box-shadow: 0 0 25px #777; -moz-box-shadow: 0 0 25px #777; 41 | -webkit-border-bottom-left-radius: 5px; -moz-border-radius-bottomleft: 5px; 42 | font: 10px Arial; 43 | text-transform: uppercase; 44 | cursor: pointer; 45 | text-align: right; 46 | } 47 | #jump_to, #jump_wrapper { 48 | position: fixed; 49 | right: 0; top: 0; 50 | padding: 5px 10px; 51 | } 52 | #jump_wrapper { 53 | padding: 0; 54 | display: none; 55 | } 56 | #jump_to:hover #jump_wrapper { 57 | display: block; 58 | } 59 | #jump_page { 60 | padding: 5px 0 3px; 61 | margin: 0 0 25px 25px; 62 | } 63 | #jump_page .source { 64 | display: block; 65 | padding: 5px 10px; 66 | text-decoration: none; 67 | border-top: 1px solid #eee; 68 | } 69 | #jump_page .source:hover { 70 | background: #f5f5ff; 71 | } 72 | #jump_page .source:first-child { 73 | } 74 | div.docs { 75 | float: left; 76 | max-width: 500px; 77 | min-width: 500px; 78 | min-height: 5px; 79 | padding: 10px 25px 1px 50px; 80 | vertical-align: top; 81 | text-align: left; 82 | } 83 | .docs pre { 84 | margin: 15px 0 15px; 85 | padding-left: 15px; 86 | } 87 | .docs p tt, .docs p code { 88 | background: #f8f8ff; 89 | border: 1px solid #dedede; 90 | font-size: 12px; 91 | padding: 0 0.2em; 92 | } 93 | .octowrap { 94 | position: relative; 95 | } 96 | .octothorpe { 97 | font: 12px Arial; 98 | text-decoration: none; 99 | color: #454545; 100 | position: absolute; 101 | top: 3px; left: -20px; 102 | padding: 1px 2px; 103 | opacity: 0; 104 | -webkit-transition: opacity 0.2s linear; 105 | } 106 | div.docs:hover .octothorpe { 107 | opacity: 1; 108 | } 109 | div.code { 110 | margin-left: 580px; 111 | padding: 14px 15px 16px 50px; 112 | vertical-align: top; 113 | } 114 | .code pre, .docs p code { 115 | font-size: 12px; 116 | } 117 | pre, tt, code { 118 | line-height: 18px; 119 | font-family: Monaco, Consolas, "Lucida Console", monospace; 120 | margin: 0; padding: 0; 121 | } 122 | div.clearall { 123 | clear: both; 124 | } 125 | 126 | 127 | /*---------------------- Syntax Highlighting -----------------------------*/ 128 | td.linenos { background-color: #f0f0f0; padding-right: 10px; } 129 | span.lineno { background-color: #f0f0f0; padding: 0 5px 0 5px; } 130 | body .hll { background-color: #ffffcc } 131 | body .c { color: #408080; font-style: italic } /* Comment */ 132 | body .err { border: 1px solid #FF0000 } /* Error */ 133 | body .k { color: #954121 } /* Keyword */ 134 | body .o { color: #666666 } /* Operator */ 135 | body .cm { color: #408080; font-style: italic } /* Comment.Multiline */ 136 | body .cp { color: #BC7A00 } /* Comment.Preproc */ 137 | body .c1 { color: #408080; font-style: italic } /* Comment.Single */ 138 | body .cs { color: #408080; font-style: italic } /* Comment.Special */ 139 | body .gd { color: #A00000 } /* Generic.Deleted */ 140 | body .ge { font-style: italic } /* Generic.Emph */ 141 | body .gr { color: #FF0000 } /* Generic.Error */ 142 | body .gh { color: #000080; font-weight: bold } /* Generic.Heading */ 143 | body .gi { color: #00A000 } /* Generic.Inserted */ 144 | body .go { color: #808080 } /* Generic.Output */ 145 | body .gp { color: #000080; font-weight: bold } /* Generic.Prompt */ 146 | body .gs { font-weight: bold } /* Generic.Strong */ 147 | body .gu { color: #800080; font-weight: bold } /* Generic.Subheading */ 148 | body .gt { color: #0040D0 } /* Generic.Traceback */ 149 | body .kc { color: #954121 } /* Keyword.Constant */ 150 | body .kd { color: #954121; font-weight: bold } /* Keyword.Declaration */ 151 | body .kn { color: #954121; font-weight: bold } /* Keyword.Namespace */ 152 | body .kp { color: #954121 } /* Keyword.Pseudo */ 153 | body .kr { color: #954121; font-weight: bold } /* Keyword.Reserved */ 154 | body .kt { color: #B00040 } /* Keyword.Type */ 155 | body .m { color: #666666 } /* Literal.Number */ 156 | body .s { color: #219161 } /* Literal.String */ 157 | body .na { color: #7D9029 } /* Name.Attribute */ 158 | body .nb { color: #954121 } /* Name.Builtin */ 159 | body .nc { color: #0000FF; font-weight: bold } /* Name.Class */ 160 | body .no { color: #880000 } /* Name.Constant */ 161 | body .nd { color: #AA22FF } /* Name.Decorator */ 162 | body .ni { color: #999999; font-weight: bold } /* Name.Entity */ 163 | body .ne { color: #D2413A; font-weight: bold } /* Name.Exception */ 164 | body .nf { color: #0000FF } /* Name.Function */ 165 | body .nl { color: #A0A000 } /* Name.Label */ 166 | body .nn { color: #0000FF; font-weight: bold } /* Name.Namespace */ 167 | body .nt { color: #954121; font-weight: bold } /* Name.Tag */ 168 | body .nv { color: #19469D } /* Name.Variable */ 169 | body .ow { color: #AA22FF; font-weight: bold } /* Operator.Word */ 170 | body .w { color: #bbbbbb } /* Text.Whitespace */ 171 | body .mf { color: #666666 } /* Literal.Number.Float */ 172 | body .mh { color: #666666 } /* Literal.Number.Hex */ 173 | body .mi { color: #666666 } /* Literal.Number.Integer */ 174 | body .mo { color: #666666 } /* Literal.Number.Oct */ 175 | body .sb { color: #219161 } /* Literal.String.Backtick */ 176 | body .sc { color: #219161 } /* Literal.String.Char */ 177 | body .sd { color: #219161; font-style: italic } /* Literal.String.Doc */ 178 | body .s2 { color: #219161 } /* Literal.String.Double */ 179 | body .se { color: #BB6622; font-weight: bold } /* Literal.String.Escape */ 180 | body .sh { color: #219161 } /* Literal.String.Heredoc */ 181 | body .si { color: #BB6688; font-weight: bold } /* Literal.String.Interpol */ 182 | body .sx { color: #954121 } /* Literal.String.Other */ 183 | body .sr { color: #BB6688 } /* Literal.String.Regex */ 184 | body .s1 { color: #219161 } /* Literal.String.Single */ 185 | body .ss { color: #19469D } /* Literal.String.Symbol */ 186 | body .bp { color: #954121 } /* Name.Builtin.Pseudo */ 187 | body .vc { color: #19469D } /* Name.Variable.Class */ 188 | body .vg { color: #19469D } /* Name.Variable.Global */ 189 | body .vi { color: #19469D } /* Name.Variable.Instance */ 190 | body .il { color: #666666 } /* Literal.Number.Integer.Long */ 191 | -------------------------------------------------------------------------------- /examples/equidés/Equidés.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "The file can be downloaded here:\n", 8 | "https://www.data.gouv.fr/fr/datasets/fichier-des-equides/\n", 9 | "or directly :\n", 10 | "https://www.data.gouv.fr/s/resources/fichier-des-equides/20141201-185229/Equides.csv\n", 11 | "\n", 12 | "Le fichier de 200 Mo contient autours de 3 millions de lignes" 13 | ] 14 | }, 15 | { 16 | "cell_type": "code", 17 | "execution_count": 1, 18 | "metadata": { 19 | "collapsed": false 20 | }, 21 | "outputs": [], 22 | "source": [ 23 | "import csv\n", 24 | "import numpy as np\n", 25 | "import pandas as pd\n", 26 | "import matplotlib\n", 27 | "import matplotlib.pyplot as plt\n", 28 | "\n", 29 | "from anonymizer.anonymity import (get_k, get_anonymities,\n", 30 | " less_anonym_groups,\n", 31 | " _remove_unknown)\n", 32 | "from anonymizer.diversity import (get_l,\n", 33 | " get_diversities,\n", 34 | " diversity_distribution,\n", 35 | " less_diverse_groups\n", 36 | " )\n", 37 | "from anonymizer.transformations import (first_letters,\n", 38 | " last_letters,\n", 39 | " local_aggregation)\n", 40 | "from anonymizer.transformations import str_drop\n", 41 | "from anonymizer.anonymDF import AnonymDataFrame\n", 42 | "\n", 43 | "from anonymizer.config_anonymizer import config\n", 44 | "import os\n", 45 | "import io" 46 | ] 47 | }, 48 | { 49 | "cell_type": "code", 50 | "execution_count": 2, 51 | "metadata": { 52 | "collapsed": false 53 | }, 54 | "outputs": [], 55 | "source": [ 56 | "path_data = config['PATH']['EQUIDES']\n", 57 | "nbre_lignes = 50000\n", 58 | "equides = pd.read_csv(path_data, sep = \";\", nrows = nbre_lignes, encoding = \"ISO-8859-1\", header=None, low_memory = False)" 59 | ] 60 | }, 61 | { 62 | "cell_type": "code", 63 | "execution_count": 3, 64 | "metadata": { 65 | "collapsed": false 66 | }, 67 | "outputs": [], 68 | "source": [ 69 | "nom_de_colonnes = ['Race',\n", 70 | " 'Sexe',\n", 71 | " 'Robe',\n", 72 | " 'Date de naissance',\n", 73 | " 'Pays de naissance',\n", 74 | " 'Nom',\n", 75 | " 'Destiné à la consommation humaine',\n", 76 | " 'Date de mort']\n", 77 | "equides.columns = nom_de_colonnes\n", 78 | "\n", 79 | "\n", 80 | "# On supprime la date de mort puisque cela nous fournirait un indice sur l'âge du cheval,\n", 81 | "# qu'il faudrait veiller à anonymiser.\n", 82 | "\n", 83 | "variables_supprimees = ['Date de mort', 'Destiné à la consommation humaine']\n", 84 | "equides = equides.drop(variables_supprimees,1)\n", 85 | "\n", 86 | "# La variable \"date de naissance\" doit être recodée. On choisit de ne garder que l'année.\n", 87 | "equides['Date de naissance'] = last_letters(equides['Date de naissance'],6)\n", 88 | "\n", 89 | "# On remplace les modalités vides ou non renseignées par des \"non renseigné\"\n", 90 | "equides = equides.fillna('non renseigné')\n", 91 | "equides = equides.applymap(lambda x: x.strip())\n", 92 | "equides.replace('', 'non renseigné', inplace=True)" 93 | ] 94 | }, 95 | { 96 | "cell_type": "code", 97 | "execution_count": 4, 98 | "metadata": { 99 | "collapsed": false 100 | }, 101 | "outputs": [ 102 | { 103 | "name": "stdout", 104 | "output_type": "stream", 105 | "text": [ 106 | "inconnu or. inconnue\n", 107 | "inconnu race inconnue\n", 108 | "anglo-arabe *anglo-arabe*\n", 109 | "anglo-arabe anglo-arabe\n", 110 | "welsh welsh cob\n", 111 | "welsh welsh pony\n", 112 | "welsh welsh type cob\n", 113 | "welsh welsh mountain\n", 114 | "welsh welsh\n", 115 | "aa compl. *aa compl.*\n" 116 | ] 117 | }, 118 | { 119 | "data": { 120 | "text/plain": [ 121 | "78" 122 | ] 123 | }, 124 | "execution_count": 4, 125 | "metadata": {}, 126 | "output_type": "execute_result" 127 | } 128 | ], 129 | "source": [ 130 | "# On convertit tous les noms de races en minuscules afin de mieux pouvoir uniformiser\n", 131 | "# et on normalise afin de n'obtenir plus qu'une modalité inconnu, anglo-arabe, weslh ou aa compl.\n", 132 | "\n", 133 | "equides['Race'] = equides['Race'].str.lower()\n", 134 | "liste_races = equides['Race'].unique().tolist()\n", 135 | "\n", 136 | "for word in ['inconnu', 'anglo-arabe', 'welsh', 'aa compl.']:\n", 137 | " for race in liste_races :\n", 138 | " if word in race:\n", 139 | " print(word, race)\n", 140 | " equides['Race'] = equides['Race'].replace(race, word)\n", 141 | "\n", 142 | "liste_races = equides['Race'].unique().tolist()\n", 143 | "equides.replace('inconnu', 'non renseigné', inplace=True)\n", 144 | "len(liste_races)" 145 | ] 146 | }, 147 | { 148 | "cell_type": "code", 149 | "execution_count": 87, 150 | "metadata": { 151 | "collapsed": true 152 | }, 153 | "outputs": [], 154 | "source": [ 155 | "# ## II. Anonymisation \n", 156 | "\n", 157 | "# On définit les variables à anonymiser\n", 158 | "\n", 159 | "ordre_aggregation = ['Race',\n", 160 | " 'Sexe',\n", 161 | " 'Robe',\n", 162 | " 'Pays de naissance',\n", 163 | " 'Date de naissance']" 164 | ] 165 | }, 166 | { 167 | "cell_type": "code", 168 | "execution_count": 88, 169 | "metadata": { 170 | "collapsed": false 171 | }, 172 | "outputs": [], 173 | "source": [ 174 | "Equides = AnonymDataFrame(equides, ordre_aggregation, unknown='non renseigné')" 175 | ] 176 | }, 177 | { 178 | "cell_type": "code", 179 | "execution_count": 80, 180 | "metadata": { 181 | "collapsed": false 182 | }, 183 | "outputs": [], 184 | "source": [ 185 | "def aggregation_serie(x):\n", 186 | " return(local_aggregation(x, 5, 'regroup_with_smallest', 'non renseigné'))\n", 187 | "method_anonymisation = [(name, aggregation_serie) for name in ordre_aggregation[:-1]]\n", 188 | "\n", 189 | "def aggregation_year(x):\n", 190 | " return(local_aggregation(x, 5, 'with_closest', 'non renseigné'))\n", 191 | "method_anonymisation += [('Date de naissance', aggregation_year)]" 192 | ] 193 | }, 194 | { 195 | "cell_type": "code", 196 | "execution_count": 82, 197 | "metadata": { 198 | "collapsed": false 199 | }, 200 | "outputs": [ 201 | { 202 | "data": { 203 | "text/plain": [ 204 | "" 205 | ] 206 | }, 207 | "execution_count": 82, 208 | "metadata": {}, 209 | "output_type": "execute_result" 210 | } 211 | ], 212 | "source": [ 213 | "Equides.local_transform(method_anonymisation, 5)" 214 | ] 215 | }, 216 | { 217 | "cell_type": "code", 218 | "execution_count": 83, 219 | "metadata": { 220 | "collapsed": false 221 | }, 222 | "outputs": [], 223 | "source": [ 224 | "Equides.df = Equides.anonymized_df" 225 | ] 226 | }, 227 | { 228 | "cell_type": "code", 229 | "execution_count": 84, 230 | "metadata": { 231 | "collapsed": false 232 | }, 233 | "outputs": [ 234 | { 235 | "data": { 236 | "text/plain": [ 237 | "5" 238 | ] 239 | }, 240 | "execution_count": 84, 241 | "metadata": {}, 242 | "output_type": "execute_result" 243 | } 244 | ], 245 | "source": [ 246 | "Equides.get_k()" 247 | ] 248 | }, 249 | { 250 | "cell_type": "code", 251 | "execution_count": 85, 252 | "metadata": { 253 | "collapsed": false 254 | }, 255 | "outputs": [], 256 | "source": [ 257 | "less = Equides.less_anonym_groups()" 258 | ] 259 | }, 260 | { 261 | "cell_type": "code", 262 | "execution_count": 86, 263 | "metadata": { 264 | "collapsed": false 265 | }, 266 | "outputs": [ 267 | { 268 | "data": { 269 | "text/html": [ 270 | "
\n", 271 | "\n", 272 | " \n", 273 | " \n", 274 | " \n", 275 | " \n", 276 | " \n", 277 | " \n", 278 | " \n", 279 | " \n", 280 | " \n", 281 | " \n", 282 | " \n", 283 | " \n", 284 | " \n", 285 | " \n", 286 | " \n", 287 | " \n", 288 | " \n", 289 | " \n", 290 | " \n", 291 | " \n", 292 | " \n", 293 | " \n", 294 | " \n", 295 | " \n", 296 | " \n", 297 | " \n", 298 | " \n", 299 | " \n", 300 | " \n", 301 | " \n", 302 | " \n", 303 | " \n", 304 | " \n", 305 | " \n", 306 | " \n", 307 | " \n", 308 | " \n", 309 | " \n", 310 | " \n", 311 | " \n", 312 | " \n", 313 | " \n", 314 | " \n", 315 | " \n", 316 | " \n", 317 | " \n", 318 | " \n", 319 | " \n", 320 | " \n", 321 | " \n", 322 | " \n", 323 | " \n", 324 | " \n", 325 | " \n", 326 | " \n", 327 | " \n", 328 | " \n", 329 | " \n", 330 | "
RaceSexeRobeDate de naissancePays de naissanceNom
3475anglo-arabeFBAI1985 ou 1988 ou 1989 ou 1990ITALIERIGHEL
30049anglo-arabeFBAI1985 ou 1988 ou 1989 ou 1990ITALIEPALMA DE FLORINAS
33913anglo-arabeFBAI1985 ou 1988 ou 1989 ou 1990ITALIEPAMPHILA DE MORES
37688anglo-arabeFBAI1985 ou 1988 ou 1989 ou 1990ITALIEMALOA
38598anglo-arabeFBAI1985 ou 1988 ou 1989 ou 1990ITALIEQUERIDA PERRA
\n", 331 | "
" 332 | ], 333 | "text/plain": [ 334 | " Race Sexe Robe Date de naissance Pays de naissance \\\n", 335 | "3475 anglo-arabe F BAI 1985 ou 1988 ou 1989 ou 1990 ITALIE \n", 336 | "30049 anglo-arabe F BAI 1985 ou 1988 ou 1989 ou 1990 ITALIE \n", 337 | "33913 anglo-arabe F BAI 1985 ou 1988 ou 1989 ou 1990 ITALIE \n", 338 | "37688 anglo-arabe F BAI 1985 ou 1988 ou 1989 ou 1990 ITALIE \n", 339 | "38598 anglo-arabe F BAI 1985 ou 1988 ou 1989 ou 1990 ITALIE \n", 340 | "\n", 341 | " Nom \n", 342 | "3475 RIGHEL \n", 343 | "30049 PALMA DE FLORINAS \n", 344 | "33913 PAMPHILA DE MORES \n", 345 | "37688 MALOA \n", 346 | "38598 QUERIDA PERRA " 347 | ] 348 | }, 349 | "execution_count": 86, 350 | "metadata": {}, 351 | "output_type": "execute_result" 352 | } 353 | ], 354 | "source": [ 355 | "less[0]" 356 | ] 357 | } 358 | ], 359 | "metadata": { 360 | "anaconda-cloud": {}, 361 | "kernelspec": { 362 | "display_name": "Python [Root]", 363 | "language": "python", 364 | "name": "Python [Root]" 365 | }, 366 | "language_info": { 367 | "codemirror_mode": { 368 | "name": "ipython", 369 | "version": 3 370 | }, 371 | "file_extension": ".py", 372 | "mimetype": "text/x-python", 373 | "name": "python", 374 | "nbconvert_exporter": "python", 375 | "pygments_lexer": "ipython3", 376 | "version": "3.5.2" 377 | } 378 | }, 379 | "nbformat": 4, 380 | "nbformat_minor": 0 381 | } 382 | -------------------------------------------------------------------------------- /examples/Transparence Santé/Transformation_santé.py: -------------------------------------------------------------------------------- 1 | 2 | # coding: utf-8 3 | 4 | #!/usr/bin/env python 5 | 6 | 7 | """ 8 | A partir des fonctions du dépôt anonymizer, ce fichier va notamment vous permettre de : 9 | 10 | 1. **Importer** les données de la base Transparence Santé. 11 | 2. **Nettoyer** les variables et sélectionner celles à anonymiser 12 | 3. **Anonymiser** les données selon un procédé de K-anonymisation 13 | 4. **Compléter** avec les données INSEE afin d'en mesurer la plus-value. 14 | 15 | 16 | The file can be downloaded here: 17 | https://www.data.gouv.fr/fr/datasets/transparence-sante-1/ 18 | or directly : 19 | https://www.transparence.sante.gouv.fr/exports-etalab/exports-etalab.zip 20 | 21 | Le jeu de données contient environ 2 millions de lignes. Le fichier exports-etalab.zip contient : 22 | 23 | Le jeu de données 24 | La présentation du jeu de données 25 | La licence d’utilisation du jeu de données 26 | 27 | 28 | 29 | Le fichier INSEE pour l'enrichissement des données peut être téléchargé ici : 30 | http://www.insee.fr/fr/themes/detail.asp?reg_id=99&ref_id=equip-serv-medical-para 31 | or directly 32 | http://www.insee.fr/fr/ppp/bases-de-donnees/donnees-detaillees/equip-serv-medical-para/equip-serv-medical-para-com-2015.zip 33 | 34 | """ 35 | 36 | import csv 37 | import numpy as np 38 | import pandas as pd 39 | import matplotlib 40 | import matplotlib.pyplot as plt 41 | 42 | from import_insee import (expand_insee, nbre_modif) 43 | 44 | from anonymizer.anonymity import (get_k, get_anonymities, 45 | less_anonym_groups, 46 | all_local_aggregation, 47 | ) 48 | from anonymizer.diversity import (get_l, 49 | get_diversities, 50 | diversity_distribution, 51 | less_diverse_groups 52 | ) 53 | from anonymizer.transformations import (first_letters, 54 | last_letters) 55 | from anonymizer.transformations import str_drop 56 | from anonymizer.anonymDF import AnonymDataFrame 57 | 58 | from anonymizer.config_anonymizer import config 59 | import os 60 | import io 61 | 62 | 63 | # ## I. Nettoyage de la base de données 64 | 65 | # Importation des 50 000 premières lignes 66 | 67 | path_data = config['PATH']['TRANSPARENCE'] 68 | 69 | nbre_lignes = 50000 70 | avantages = pd.read_csv(path_data, sep = ";", nrows = nbre_lignes, low_memory = False) 71 | 72 | 73 | 74 | # === Séparation personnes physiques/morales === 75 | 76 | # On ne traite pas le cas des personnes morales 77 | 78 | 79 | code_personne_physique = ['[PRS]','[ETU]'] 80 | personnes_physiques = avantages[avantages['benef_categorie_code'].isin(code_personne_physique)] 81 | personnes_morales = avantages[~avantages['benef_categorie_code'].isin(code_personne_physique)] 82 | avantages = personnes_physiques 83 | 84 | xxx 85 | 86 | # === transformations préalables === 87 | 88 | # * On transforme les CP en indicateurs régionaux 89 | avantages['benef_dept'] = first_letters(avantages['benef_codepostal'],2) 90 | 91 | # * On supprime les CP peu orthodoxes 92 | erreur_CP = ['0', '', 'IN'] 93 | avantages.loc[avantages['benef_dept'].isin(erreur_CP), 'benef_dept'] = np.nan 94 | erreur_pays = ['[RE]','[GP]'] 95 | avantages.loc[avantages['benef_pays_code'].isin(erreur_pays), 'benef_pays_code'] = '[FR]' 96 | 97 | # * On homogénéise les valeurs manquantes ou tierces par la mention "non-renseigné" 98 | avantages = avantages.fillna('non renseigné') 99 | to_replace = ['[AUTRE]', ''] 100 | avantages.replace(to_replace, 'non renseigné', inplace=True) 101 | 102 | # * On transforme la valeur des conventions/avantages en leur équivalent décile (uniformisation) 103 | 104 | avantages['avant_montant_ttc'] = avantages['avant_montant_ttc'].astype(float) 105 | avantages['montant_décile'] = pd.qcut(avantages.avant_montant_ttc,10) 106 | 107 | # * On transforme la date (signature des avantages) en mois/année (le jour est trop identifiant) 108 | 109 | avantages['date'] = last_letters(avantages['avant_date_signature'],3) 110 | 111 | avantages['avant_nature'] = avantages['avant_nature'].str.lower() 112 | 113 | 114 | # * On supprime d'abord les variables identifiantes afin de ne garder que les variables quasi-identifiantes 115 | 116 | variables_supprimees = ['avant_convention_lie', 117 | 'identifiant_type', 118 | 'benef_qualification', 119 | 'benef_speicalite_libelle', 120 | 'ligne_rectification', 121 | 'denomination_sociale', 122 | 'benef_titre_libelle', 123 | 'benef_prenom', 124 | 'benef_nom', 125 | 'benef_adresse1', 126 | 'benef_adresse2', 127 | 'benef_adresse3', 128 | 'benef_adresse4', 129 | 'benef_identifiant_valeur', 130 | 'benef_ville', 131 | 'benef_etablissement_ville', 132 | 'categorie', 133 | 'benef_qualite_code', 134 | 'benef_codepostal', 135 | 'benef_etablissement_codepostal', 136 | 'ligne_identifiant', 137 | 'pays', 138 | 'benef_denomination_sociale', 139 | 'benef_objet_social', 140 | 'avant_date_signature', 141 | 'avant_montant_ttc', 142 | 'benef_etablissement'] 143 | 144 | avantages = avantages.drop(variables_supprimees,1) 145 | 146 | avantages['montant_décile'] = avantages['montant_décile'].astype(str) 147 | avantages['date'] = avantages['date'].astype(str) 148 | 149 | 150 | 151 | # On définit ici les variables traitées pour l'anonymisation 152 | 153 | var = avantages.columns.tolist() 154 | var.remove('ligne_type') 155 | var.remove('avant_nature') 156 | 157 | 158 | 159 | # ## II. Traitement des données brutes (sans INSEE) 160 | 161 | # On k-anonymise dès maintenant la base brute. 162 | # On définit ici k = 5 163 | 164 | ordre_aggregation = ['benef_dept', 165 | 'benef_categorie_code', 166 | 'qualite', 167 | 'benef_pays_code', 168 | 'benef_titre_code', 169 | 'benef_identifiant_type_code'] 170 | 171 | Avantages = AnonymDataFrame(avantages.copy(), ordre_aggregation, unknown='non renseigné') 172 | k = 5 173 | 174 | def aggregation_serie(x): 175 | return(local_aggregation(x, k, 'regroup_with_smallest', 'non renseigné')) 176 | 177 | def aggregation_year(x): 178 | return(local_aggregation(x, k, 'with_closest', 'non renseigné')) 179 | 180 | method_anonymisation = [(name, aggregation_serie) for name in ordre_aggregation[:-1]] + [('date', aggregation_year)] 181 | 182 | Avantages.local_transform(method_anonymisation, k) 183 | 184 | modalites_modifiees = (Avantages.anonymized_df.values != avantages.values).sum() 185 | modalites_intactes = (Avantages.anonymized_df.values == avantages.values).sum() 186 | 187 | 188 | 189 | # ## II. Chargement des données INSEE 190 | 191 | # construction d'un dictionnaire reliant les professions (INSEE) aux professions (Transparence Santé) 192 | 193 | annuaire = {'Médecin omnipraticien' : ['benef_specialite_code', '[SM54]'], 194 | 'Spécialiste en cardiologie' : ['benef_specialite_code', '[SM04]'], 195 | 'Spécialiste en dermatologie vénéréologie' : ['benef_specialite_code', '[SM15]'], 196 | 'Spécialiste en gynécologie médicale' : ['benef_specialite_code', '[SM19]'], 197 | 'Spécialiste en gynécologie obstétrique' : ['benef_specialite_code', '[SM20]'], 198 | 'Spécialiste en gastro-entérologie hépatologie' : ['benef_specialite_code', '[SM24]'], 199 | 'Spécialiste en psychiatrie' : ['benef_specialite_code', '[SM42]'], 200 | 'Spécialiste en ophtalmologie' : ['benef_specialite_code', '[SM38]'], 201 | 'Spécialiste en oto-rhino-laryngologie' : ['benef_specialite_code', '[SM39]'], 202 | 'Spécialiste en pédiatrie' : ['benef_specialite_code', '[SM40]'], 203 | 'Spécialiste en pneumologie' : ['benef_specialite_code', '[SM41]'], 204 | 'Spécialiste en radiodiagnostic et imagerie médicale' : ['benef_specialite_code', '[SM44]'], 205 | 'Spécialiste en stomatologie' : ['benef_specialite_code', '[SM50]'], 206 | 'Chirurgien dentiste' : ['qualite', 'Chirurgien-dentiste'], 207 | 'Sage-femme' : ['qualite', 'Sage-femme'], 208 | 'Infirmier' : ['qualite', 'Infirmier'], 209 | 'Masseur kinésithérapeute' : ['qualite', 'Masseur-kinésithérapeute'], 210 | 'Orthophoniste' : ['qualite', 'Orthophoniste'], 211 | 'Orthoptiste' : ['qualite', 'Orthoptiste'], 212 | 'Pédicure-podologue' : ['qualite', 'Pédicure-podologue'], 213 | 'Audio prothésiste' : ['qualite', 'Audio prothésiste'], 214 | 'Ergothérapeute' : ['qualite', 'Ergothérapeute'], 215 | 'Psychomotricien' : ['qualite', 'Psychomotricien']} 216 | 217 | 218 | # On charge les données INSEE 219 | 220 | path_data_insee = config['PATH']['INSEE'] 221 | 222 | names = pd.read_excel(path_data_insee, encoding = "ISO-8859-1", skiprows=4, skip_footer=36000).columns 223 | insee_init = pd.read_excel(path_data_insee, encoding = "ISO-8859-1", skiprows=5, headers=None, names=names) 224 | 225 | 226 | insee_init['Département'] = insee_init['Département'].astype(str) 227 | insee_init['Région 2016'] = insee_init['Région 2016'].astype(str) 228 | 229 | insee_init['Département'] = first_letters(insee_init['Département'],2) 230 | 231 | 232 | 233 | 234 | # On fusionne les départements d'Outre-mer dans une seule catégorie (trop identifiant, sinon) 235 | 236 | outremer = ['1','2','3','4','6'] 237 | insee_init.loc[insee_init['Région 2016'].isin(outremer), 'Région 2016'] = 1 238 | 239 | list_région = insee_init['Région 2016'].unique().tolist() 240 | 241 | insee = insee_init.copy() 242 | 243 | var_écartées = ['Région', 'Région 2016', 'CODGEO', 'Libellé commune ou ARM'] 244 | insee = insee.drop(var_écartées,1) 245 | 246 | 247 | 248 | # === On rajoute à la base originale les données INSEE === 249 | 250 | # avantages_total est donc constituée de la base Transparence Santé, complétée par les données INSEE 251 | 252 | g = insee.groupby('Département') 253 | 254 | expanded_insee = expand_insee(g, annuaire, avantages) 255 | 256 | expanded_insee.columns = avantages.columns.tolist() 257 | avantages_total = pd.concat([avantages, expanded_insee]).reset_index() 258 | avantages_total = avantages_total.drop('index',1) 259 | 260 | 261 | 262 | 263 | # === On anonymise (données enrichies) === 264 | 265 | 266 | Avantages_avec_insee = AnonymDataFrame(avantages_total.copy(), ordre_aggregation, unknown='non renseigné') 267 | 268 | Avantages_avec_insee.local_transform(method_anonymisation, k, force_unknown='Forcer') 269 | Avantages_avec_insee.df = Avantages_avec_insee.anonymized_df 270 | 271 | 272 | 273 | table = Avantages_avec_insee.df[Avantages_avec_insee.df['ligne_type']=='[A]'] 274 | modalites_modifiees_avec_insee = (table.values != avantages_total[avantages_total['ligne_type']=='[A]'].values).sum() 275 | modalites_intactes_avec_insee = (table.values == avantages_total[avantages_total['ligne_type']=='[A]'].values).sum() 276 | 277 | ## IV. Comparaison 278 | 279 | 280 | # === On va maintenant comparer par variables le taux de remplacement === 281 | 282 | (avantages_kanonym[var[0]] != avantages[var[0]]).sum() 283 | 284 | modif_par_var_1 = [] 285 | for variable in var : 286 | modif_par_var_1.append((avantages_kanonym[variable] != avantages[variable]).sum()) 287 | 288 | modif_par_var_2 = [] 289 | for variable in var : 290 | modif_par_var_2.append((result_insee[variable][result_insee['ligne_type']=='[A]'] != avantages_total[variable][avantages_total['ligne_type']=='[A]']).sum()) 291 | 292 | 293 | n_groups = len(var) # data to plot 294 | 295 | fig, ax = plt.subplots(figsize=(15, 6)) # create plot 296 | 297 | 298 | index = np.arange(n_groups) 299 | bar_width = 0.35 300 | opacity = 1 301 | 302 | rects1 = plt.bar(index, modif_par_var_1, bar_width, 303 | alpha=opacity, 304 | color='b', 305 | label='Séries brutes') 306 | 307 | 308 | rects2 = plt.bar(index + bar_width, modif_par_var_2 , bar_width, 309 | alpha=opacity, 310 | color='y', 311 | label='Séries avec données INSEE') 312 | 313 | plt.ylim(0, 30000) #ax.axhline(y = modalites_modifiees[0]) #ax.axhline(y = taille_données_transparence[0]) 314 | 315 | 316 | plt.xlabel('Variable anonymisée') 317 | plt.ylabel('Nombre de valeurs modifiées') 318 | plt.title('Modification de valeurs') 319 | plt.xticks(index + bar_width, var) 320 | plt.legend() 321 | 322 | plt.tight_layout() 323 | plt.show() 324 | -------------------------------------------------------------------------------- /docs/Equidés.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Equidés.py 6 | 7 | 8 | 9 |
10 |
11 |
12 |

Equidés.py

13 |
14 |
15 |
16 |
17 |
18 | # 19 |
20 | 21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 | # 31 |
32 |

!/usr/bin/env python

33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 | # 43 |
44 |

A partir des fonctions du dépôt anonymizer, ce fichier va notamment vous permettre de :

45 |
    46 |
  1. Importer les données de la base équidés.
  2. 47 |
  3. Nettoyer les variables et sélectionner celles à anonymiser
  4. 48 |
  5. Anonymiser les données selon un procédé de K-anonymisation
  6. 49 |
50 |

The file can be downloaded here: 51 | https://www.data.gouv.fr/fr/datasets/fichier-des-equides/ 52 | or directly : 53 | https://www.data.gouv.fr/s/resources/fichier-des-equides/20141201-185229/Equides.csv

54 |

Le fichier de 200 Mo contient autours de 3 millions de lignes

55 |
56 |
57 |
import csv
 58 | import numpy as np
 59 | import pandas as pd
 60 | import matplotlib
 61 | import matplotlib.pyplot as plt
 62 | 
 63 | from anonymizer.import_insee import (expand_insee,
 64 |                                      nbre_modif)
 65 | 
 66 | from anonymizer.anonymity import (get_k, get_anonymities,
 67 |                                   less_anonym_groups,
 68 |                                   local_aggregation,
 69 |                                   _local_aggregate_one_var)
 70 | from anonymizer.diversity import (get_l,
 71 |                                   get_diversities,
 72 |                                   diversity_distribution,
 73 |                                   less_diverse_groups
 74 |                                 )
 75 | from anonymizer.transformations import (first_letters,
 76 |                                        last_letters)
 77 | from anonymizer.transformations import str_drop
 78 | from anonymizer.anonymDF import AnonymDataFrame
79 |
80 |
81 |
82 |
83 |
84 |
85 | # 86 |
87 |

I. Nettoyage de la base de données

88 |
89 |
90 |
chemin = "D:/data/Equides.csv"
 91 | equides = pd.read_csv(chemin, sep = ";", encoding = "ISO-8859-1", nrows = 50000, header=None, low_memory = False)
 92 | 
 93 | 
 94 | nom_de_colonnes = ['Race',
 95 |                    'Sexe',
 96 |                    'Robe',
 97 |                    'Date de naissance',
 98 |                    'Pays de naissance',
 99 |                    'Nom',
100 |                    'Destiné à la consommation humaine',
101 |                    'Date de mort']
102 | equides.columns = nom_de_colonnes
103 |
104 |
105 |
106 |
107 |
108 |
109 | # 110 |
111 |

On supprime la date de mort puisque cela nous fournirait un indice sur l'âge du cheval, 112 | qu'il faudrait veiller à anonymiser.

113 |
114 |
115 |
variables_supprimees = ['Date de mort']
116 | equides = equides.drop(variables_supprimees,1)
117 |
118 |
119 |
120 |
121 |
122 |
123 | # 124 |
125 |

La variable "date de naissance" doit être recodée. On choisit de ne garder que l'année.

126 |
127 |
128 |
equides['Date de naissance'] = last_letters(equides['Date de naissance'],6)
129 |
130 |
131 |
132 |
133 |
134 |
135 | # 136 |
137 |

On remplace les modalités vides ou non renseignées par des "non renseigné"

138 |
139 |
140 |
equides = equides.fillna('non renseigné')
141 | equides = equides.applymap(lambda x: x.strip())
142 | equides.replace('', 'non renseigné', inplace=True)
143 |
144 |
145 |
146 |
147 |
148 |
149 | # 150 |
151 |

On convertit tous les noms de races en minuscules afin de mieux pouvoir uniformiser 152 | et on normalise afin de n'obtenir plus qu'une modalité inconnu, anglo-arabe, weslh ou aa compl.

153 |
154 |
155 |
equides['Race'] = equides['Race'].str.lower()
156 | liste_races = equides['Race'].unique().tolist()
157 | 
158 | for word in ['inconnu', 'anglo-arabe', 'welsh', 'aa compl.']:
159 |     for race in liste_races :
160 |         if word in race:
161 |             print(word, race)
162 |             equides['Race'] = equides['Race'].replace(race, word)
163 | 
164 | liste_races = equides['Race'].unique().tolist()
165 | len(liste_races)
166 |
167 |
168 |
169 |
170 |
171 |
172 | # 173 |
174 |

II. Anonymisation

175 |
176 |
177 |
178 |
179 |
180 |
181 |
182 |
183 |
184 | # 185 |
186 |

On définit les variables à anonymiser

187 |
188 |
189 |
ordre_aggregation = ['Race',
190 |                      'Sexe',
191 |                      'Robe',
192 |                      'Pays de naissance',
193 |                      'Destiné à la consommation humaine',
194 |                      'Date de naissance']
195 |
196 |
197 |
198 |
199 |
200 |
201 | # 202 |
203 |

Pour les cinq premières variables, on anonymise selon la méthode "groupped"

204 |
205 |
206 |
k = 5
207 | kanonym_equides = local_aggregation(equides.copy(), k, ordre_aggregation[:-1])
208 |
209 |
210 |
211 |
212 |
213 |
214 | # 215 |
216 |

Pour la date de naissance, on anonymise selon la méthode "year"

217 |
218 |
219 |
kanonym_equides = local_aggregation(kanonym_equides, k, [ordre_aggregation[-1]], method = "year")
220 |
221 |
222 |
223 |
224 |
225 |
226 | # 227 |
228 |

III. Résultats

229 |
230 |
231 |
232 |
233 |
234 |
235 |
236 |
237 |
238 | # 239 |
240 |

La base est 5-anonymisée

241 |
242 |
243 |
kanonym_equides
244 | 
245 | 
246 |
247 |
248 |
249 |
250 | 251 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /docs/Transformation_santé.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Transformation_santé.py 6 | 7 | 8 | 9 |
10 |
11 |
12 |

Transformation_santé.py

13 |
14 |
15 |
16 |
17 |
18 | # 19 |
20 | 21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 | # 31 |
32 |

!/usr/bin/env python

33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 | # 43 |
44 |

A partir des fonctions du dépôt anonymizer, ce fichier va notamment vous permettre de :

45 |
    46 |
  1. Importer les données de la base Transparence Santé.
  2. 47 |
  3. Nettoyer les variables et sélectionner celles à anonymiser
  4. 48 |
  5. Anonymiser les données selon un procédé de K-anonymisation
  6. 49 |
  7. Compléter avec les données INSEE afin d'en mesurer la plus-value.
  8. 50 |
51 |
52 |
53 |
import csv
 54 | import numpy as np
 55 | import pandas as pd
 56 | import matplotlib
 57 | import matplotlib.pyplot as plt
 58 | 
 59 | from import_insee import (expand_insee, nbre_modif)
 60 | 
 61 | from anonymizer.anonymity import (get_k, get_anonymities,
 62 |                                   less_anonym_groups,
 63 |                                   local_aggregation,
 64 |                                   _local_aggregate_one_var)
 65 | from anonymizer.diversity import (get_l,
 66 |                                   get_diversities,
 67 |                                   diversity_distribution,
 68 |                                   less_diverse_groups
 69 |                                 )
 70 | from anonymizer.transformations import (first_letters,
 71 |                                        last_letters)
 72 | from anonymizer.transformations import str_drop
 73 | from anonymizer.anonymDF import AnonymDataFrame
74 |
75 |
76 |
77 |
78 |
79 |
80 | # 81 |
82 |

I. Nettoyage de la base de données

83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 | # 93 |
94 |

Importation des 50 000 premières lignes

95 |
96 |
97 |
chemin = "~/data/transparence/declaration_avantage_2016_05_14_04_00.csv"
 98 | 
 99 | nbre_lignes = 50000
100 | avantages = pd.read_csv(chemin, sep = ";", nrows = nbre_lignes, low_memory = False)
101 |
102 |
103 |
104 |
105 |
106 |
107 | # 108 |
109 |

Séparation personnes physiques/morales

110 |
111 |
112 |
113 |
114 |
115 |
116 |
117 |
118 |
119 | # 120 |
121 |

On ne traite pas le cas des personnes morales

122 |
123 |
124 |
code_personne_physique = ['[PRS]','[ETU]']
125 | personnes_physiques = avantages[avantages['benef_categorie_code'].isin(code_personne_physique)]
126 | personnes_morales = avantages[~avantages['benef_categorie_code'].isin(code_personne_physique)]
127 | avantages = personnes_physiques
128 |
129 |
130 |
131 |
132 |
133 |
134 | # 135 |
136 |

transformations préalables

137 |
138 |
139 |
140 |
141 |
142 |
143 |
144 |
145 |
146 | # 147 |
148 |
    149 |
  • On transforme les CP en indicateurs régionaux
  • 150 |
151 |
152 |
153 |
avantages['benef_dept'] = first_letters(avantages['benef_codepostal'],2)
154 |
155 |
156 |
157 |
158 |
159 |
160 | # 161 |
162 |
    163 |
  • On supprime les CP peu orthodoxes
  • 164 |
165 |
166 |
167 |
erreur_CP = ['0', '', 'IN']
168 | avantages.loc[avantages['benef_dept'].isin(erreur_CP), 'benef_dept'] = np.nan
169 | erreur_pays = ['[RE]','[GP]']
170 | avantages.loc[avantages['benef_pays_code'].isin(erreur_pays), 'benef_pays_code'] = '[FR]'
171 |
172 |
173 |
174 |
175 |
176 |
177 | # 178 |
179 |
    180 |
  • On homogénéise les valeurs manquantes ou tierces par la mention "non-renseigné"
  • 181 |
182 |
183 |
184 |
avantages = avantages.fillna('non renseigné')
185 | to_replace = ['[AUTRE]', '']
186 | avantages.replace(to_replace, 'non renseigné', inplace=True)
187 |
188 |
189 |
190 |
191 |
192 |
193 | # 194 |
195 |
    196 |
  • On transforme la valeur des conventions/avantages en leur équivalent décile (uniformisation)
  • 197 |
198 |
199 |
200 |
avantages['avant_montant_ttc'] = avantages['avant_montant_ttc'].astype(float)
201 | avantages['montant_décile'] = pd.qcut(avantages.avant_montant_ttc,10)
202 |
203 |
204 |
205 |
206 |
207 |
208 | # 209 |
210 |
    211 |
  • On transforme la date (signature des avantages) en mois/année (le jour est trop identifiant)
  • 212 |
213 |
214 |
215 |
avantages['date'] = last_letters(avantages['avant_date_signature'],3)
216 | 
217 | avantages['avant_nature'] = avantages['avant_nature'].str.lower()
218 |
219 |
220 |
221 |
222 |
223 |
224 | # 225 |
226 |
    227 |
  • On supprime d'abord les variables identifiantes afin de ne garder que les variables quasi-identifiantes
  • 228 |
229 |
230 |
231 |
variables_supprimees = ['avant_convention_lie',
232 |                         'identifiant_type',
233 |                         'benef_qualification',
234 |                         'benef_speicalite_libelle',
235 |                         'ligne_rectification',
236 |                         'denomination_sociale',
237 |                         'benef_titre_libelle',
238 |                         'benef_prenom',
239 |                         'benef_nom',
240 |                         'benef_adresse1',
241 |                         'benef_adresse2',
242 |                         'benef_adresse3',
243 |                         'benef_adresse4',
244 |                         'benef_identifiant_valeur',
245 |                         'benef_ville',
246 |                         'benef_etablissement_ville',
247 |                         'categorie',
248 |                         'benef_qualite_code',
249 |                         'benef_codepostal',
250 |                         'benef_etablissement_codepostal',
251 |                        'ligne_identifiant',
252 |                        'pays',
253 |                        'benef_denomination_sociale',
254 |                        'benef_objet_social',
255 |                         'avant_date_signature',
256 |                         'avant_montant_ttc',
257 |                        'benef_etablissement']
258 | 
259 | avantages = avantages.drop(variables_supprimees,1)
260 | 
261 | avantages['montant_décile'] = avantages['montant_décile'].astype(str)
262 | avantages['date'] = avantages['date'].astype(str)
263 |
264 |
265 |
266 |
267 |
268 |
269 | # 270 |
271 |

On définit ici les variables traitées pour l'anonymisation

272 |
273 |
274 |
var = avantages.columns.tolist()
275 | var.remove('ligne_type')
276 | var.remove('avant_nature')
277 |
278 |
279 |
280 |
281 |
282 |
283 | # 284 |
285 |

II. Traitement des données brutes (sans INSEE)

286 |
287 |
288 |
289 |
290 |
291 |
292 |
293 |
294 |
295 | # 296 |
297 |

On k-anonymise dès maintenant la base brute. 298 | On définit ici k = 5

299 |
300 |
301 |
copy = avantages.copy
302 | k = 5
303 | avantages_kanonym = local_aggregation(avantages.copy(), k, var, method='regroup')
304 | 
305 | 
306 | 
307 | 
308 | modalites_modifiees = [((avantages_kanonym[avantages_kanonym['ligne_type']=='[A]'].values != avantages[avantages['ligne_type']=='[A]'].values).sum())]
309 | modalites_intactes = [((avantages_kanonym[avantages_kanonym['ligne_type']=='[A]'].values == avantages[avantages['ligne_type']=='[A]'].values).sum())]
310 |
311 |
312 |
313 |
314 |
315 |
316 | # 317 |
318 |

II. Chargement des données INSEE

319 |
320 |
321 |
322 |
323 |
324 |
325 |
326 |
327 |
328 | # 329 |
330 |

construction d'un dictionnaire reliant les professions (INSEE) aux professions (Transparence Santé)

331 |
332 |
333 |
annuaire = {'Médecin omnipraticien' : ['benef_specialite_code', '[SM54]'],
334 |  'Spécialiste en cardiologie' : ['benef_specialite_code', '[SM04]'],
335 |  'Spécialiste en dermatologie vénéréologie' : ['benef_specialite_code', '[SM15]'],
336 |  'Spécialiste en gynécologie médicale' : ['benef_specialite_code', '[SM19]'],
337 |  'Spécialiste en gynécologie obstétrique' : ['benef_specialite_code', '[SM20]'],
338 |  'Spécialiste en gastro-entérologie hépatologie' : ['benef_specialite_code', '[SM24]'],
339 |  'Spécialiste en psychiatrie' : ['benef_specialite_code', '[SM42]'],
340 |  'Spécialiste en ophtalmologie' : ['benef_specialite_code', '[SM38]'],
341 |  'Spécialiste en oto-rhino-laryngologie' : ['benef_specialite_code', '[SM39]'],
342 |  'Spécialiste en pédiatrie' : ['benef_specialite_code', '[SM40]'],
343 |  'Spécialiste en pneumologie' : ['benef_specialite_code', '[SM41]'],
344 |  'Spécialiste en radiodiagnostic et imagerie médicale' : ['benef_specialite_code', '[SM44]'],
345 |  'Spécialiste en stomatologie' : ['benef_specialite_code', '[SM50]'],
346 |  'Chirurgien dentiste' : ['qualite', 'Chirurgien-dentiste'],
347 |  'Sage-femme' : ['qualite', 'Sage-femme'],
348 |  'Infirmier' : ['qualite', 'Infirmier'],
349 |  'Masseur kinésithérapeute' : ['qualite', 'Masseur-kinésithérapeute'],
350 |  'Orthophoniste' : ['qualite', 'Orthophoniste'],
351 |  'Orthoptiste' : ['qualite', 'Orthoptiste'],
352 |  'Pédicure-podologue' : ['qualite', 'Pédicure-podologue'],
353 |  'Audio prothésiste' : ['qualite', 'Audio prothésiste'],
354 |  'Ergothérapeute' : ['qualite', 'Ergothérapeute'],
355 |  'Psychomotricien' : ['qualite', 'Psychomotricien']}
356 |
357 |
358 |
359 |
360 |
361 |
362 | # 363 |
364 |

On charge les données INSEE

365 |
366 |
367 |
chemin_insee = '/home/pierre-louis/Téléchargements/Python/insee_sante.csv'
368 | 
369 | insee_init = pd.read_csv(chemin_insee, sep=";", encoding = "ISO-8859-1", low_memory=False)
370 | insee_init.columns.astype(str)
371 | 
372 | insee_init['Département'] = insee_init['Département'].astype(str)
373 | insee_init['Région 2016'] = insee_init['Région 2016'].astype(str)
374 | 
375 | insee_init['Département'] = first_letters(insee_init['Département'],2)
376 |
377 |
378 |
379 |
380 |
381 |
382 | # 383 |
384 |

On fusionne les départements d'Outre-mer dans une seule catégorie (trop identifiant, sinon)

385 |
386 |
387 |
outremer = ['1','2','3','4','6']
388 | insee_init.loc[insee_init['Région 2016'].isin(outremer), 'Région 2016'] = 1
389 | 
390 | list_région = insee_init['Région 2016'].unique().tolist()
391 | 
392 | insee = insee_init.copy()
393 | 
394 | var_écartées = ['Région', 'Région 2016', 'CODGEO', 'Libellé commune ou ARM']
395 | insee = insee.drop(var_écartées,1)
396 |
397 |
398 |
399 |
400 |
401 |
402 | # 403 |
404 |

On rajoute à la base originale les données INSEE

405 |
406 |
407 |
408 |
409 |
410 |
411 |
412 |
413 |
414 | # 415 |
416 |

avantages_total est donc constituée de la base Transparence Santé, complétée par les données INSEE

417 |
418 |
419 |
g = insee.groupby('Département')
420 | 
421 | expanded_insee = expand_insee(g, annuaire, avantages)
422 | 
423 | expanded_insee.columns = avantages.columns.tolist()
424 | avantages_total = pd.concat([avantages, expanded_insee]).reset_index()
425 | avantages_total = avantages_total.drop('index',1)
426 |
427 |
428 |
429 |
430 |
431 |
432 | # 433 |
434 |

On anonymise (données enrichies)

435 |
436 |
437 |
result_insee = local_aggregation(avantages_total.copy(), k, var, method = 'regroup')
438 | 
439 | 
440 | 
441 | 
442 | modalites_modifiees.append((result_insee[result_insee['ligne_type']=='[A]'].values != avantages_total[avantages_total['ligne_type']=='[A]'].values).sum())
443 | modalites_intactes.append((result_insee[result_insee['ligne_type']=='[A]'].values == avantages_total[avantages_total['ligne_type']=='[A]'].values).sum())
444 |
445 |
446 |
447 |
448 |
449 |
450 | # 451 |
452 |

IV. Comparaison

453 |
454 |
455 |
456 |
457 |
458 |
459 |
460 |
461 |
462 | # 463 |
464 |

Représentation graphique des différences entre les deux méthodes

465 |
466 |
467 |
468 |
469 |
470 |
471 |
472 |
473 |
474 | # 475 |
476 |

On mesure :

477 |
478 |
479 |
480 |
481 |
482 |
483 |
484 |
485 |
486 | # 487 |
488 |
    489 |
  1. Le nombre de lignes différentes avant et après l'opération
  2. 490 |
  3. Le nombre de lignes inchangées après l'opération
  4. 491 |
  5. On stocke ces valeurs dans modalites_modifiees et modalites_intactes
  6. 492 |
493 |
494 |
495 |
n_groups = 2 # data to plot
496 | 
497 | 
498 | fig, ax = plt.subplots() # create plot # éventuellement mentionner la taille du graphique : figsize=(15, 6)
499 | 
500 | index = np.arange(n_groups)
501 | bar_width = 0.35
502 | opacity = 1
503 | 
504 | rects1 = plt.bar(index, modalites_modifiees, bar_width,
505 |                  alpha=opacity,
506 |                  color='b',
507 |                  label='Modalités modifiées')
508 | 
509 | 
510 | rects2 = plt.bar(index + bar_width, modalites_intactes , bar_width,
511 |                  alpha=opacity,
512 |                  color='y',
513 |                  label='Modalités non modifiées')
514 | 
515 | plt.ylim(0, 500000)
516 | ax.axhline(y = modalites_modifiees[0])
517 | ax.axhline(y = modalites_intactes[0])
518 | 
519 | plt.xlabel('Région')
520 | plt.ylabel('Modalités modifiées')
521 | plt.title('Nombre de modalités')
522 | plt.xticks(index + bar_width, 'bla')
523 | plt.legend()
524 | 
525 | plt.tight_layout()
526 | plt.show()
527 |
528 |
529 |
530 |
531 |
532 |
533 | # 534 |
535 |

On va maintenant comparer par variables le taux de remplacement

536 |
537 |
538 |
(avantages_kanonym[var[0]] != avantages[var[0]]).sum()
539 | 
540 | modif_par_var_1 = []
541 | for variable in var :
542 |     modif_par_var_1.append((avantages_kanonym[variable] != avantages[variable]).sum())
543 | 
544 | modif_par_var_2 = []
545 | for variable in var :
546 |     modif_par_var_2.append((result_insee[variable][result_insee['ligne_type']=='[A]'] != avantages_total[variable][avantages_total['ligne_type']=='[A]']).sum())
547 | 
548 | 
549 | n_groups = len(var) # data to plot
550 | 
551 | fig, ax = plt.subplots(figsize=(15, 6)) # create plot
552 | 
553 | 
554 | index = np.arange(n_groups)
555 | bar_width = 0.35
556 | opacity = 1
557 | 
558 | rects1 = plt.bar(index, modif_par_var_1, bar_width,
559 |                  alpha=opacity,
560 |                  color='b',
561 |                  label='Séries brutes')
562 | 
563 | 
564 | rects2 = plt.bar(index + bar_width, modif_par_var_2 , bar_width,
565 |                  alpha=opacity,
566 |                  color='y',
567 |                  label='Séries avec données INSEE')
568 | 
569 | plt.ylim(0, 30000) #ax.axhline(y = modalites_modifiees[0]) #ax.axhline(y = taille_données_transparence[0])
570 | 
571 | 
572 | plt.xlabel('Variable anonymisée')
573 | plt.ylabel('Nombre de valeurs modifiées')
574 | plt.title('Modification de valeurs')
575 | plt.xticks(index + bar_width, var)
576 | plt.legend()
577 | 
578 | plt.tight_layout()
579 | plt.show()
580 | 
581 | 
582 |
583 |
584 |
585 |
586 | 587 | --------------------------------------------------------------------------------