markdown
stringlengths 0
37k
| code
stringlengths 1
33.3k
| path
stringlengths 8
215
| repo_name
stringlengths 6
77
| license
stringclasses 15
values |
---|---|---|---|---|
Attributes are data associated with an object (instance) or class. Object attributes (and methods) are specified by using "self". Instance attributes and methods are accessed using the dot "." operator. | class Car(object):
# The following method is called when the class
# is created or "constructed". The variables "self.x" refers
# to the variable "x" in a created object.
def __init__(self, color, car_type, speed):
self.color = color
self.car_type = car_type
self.speed = speed
car1 = Car("blue", "sedan", "very slow")
car2 = Car("red", "sedan", "not so slow")
print(car1.speed, car2.speed)
class Car(object):
# The following method is called when the class
# is created or "constructed". The variables "self.x" refers
# to the variable "x" in a created object.
def __init__(self, color, car_type, speed, sunroof=True):
self.color = color
self.car_type = car_type
if isinstance(speed, int):
self.speed = speed
else:
raise ValueError("Bad speed value.")
self.sunroof = sunroof
car = Car("blue", "sedan", 100)
# Creating an object for a class with arguments in the __init__ method
car = Car("Blue", "HatchBack", 100)
car.color
# Creating an object for a class with arguments in the __init__ method
joe_car = Car("Blue", "Sedan", 100)
dave_car = Car("Red", "Sports", 150)
print ("Type of joe_car is %s. Type of dave_car is %s"% (type(joe_car), type(dave_car)))
# Accessed instance attributes
joe_car = Car("Blue", "Sedan", 100)
print ("Type of joe_car has (color, type, speed)=%s." % str((joe_car.color, joe_car.car_type, joe_car.speed))) | Spring2019/06a_Objects/Building Software With Objects.ipynb | UWSEDS/LectureNotes | bsd-2-clause |
EXERCISE: Change the constructor for Car to include the attribute "doors".
Instance Methods | from IPython.display import Image
Image(filename='InstanceMethods.png')
#Class diagram
from IPython.display import Image
Image(filename='SingleClassDiagram.png', width=200, height=200) | Spring2019/06a_Objects/Building Software With Objects.ipynb | UWSEDS/LectureNotes | bsd-2-clause |
A class diagram provides a more compact representation of a class. There are three sections.
- Class name
- Attributes
- Methods
Instance methods
- functions associated with the objects constructed for a class
- provide a way to transform data in objects
- use instance attributes (references to variables beginning with "self.") | class Car(object):
def __init__(self, color, car_type, speed):
"""
:param str color:
:param str car_type:
:param int speed:
"""
self.color = color
self.car_type = car_type
self.speed = speed
def start(self):
print ("%s %s started!" % (self.color, self.car_type))
def stop(self):
pass
def turn(self, direction):
"""
:parm str direction: left or right
"""
pass
car = Car("Blue", "Sedan", 100)
car.start() | Spring2019/06a_Objects/Building Software With Objects.ipynb | UWSEDS/LectureNotes | bsd-2-clause |
EXERCISE: Implement the stop and turn methods. Run the methods.
Inheritance
Inheritance is a common way that classes reuse data and code from other classes. A child class or derived class gets attributes and methods from its parent class.
Programmatically:
- Specify inheritance in the class statement
- Constructor for derived class (class that inherits) have access to the constructor of its parent.
Inheritance is represented in diagrams as an arror from the child class to its parent class. | from IPython.display import Image
Image(filename='SimpleClassHierarchy.png', width=400, height=400)
# Code for inheritance
class Sedan(Car):
# Sedan inherits from car
def __init__(self, color, speed):
"""
:param str color:
:param int speed:
"""
super().__init__(color, "Sedan", speed)
def play_cd(self):
print ("Playing cd in %s sedan" % self.color)
sedan = Sedan("Yellow", 1e6)
sedan.color
sedan.car_type
sedan.car_type
joe_car = Sedan("Blue", 100)
print ("Type of joe_car has (color, type, speed)=%s." % str((joe_car.color, joe_car.car_type, joe_car.speed))) | Spring2019/06a_Objects/Building Software With Objects.ipynb | UWSEDS/LectureNotes | bsd-2-clause |
Exercise: Implement SportsCar and create dave_car from SportsCar. Print attributes of dave_car. | from IPython.display import Image
Image(filename='ClassInheritance.png', width=400, height=400) | Spring2019/06a_Objects/Building Software With Objects.ipynb | UWSEDS/LectureNotes | bsd-2-clause |
Subclasses can have their own methods.
Exercise: Add the play_cd() to Sedan and play_bluetooth() method to SportsCar. Construct a test to run these methods.
What Else?
Class attributes
Class methods
Object Oriented Design
A design methodology must specify:
- Components: What they do and how to build them
- Interactions: How the components interact to implement use cases
Object oriented designed
- Components are specified by class diagrams.
- Interactions are specified by interaction diagrams.
Class diagram for the ATM system | from IPython.display import Image
Image(filename='ATMClassDiagram.png', width=400, height=400) | Spring2019/06a_Objects/Building Software With Objects.ipynb | UWSEDS/LectureNotes | bsd-2-clause |
The diamond arrow is a "has-a" relationship. For example, the Controller has-a ATMInput. This means that a Controller object has an instance variable for an ATMInput object.
Interaction Diagram for the ATM System
An interaction diagram specifies how components interact to achieve a use case.
Interactions are from one object to another object, indicating that the first object calls a method in the second object.
Rules for drawing lines in an interaction diagram:
- The calling object must know about the called object.
- The called object must have the method invoked by the calling object. | from IPython.display import Image
Image(filename='ATMAuthentication.png', width=800, height=800) | Spring2019/06a_Objects/Building Software With Objects.ipynb | UWSEDS/LectureNotes | bsd-2-clause |
Look at Objects/ATMDiagrams.pdf for a solution.
What Else in Design?
Other diagrams: state diagrams, package diagrams, ...
Object oriented design patterns
Complex Example of Class Hierarchy | from IPython.display import Image
Image(filename='SciSheetsCoreClasses.png', width=300, height=30) | Spring2019/06a_Objects/Building Software With Objects.ipynb | UWSEDS/LectureNotes | bsd-2-clause |
Section 1: Exemple de signaux, temps et fréquence
1. Commençons par générer un signal d'intérêt: | %%matlab
%% Définition du signal d'intêret
% fréquence du signal
freq = 1;
% on crée des blocs off/on de 15 secondes
bloc = repmat([zeros(1,15*freq) ones(1,15*freq)],[1 10]);
% les temps d'acquisition
ech = (0:(1/freq):(length(bloc)/freq)-(1/freq));
% ce paramètre fixe le pic de la réponse hémodynamique
pic = 5;
% noyau de réponse hémodynamique
noyau = [linspace(0,1,(pic*freq)+1) linspace(1,-0.3,(pic*freq)/2) linspace(-0.3,0,(pic*freq)/2)];
noyau = [zeros(1,length(noyau)-1) noyau];
% normalisation du noyau
noyau = noyau/sum(abs(noyau));
% convolution du bloc avec le noyau
signal = conv(bloc,noyau,'same');
% on fixe la moyenne de la réponse à zéro
signal = signal - mean(signal); | NSC2006/labo8_filtrage/labo 8 Introduction au filtrage reponses.ipynb | SIMEXP/Projects | mit |
Représentez noyau et signal en temps, à l'aide de la commande plot. Utiliser les temps d'acquisition corrects, et labéliser les axes (xlabel, ylabel). Comment est généré signal? reconnaissez vous le processus employé? Est ce que le signal est périodique? si oui, quelle est sa période? Peut-on trouver la réponse dans le code? | %%matlab
%% représentation en temps
% Nouvelle figure
figure
% On commence par tracer le noyau
plot(noyau,'-bo')
% Nouvelle figure
figure
% On trace le signal, en utilisant ech pour spécifier les échantillons temporels
plot(ech,signal)
% Les fonctions xlim et ylim permettent d'ajuster les valeurs min/max des axes
xlim([-1 max(ech)+1])
ylim([-0.6 0.7])
% Les fonctions xlabel et ylabel permettent de labéliser les axes
xlabel('Temps (s)')
ylabel('a.u') | NSC2006/labo8_filtrage/labo 8 Introduction au filtrage reponses.ipynb | SIMEXP/Projects | mit |
A partir du graphe du noyau, on reconnait la fonction de réponse hémodynamique utilisée lors du laboratoire sur la convolution. Le signal est généré par convolution du noyau avec un vecteur bloc (ligne 18 du bloc de code initial). On voit que bloc est créé en assemblant deux vecteurs de 15 zéros et de 15 uns (ligne 7). Le signal est donc périodique. Comme la fréquence d'acquisition est de 1 Hz (ligne 9 définissant les échantillons temporels, on voit un pas de 1/freq, avec freq=1, ligne 5), la période du signal est de 30 secondes, soit une fréquence de 0.033Hz. On peut confirmer cela visuellement sur le graphe.
2. Représenter le contenu fréquentiel de signal avec la commande Analyse_Frequence_Puissance.
Utilisez la commande ylim pour ajuster les limites de l'axe y et pouvoir bien observer le signal. Notez que l'axe y (puissance) est en échelle log (dB). Quelles sont les fréquences principales contenues dans le signal? Etait-ce attendu? | %%matlab
%% représentation en fréquences
% Nouvelle figure
figure
% La fonction utilise le signal comme premier argument, et les échantillons temporels comme deuxième
Analyse_Frequence_Puissance(signal,ech);
% On ajuste l'échelle de l'axe y.
ylim([10^(-10) 1]) | NSC2006/labo8_filtrage/labo 8 Introduction au filtrage reponses.ipynb | SIMEXP/Projects | mit |
Comme attendu, étant donné le caractère périodique de période 30s du signal, la fréquence principale est de 0.033 Hz. Les pics suivants sont situés à 0.1 Hz et 0.166 Hz.
3. Répétez les questions 1.1 et 1.2 avec un bruit dit blanc, généré ci dessous. | %%matlab
%% définition du bruit blanc
bruit = 0.05*randn(size(signal)); | NSC2006/labo8_filtrage/labo 8 Introduction au filtrage reponses.ipynb | SIMEXP/Projects | mit |
Pourquoi est ce que ce bruit porte ce nom? | %%matlab
% Ce code n'est pas commenté, car essentiellement identique
% à ceux présentés en question 1.1. et 1.2.
%% représentation en temps
figure
plot(ech,bruit)
ylim([-0.6 0.7])
xlabel('Temps (s)')
ylabel('a.u')
%% représentation en fréquences
figure
Analyse_Frequence_Puissance(bruit,ech);
ylim([10^(-10) 1]) | NSC2006/labo8_filtrage/labo 8 Introduction au filtrage reponses.ipynb | SIMEXP/Projects | mit |
Le vecteur bruit est généré à l'aide de la fonction randn, qui est un générateur pseudo-aléatoires d'échantillons indépendants Gaussiens. Le spectre de puissance représente l'amplitude de la contribution de chaque fréquence au signal. On peut également décomposer une couleur en fréquences. Quand toutes les fréquences sont présentes, et en proportion similaire, on obtient du blanc. Le bruit Gaussien a un spectre de puissance plat (hormis de petites variations aléatoires), ce qui lui vaut son surnom de bruit blanc.
4. Bruit respiratoire.
Répétez les les questions 1.1 et 1.2 avec un bruit dit respiratoire, généré ci dessous. | %%matlab
%% définition du signal de respiration
% fréquence de la respiration
freq_resp = 0.3;
% un modéle simple (cosinus) des fluctuations liées à la respiration
resp = cos(2*pi*freq_resp*ech/freq);
% fréquence de modulation lente de l'amplitude respiratoire
freq_mod = 0.01;
% modulation de l'amplitude du signal lié à la respiration
resp = resp.*(ones(size(resp))-0.1*cos(2*pi*freq_mod*ech/freq));
% on force une moyenne nulle, et une amplitude max de 0.1
resp = 0.1*(resp-mean(resp));
%%matlab
% Ce code n'est pas commenté, car essentiellement identique
% à ceux présentés en question 1.1. et 1.2.
%% représentation en temps
figure
plot(ech,resp)
xlim([-1 max(ech)/2+1])
xlabel('Temps (s)')
ylabel('a.u')
%% représentation en fréquences
figure
[ech_f,signal_f,signal_af,signal_pu] = Analyse_Frequence_Puissance(resp,ech);
set(gca,'yscale','log');
ylim([10^(-35) 1]) | NSC2006/labo8_filtrage/labo 8 Introduction au filtrage reponses.ipynb | SIMEXP/Projects | mit |
Est ce une simulation raisonnable de variations liées à la respiration? pourquoi?
On voit que ce signal est essentiellement composé de fréquences autour de 0.3Hz. Cela était déjà apparent avec l'introduction d'un cosinus de fréquence 0.3Hz dans la génération (ligne 7). L'amplitude de ce cosinus est elle-même modulée par un autre cosinus, plus lent (ligne 11). D'aprés wikipedia, un adulte respire de 16 à 20 fois par minutes, soit une fréquence de 0.26 à 0.33Hz (en se ramenant en battements par secondes). Cette simulation utilise donc une fréquence raisonnable pour simuler la respiration.
5. Ligne de base.
Répétez les les questions 1.1 et 1.2 avec une dérive de la ligne de base, telle que générée ci dessous. | %%matlab
%% définition de la ligne de base
base = 0.1*(ech-mean(ech))/mean(ech);
%%matlab
% Ce code n'est pas commenté, car essentiellement identique
% à ceux présentés en question 1.1. et 1.2.
%% représentation en temps
figure
plot(ech,base)
xlim([-1 max(ech)+1])
ylim([-0.6 0.7])
xlabel('Temps (s)')
ylabel('a.u')
%% représentation en fréquence
figure
[ech_f,base_f,base_af,base_pu] = Analyse_Frequence_Puissance(base,ech);
ylim([10^(-10) 1]) | NSC2006/labo8_filtrage/labo 8 Introduction au filtrage reponses.ipynb | SIMEXP/Projects | mit |
Le vecteur base est une fonction linéaire du temps (ligne 4). En représentation fréquentielle, il s'agit d'un signal essentiellement basse fréquence.
6. Mélange de signaux.
On va maintenant mélanger nos différentes signaux, tel qu'indiqué ci-dessous. Représentez les trois mélanges en temps et en fréquence, superposé au signal d'intérêt sans aucun bruit (variable signal). Pouvez-vous reconnaitre la contribution de chaque source dans le mélange fréquentiel? Est ce que les puissances de fréquences s'additionnent systématiquement? | %%matlab
%% Mélanges de signaux
y_sr = signal + resp;
y_srb = signal + resp + bruit;
y_srbb = signal + resp + bruit + base;
%%matlab
% Ce code n'est pas commenté, car essentiellement identique
% à ceux présentés en question 1.1. et 1.2.
% notez tout de même l'utilisation d'un hold on pour superposer la variable `signal` (sans bruit)
% au mélange de signaux.
y = y_sr;
% représentation en temps
figure
plot(ech,y)
hold on
plot(ech,signal,'r')
xlim([-1 301])
ylim([-0.8 0.8])
xlabel('Temps (s)')
ylabel('a.u')
% représentation en fréquence
figure
Analyse_Frequence_Puissance(y,ech);
ylim([10^(-10) 1]) | NSC2006/labo8_filtrage/labo 8 Introduction au filtrage reponses.ipynb | SIMEXP/Projects | mit |
On reconnait clairement la série de pics qui composent la variable signal auquelle vient se rajouter les fréquences de la variable resp, à 0.3 Hz. Notez que les spectres de puissance ne s'additionnent pas nécessairement, cela dépend si, à une fréquence donnée, les signaux que l'on additionne sont ou non en phase. | %%matlab
% Idem au code précédent, y_sr est remplacé par y_srb dans la ligne suivante.
y = y_srb;
% représentation en temps
figure
plot(ech,y)
hold on
plot(ech,signal,'r')
xlim([-1 301])
ylim([-0.8 0.8])
xlabel('Temps (s)')
ylabel('a.u')
% représentation en fréquence
figure
[freq_f,y_f,y_af,y_pu] = Analyse_Frequence_Puissance(y,ech);
ylim([10^(-10) 1]) | NSC2006/labo8_filtrage/labo 8 Introduction au filtrage reponses.ipynb | SIMEXP/Projects | mit |
L'addition du bruit blanc ajoute des variations aléatoires dans la totalité du spectre et, hormis les pics du spectre associé à signal, il devient difficile de distinguer la contribution de resp. | %%matlab
% Idem au code précédent, y_srb est remplacé par y_srbb dans la ligne suivante.
y = y_srbb;
% représentation en temps
figure
plot(ech,y)
hold on
plot(ech,signal,'r')
xlim([-1 301])
ylim([-0.8 0.8])
xlabel('Temps (s)')
ylabel('a.u')
% représentation en fréquence
figure
[freq_f,y_f,y_af,y_pu] = Analyse_Frequence_Puissance(y,ech);
ylim([10^(-10) 1]) | NSC2006/labo8_filtrage/labo 8 Introduction au filtrage reponses.ipynb | SIMEXP/Projects | mit |
Section 2: Optimisation de filtre
2.1. Nous allons commencer par appliquer un filtre de moyenne mobile, avec le signal le plus simple (y_sr).
Pour cela on crée un noyau et on applique une convolution, comme indiqué ci dessous. | %%matlab
%%définition d'un noyau de moyenne mobile
% taille de la fenêtre pour la moyenne mobile, en nombre d'échantillons temporels
taille = ceil(3*freq);
% le noyau, défini sur une fenêtre identique aux signaux précédents
noyau = [zeros(1,(length(signal)-taille-1)/2) ones(1,taille) zeros(1,(length(signal)-taille-1)/2)];
% normalisation du moyau
noyau = noyau/sum(abs(noyau));
% convolution avec le noyau (filtrage)
y_f = conv(y_sr,noyau,'same'); | NSC2006/labo8_filtrage/labo 8 Introduction au filtrage reponses.ipynb | SIMEXP/Projects | mit |
Représentez le noyau en fréquence (avec Analyse_Frequence_Puissance), commentez sur l'impact fréquentiel de la convolution. Faire un deuxième graphe représentant le signal d'intérêt superposé au signal filtré. | %%matlab
%% Représentation fréquentielle du filtre
figure
% représentation fréquentielle du noyau
Analyse_Frequence_Puissance(noyau,ech);
ylim([10^(-10) 1])
%% représentation du signal filtré
figure
% signal aprés filtrage
plot(ech,y_f,'k')
hold on
% signal sans bruit
plot(ech,signal,'r')
%% erreur résiduelle
err = sqrt(mean((signal-y_f).^2)) | NSC2006/labo8_filtrage/labo 8 Introduction au filtrage reponses.ipynb | SIMEXP/Projects | mit |
On voit que cette convolution supprime exactement la fréquence correspondant à la largeur du noyau (3 secondes). Il se trouve que cette fréquence est aussi trés proche de la fréquence respiratoire choisie! Visuellement, le signal filtré est très proche du signal original. La mesure d'erreur (tel que demandée dans la question 2.2. ci dessous est de 3%.
2.2 Répétez la question 2.1 avec un noyau plus gros.
Commentez qualitativement sur la qualité du débruitage. | %%matlab
% taille de la fenêtre pour la moyenne mobile, en nombre d'échantillons temporels
% On passe de 3 à 7
% ATTENTION: sous matlab, ce code ne marche qu'avec des noyaux de taille impaire
taille = ceil(6*freq);
% le noyau, défini sur une fenêtre identique aux signaux précédents
noyau = [zeros(1,(length(signal)-taille-1)/2) ones(1,taille) zeros(1,(length(signal)-taille-1)/2)];
% normalisation du moyau
noyau = noyau/sum(abs(noyau));
% convolution avec le noyau (filtrage)
y_f = conv(y_sr,noyau,'same');
%% Représentation fréquentielle du filtre
figure
Analyse_Frequence_Puissance(noyau,ech);
ylim([10^(-10) 1])
%% représentation du signal filtré
figure
plot(ech,y_f,'k')
hold on
plot(ech,signal,'r')
%% erreur résiduelle
err = sqrt(mean((signal-y_f).^2)) | NSC2006/labo8_filtrage/labo 8 Introduction au filtrage reponses.ipynb | SIMEXP/Projects | mit |
On voit que ce noyau, en plus de supprimer une fréquence légèrement au dessus de 0.3 Hz, supprime aussi une fréquence proche de 0.16 Hz. C'était l'un des pics que l'on avait identifié dans le spectre de signal. De fait, dans la représentation temporelle, on voit que le signal filtré (en noir) est dégradé: les fluctuations rapides du signal rouge sont perdues. Et effectivement, on a maintenant une erreur résiduelle de 7.6%, supérieure au 3% du filtre précédent.
2.3 Nous allons maintenant appliquer des filtres de Butterworth.
Ces filtres sont disponibles dans des fonctions que vous avez déjà utilisé lors du laboratoire sur la transformée de Fourier:
- FiltrePasseHaut.m: suppression des basses fréquences.
- FiltrePasseBas.m: suppression des hautes fréquences.
Le filtre de Butterworth n'utilise pas explicitement un noyau de convolution. Mais comme il s'agit d'un systéme linéaire invariant dans le temps, on peut toujours récupérer le noyau en regardant la réponse à une impulsion finie unitaire. | %%matlab
%% Définition d'une implusion finie unitaire
impulsion = zeros(size(signal));
impulsion(round(length(impulsion)/2))=1;
noyau = FiltrePasseHaut(impulsion,freq,0.1); | NSC2006/labo8_filtrage/labo 8 Introduction au filtrage reponses.ipynb | SIMEXP/Projects | mit |
Représentez le noyau en temps et en fréquence. Quelle est la fréquence de coupure du filtre? | %%matlab
%% représentation temporelle
figure
plot(ech,noyau)
xlabel('Temps (s)')
ylabel('a.u')
%% représentation fréquentielle
figure
Analyse_Frequence_Puissance(noyau,ech);
set(gca,'yscale','log'); | NSC2006/labo8_filtrage/labo 8 Introduction au filtrage reponses.ipynb | SIMEXP/Projects | mit |
On observe une réduction importante de l'amplitude des fréquences inférieures à 0.1 Hz, qui correspond donc à la fréquence de coupure du filtre.
2.4. Application du filtre de Butterworth.
L'exemple ci dessous filtre le signal avec un filtre passe bas, avec une fréquence de coupure de 0.1. Faire un graphe représentant le signal d'intérêt (signal) superposé au signal filtré. Calculez l'erreur résiduelle, et comparez au filtre par moyenne mobile évalué précédemment. | %%matlab
y = y_sr;
y_f = FiltrePasseBas(y,freq,0.1);
%%représentation du signal filtré
plot(ech,signal,'r')
hold on
plot(ech,y_f,'k')
err = sqrt(mean((signal-y_f).^2)) | NSC2006/labo8_filtrage/labo 8 Introduction au filtrage reponses.ipynb | SIMEXP/Projects | mit |
Avec une fréquence de coupure de 0.1 Hz, on perd de nombreux pics de signal, notamment celui situé à 0.16Hz. Effectivement dans la représentation en temps on voit que les variations rapides de signal sont perdues, et l'erreur résiduelle est de 6%.
2.5. Optimisation du filtre de Butterworth.
Trouvez une combinaison de filtre passe-haut et de filtre passe-bas de Butterworth qui permette d'améliorer l'erreur résiduelle par rapport au filtre de moyenne mobile. Faire un graphe représentant le signal d'intérêt (signal) superposé au signal filtré, et un second avec le signal d'intérêt superposé au signal bruité, pour référence. | %%matlab
y = y_sr;
%% filtre de Butterworth
% on combine une passe-haut et un passe-bas, de maniére à retirer uniquement les fréquences autour de 0.3 Hz
y_f = FiltrePasseHaut(y,freq,0.35);
y_f = y_f+FiltrePasseBas(y,freq,0.25);
%% représentation du signal filtré
figure
plot(ech,signal,'r')
hold on
plot(ech,y_f,'k')
err = sqrt(mean((signal-y_f).^2))
%% représentation du signal brut
figure
plot(ech,signal,'r')
hold on
plot(ech,y,'k') | NSC2006/labo8_filtrage/labo 8 Introduction au filtrage reponses.ipynb | SIMEXP/Projects | mit |
Numpy Arrays
Manipulating numpy arrays is an important part of doing machine learning
(or, really, any type of scientific computation) in Python. This will likely
be review for most: we'll quickly go through some of the most important features. | import numpy as np
# Generating a random array
X = np.random.random((3, 5)) # a 3 x 5 array
print(X)
# Accessing elements
# get a single element
print(X[0, 0])
# get a row
print(X[1])
# get a column
print(X[:, 1])
# Transposing an array
print(X.T)
# Turning a row vector into a column vector
y = np.linspace(0, 12, 5)
print(y)
# make into a column vector
print(y[:, np.newaxis]) | _doc/notebooks/sklearn_ensae_course/01_data_manipulation.ipynb | sdpython/ensae_teaching_cs | mit |
There is much, much more to know, but these few operations are fundamental to what we'll
do during this tutorial.
Scipy Sparse Matrices
We won't make very much use of these in this tutorial, but sparse matrices are very nice
in some situations. For example, in some machine learning tasks, especially those associated
with textual analysis, the data may be mostly zeros. Storing all these zeros is very
inefficient. We can create and manipulate sparse matrices as follows: | from scipy import sparse
# Create a random array with a lot of zeros
X = np.random.random((10, 5))
print(X)
# set the majority of elements to zero
X[X < 0.7] = 0
print(X)
# turn X into a csr (Compressed-Sparse-Row) matrix
X_csr = sparse.csr_matrix(X)
print(X_csr)
# convert the sparse matrix to a dense array
print(X_csr.toarray()) | _doc/notebooks/sklearn_ensae_course/01_data_manipulation.ipynb | sdpython/ensae_teaching_cs | mit |
Matplotlib
Another important part of machine learning is visualization of data. The most common
tool for this in Python is matplotlib. It is an extremely flexible package, but
we will go over some basics here.
First, something special to IPython notebook. We can turn on the "IPython inline" mode,
which will make plots show up inline in the notebook. | %matplotlib inline
# Here we import the plotting functions
import matplotlib.pyplot as plt
# plotting a line
x = np.linspace(0, 10, 100)
plt.plot(x, np.sin(x));
# scatter-plot points
x = np.random.normal(size=500)
y = np.random.normal(size=500)
plt.scatter(x, y);
# showing images
x = np.linspace(1, 12, 100)
y = x[:, np.newaxis]
im = y * np.sin(x) * np.cos(y)
print(im.shape)
# imshow - note that origin is at the top-left by default!
plt.imshow(im);
# Contour plot - note that origin here is at the bottom-left by default!
plt.contour(im); | _doc/notebooks/sklearn_ensae_course/01_data_manipulation.ipynb | sdpython/ensae_teaching_cs | mit |
There are many, many more plot types available. One useful way to explore these is by
looking at the matplotlib gallery: http://matplotlib.org/gallery.html
You can test these examples out easily in the notebook: simply copy the Source Code
link on each page, and put it in a notebook using the %load magic.
For example: | # %load http://matplotlib.org/mpl_examples/pylab_examples/ellipse_collection.py
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.collections import EllipseCollection
x = np.arange(10)
y = np.arange(15)
X, Y = np.meshgrid(x, y)
XY = np.hstack((X.ravel()[:, np.newaxis], Y.ravel()[:, np.newaxis]))
ww = X/10.0
hh = Y/15.0
aa = X*9
fig, ax = plt.subplots()
ec = EllipseCollection(ww, hh, aa, units='x', offsets=XY,
transOffset=ax.transData)
ec.set_array((X + Y).ravel())
ax.add_collection(ec)
ax.autoscale_view()
ax.set_xlabel('X')
ax.set_ylabel('y')
cbar = plt.colorbar(ec)
cbar.set_label('X+Y'); | _doc/notebooks/sklearn_ensae_course/01_data_manipulation.ipynb | sdpython/ensae_teaching_cs | mit |
To quickly inspect the data we can export it as a dictionary of numpy arrays thanks to the AsNumpy RDataFrame method. Note that for each row, E is an array of values: | npy_dict = df.AsNumpy(["E"])
for row, vec in enumerate(npy_dict["E"]):
print(f"\nRow {row} contains:\n{vec}") | NCPSchool2021/RDataFrame/02-rdataframe-collections.ipynb | root-mirror/training | gpl-2.0 |
Define a new column with operations on RVecs | df1 = df.Define("good_pt", "sqrt(px*px + py*py)[E>100]") | NCPSchool2021/RDataFrame/02-rdataframe-collections.ipynb | root-mirror/training | gpl-2.0 |
sqrt(px*px + py*py)[E>100]:
* px, py and E are columns the elements of which are RVecs
* Operations on RVecs like sum, product, sqrt preserve the dimensionality of the array
* [E>100] selects the elements of the array that satisfy the condition
* E > 100: boolean expressions on RVecs such as E > 100 return a mask, that is an array with information on which values pass the selection (e.g. [0, 1, 0, 0] if only the second element satisfies the condition)
Now we can plot the newly defined column values in a histogram | c = ROOT.TCanvas()
h = df1.Histo1D(("pt", "pt", 16, 0, 4), "good_pt")
h.Draw()
c.Draw() | NCPSchool2021/RDataFrame/02-rdataframe-collections.ipynb | root-mirror/training | gpl-2.0 |
Base manifold (three dimensional)
Metric tensor (cartesian coordinates - norm = False) | from sympy import cos, sin, symbols
g3coords = (x,y,z) = symbols('x y z')
g3 = Ga('ex ey ez', g = [1,1,1], coords = g3coords,norm=False) # Create g3
(e_x,e_y,e_z) = g3.mv()
Math(r'g =%s' % latex(g3.g)) | examples/ipython/colored_christoffel_symbols.ipynb | arsenovic/galgebra | bsd-3-clause |
Two dimensioanal submanifold - Unit sphere
Basis not normalised | sp2coords = (theta, phi) = symbols(r'{\color{airforceblue}\theta} {\color{applegreen}\phi}', real = True)
sp2param = [sin(theta)*cos(phi), sin(theta)*sin(phi), cos(theta)]
sp2 = g3.sm(sp2param, sp2coords, norm = False) # submanifold
(etheta, ephi) = sp2.mv() # sp2 basis vectors
(rtheta, rphi) = sp2.mvr() # sp2 reciprocal basis vectors
sp2grad = sp2.grad
sph_map = [1, theta, phi] # Coordinate map for sphere of r = 1
Math(r'(\theta,\phi)\rightarrow (r,\theta,\phi) = %s' % latex(sph_map))
Math(r'e_\theta \cdot e_\theta = %s' % (etheta|etheta))
Math(r'e_\phi \cdot e_\phi = %s' % (ephi|ephi))
Math('g = %s' % latex(sp2.g))
Math(r'g^{-1} = %s' % latex(sp2.g_inv)) | examples/ipython/colored_christoffel_symbols.ipynb | arsenovic/galgebra | bsd-3-clause |
Christoffel symbols of the first kind: | Cf1 = sp2.Christoffel_symbols(mode=1)
Cf1 = permutedims(Array(Cf1), (2, 0, 1))
Math(r'\Gamma_{1, \alpha, \beta} = %s \quad \Gamma_{2, \alpha, \beta} = %s ' % (latex(Cf1[0, :, :]), latex(Cf1[1, :, :])))
Cf2 = sp2.Christoffel_symbols(mode=2)
Cf2 = permutedims(Array(Cf2), (2, 0, 1))
Math(r'\Gamma^{1}_{\phantom{1,}\alpha, \beta} = %s \quad \Gamma^{2}_{\phantom{2,}\alpha, \beta} = %s ' % (latex(Cf2[0, :, :]), latex(Cf2[1, :, :])))
F = sp2.mv('F','vector',f=True) #scalar function
f = sp2.mv('f','scalar',f=True) #vector function
Math(r'\nabla = %s' % sp2grad)
Math(r'\nabla f = %s' % (sp2.grad * f))
Math(r'F = %s' % F)
Math(r'\nabla F = %s' % (sp2.grad * F)) | examples/ipython/colored_christoffel_symbols.ipynb | arsenovic/galgebra | bsd-3-clause |
One dimensioanal submanifold
Basis not normalised | cir_th = phi = symbols(r'{\color{atomictangerine}\phi}',real = True)
cir_map = [pi/8, phi]
Math(r'(\phi)\rightarrow (\theta,\phi) = %s' % latex(cir_map))
cir1d = sp2.sm( cir_map , (cir_th,), norm = False) # submanifold
cir1dgrad = cir1d.grad
(ephi) = cir1d.mv()
Math(r'e_\phi \cdot e_\phi = %s' % latex(ephi[0] | ephi[0]))
Math('g = %s' % latex(cir1d.g))
h = cir1d.mv('h','scalar',f= True)
H = cir1d.mv('H','vector',f= True)
Math(r'\nabla = %s' % cir1dgrad)
Math(r'\nabla h = %s' %(cir1d.grad * h).simplify())
Math('H = %s' % H)
Math(r'\nabla H = %s' % (cir1d.grad * H).simplify()) | examples/ipython/colored_christoffel_symbols.ipynb | arsenovic/galgebra | bsd-3-clause |
Pandas Data Structures
Series
A Series is a single vector of data (like a NumPy array) with an index that labels each element in the vector. | counts = pd.Series([632, 1638, 569, 115])
counts | Day_01/01_Pandas/1. Introduction to Pandas.ipynb | kialio/gsfcpyboot | mit |
If an index is not specified, a default sequence of integers is assigned as the index. A NumPy array comprises the values of the Series, while the index is a pandas Index object. | counts.values
counts.index | Day_01/01_Pandas/1. Introduction to Pandas.ipynb | kialio/gsfcpyboot | mit |
We can assign meaningful labels to the index, if they are available: | bacteria = pd.Series([632, 1638, 569, 115],
index=['Firmicutes', 'Proteobacteria', 'Actinobacteria', 'Bacteroidetes'])
bacteria | Day_01/01_Pandas/1. Introduction to Pandas.ipynb | kialio/gsfcpyboot | mit |
These labels can be used to refer to the values in the Series. | bacteria['Actinobacteria']
bacteria[[name.endswith('bacteria') for name in bacteria.index]]
[name.endswith('bacteria') for name in bacteria.index] | Day_01/01_Pandas/1. Introduction to Pandas.ipynb | kialio/gsfcpyboot | mit |
Notice that the indexing operation preserved the association between the values and the corresponding indices.
We can still use positional indexing if we wish. | bacteria[0] | Day_01/01_Pandas/1. Introduction to Pandas.ipynb | kialio/gsfcpyboot | mit |
We can give both the array of values and the index meaningful labels themselves: | bacteria.name = 'counts'
bacteria.index.name = 'phylum'
bacteria | Day_01/01_Pandas/1. Introduction to Pandas.ipynb | kialio/gsfcpyboot | mit |
NumPy's math functions and other operations can be applied to Series without losing the data structure. | np.log(bacteria)
bacteria | Day_01/01_Pandas/1. Introduction to Pandas.ipynb | kialio/gsfcpyboot | mit |
We can also filter according to the values in the Series: | bacteria[bacteria>1000] | Day_01/01_Pandas/1. Introduction to Pandas.ipynb | kialio/gsfcpyboot | mit |
A Series can be thought of as an ordered key-value store. In fact, we can create one from a dict: | bacteria_dict = {'Firmicutes': 632, 'Proteobacteria': 1638, 'Actinobacteria': 569, 'Bacteroidetes': 115}
pd.Series(bacteria_dict) | Day_01/01_Pandas/1. Introduction to Pandas.ipynb | kialio/gsfcpyboot | mit |
Notice that the Series is created in key-sorted order.
If we pass a custom index to Series, it will select the corresponding values from the dict, and treat indices without corrsponding values as missing. Pandas uses the NaN (not a number) type for missing values. | bacteria2 = pd.Series(bacteria_dict, index=['Cyanobacteria','Firmicutes','Proteobacteria','Actinobacteria'])
bacteria2
bacteria2.isnull() | Day_01/01_Pandas/1. Introduction to Pandas.ipynb | kialio/gsfcpyboot | mit |
Critically, the labels are used to align data when used in operations with other Series objects: | bacteria + bacteria2 | Day_01/01_Pandas/1. Introduction to Pandas.ipynb | kialio/gsfcpyboot | mit |
Contrast this with NumPy arrays, where arrays of the same length will combine values element-wise; adding Series combined values with the same label in the resulting series. Notice also that the missing values were propogated by addition.
DataFrame
Inevitably, we want to be able to store, view and manipulate data that is multivariate, where for every index there are multiple fields or columns of data, often of varying data type.
A DataFrame is a tabular data structure, encapsulating multiple series like columns in a spreadsheet. Data are stored internally as a 2-dimensional object, but the DataFrame allows us to represent and manipulate higher-dimensional data. | data = pd.DataFrame({'value':[632, 1638, 569, 115, 433, 1130, 754, 555],
'patient':[1, 1, 1, 1, 2, 2, 2, 2],
'phylum':['Firmicutes', 'Proteobacteria', 'Actinobacteria',
'Bacteroidetes', 'Firmicutes', 'Proteobacteria', 'Actinobacteria', 'Bacteroidetes']})
data | Day_01/01_Pandas/1. Introduction to Pandas.ipynb | kialio/gsfcpyboot | mit |
Notice the DataFrame is sorted by column name. We can change the order by indexing them in the order we desire: | newdata = data[['phylum','value','patient']]
newdata | Day_01/01_Pandas/1. Introduction to Pandas.ipynb | kialio/gsfcpyboot | mit |
A DataFrame has a second index, representing the columns: | data.columns
newdata.columns | Day_01/01_Pandas/1. Introduction to Pandas.ipynb | kialio/gsfcpyboot | mit |
If we wish to access columns, we can do so either by dict-like indexing or by attribute: | data['value']
data.value
type(data.value)
type(data[['value']]) | Day_01/01_Pandas/1. Introduction to Pandas.ipynb | kialio/gsfcpyboot | mit |
Notice this is different than with Series, where dict-like indexing retrieved a particular element (row). If we want access to a row in a DataFrame, we index its ix attribute. | data.ix[3] | Day_01/01_Pandas/1. Introduction to Pandas.ipynb | kialio/gsfcpyboot | mit |
Alternatively, we can create a DataFrame with a dict of dicts: | data = pd.DataFrame({0: {'patient': 1, 'phylum': 'Firmicutes', 'value': 632},
1: {'patient': 1, 'phylum': 'Proteobacteria', 'value': 1638},
2: {'patient': 1, 'phylum': 'Actinobacteria', 'value': 569},
3: {'patient': 1, 'phylum': 'Bacteroidetes', 'value': 115},
4: {'patient': 2, 'phylum': 'Firmicutes', 'value': 433},
5: {'patient': 2, 'phylum': 'Proteobacteria', 'value': 1130},
6: {'patient': 2, 'phylum': 'Actinobacteria', 'value': 754},
7: {'patient': 2, 'phylum': 'Bacteroidetes', 'value': 555}})
data | Day_01/01_Pandas/1. Introduction to Pandas.ipynb | kialio/gsfcpyboot | mit |
We probably want this transposed: | data = data.T
data | Day_01/01_Pandas/1. Introduction to Pandas.ipynb | kialio/gsfcpyboot | mit |
Its important to note that the Series returned when a DataFrame is indexted is merely a view on the DataFrame, and not a copy of the data itself. So you must be cautious when manipulating this data: | vals = data.value
vals
vals[5] = 0
vals
data
vals = data.value.copy()
vals[5] = 1000
data | Day_01/01_Pandas/1. Introduction to Pandas.ipynb | kialio/gsfcpyboot | mit |
We can create or modify columns by assignment: | data.value[3] = 14
data
data['year'] = 2013
data | Day_01/01_Pandas/1. Introduction to Pandas.ipynb | kialio/gsfcpyboot | mit |
But note, we cannot use the attribute indexing method to add a new column: | data.treatment = 1
data
data.treatment | Day_01/01_Pandas/1. Introduction to Pandas.ipynb | kialio/gsfcpyboot | mit |
Specifying a Series as a new columns cause its values to be added according to the DataFrame's index: | treatment = pd.Series([0]*4 + [1]*2)
treatment
data['treatment'] = treatment
data | Day_01/01_Pandas/1. Introduction to Pandas.ipynb | kialio/gsfcpyboot | mit |
Other Python data structures (ones without an index) need to be the same length as the DataFrame: | month = ['Jan', 'Feb', 'Mar', 'Apr']
data['month'] = month
data['month'] = ['Jan']*len(data)
data | Day_01/01_Pandas/1. Introduction to Pandas.ipynb | kialio/gsfcpyboot | mit |
We can use del to remove columns, in the same way dict entries can be removed: | del data['month']
data | Day_01/01_Pandas/1. Introduction to Pandas.ipynb | kialio/gsfcpyboot | mit |
We can extract the underlying data as a simple ndarray by accessing the values attribute: | data.values | Day_01/01_Pandas/1. Introduction to Pandas.ipynb | kialio/gsfcpyboot | mit |
Notice that because of the mix of string and integer (and NaN) values, the dtype of the array is object. The dtype will automatically be chosen to be as general as needed to accomodate all the columns. | df = pd.DataFrame({'foo': [1,2,3], 'bar':[0.4, -1.0, 4.5]})
df.values | Day_01/01_Pandas/1. Introduction to Pandas.ipynb | kialio/gsfcpyboot | mit |
Pandas uses a custom data structure to represent the indices of Series and DataFrames. | data.index | Day_01/01_Pandas/1. Introduction to Pandas.ipynb | kialio/gsfcpyboot | mit |
Index objects are immutable: | data.index[0] = 15 | Day_01/01_Pandas/1. Introduction to Pandas.ipynb | kialio/gsfcpyboot | mit |
This is so that Index objects can be shared between data structures without fear that they will be changed. | bacteria2.index = bacteria.index
bacteria2 | Day_01/01_Pandas/1. Introduction to Pandas.ipynb | kialio/gsfcpyboot | mit |
Importing data
A key, but often under-appreciated, step in data analysis is importing the data that we wish to analyze. Though it is easy to load basic data structures into Python using built-in tools or those provided by packages like NumPy, it is non-trivial to import structured data well, and to easily convert this input into a robust data structure:
genes = np.loadtxt("genes.csv", delimiter=",", dtype=[('gene', '|S10'), ('value', '<f4')])
Pandas provides a convenient set of functions for importing tabular data in a number of formats directly into a DataFrame object. These functions include a slew of options to perform type inference, indexing, parsing, iterating and cleaning automatically as data are imported.
Let's start with some more bacteria data, stored in csv format. | !cat data/microbiome.csv | Day_01/01_Pandas/1. Introduction to Pandas.ipynb | kialio/gsfcpyboot | mit |
This table can be read into a DataFrame using read_csv: | mb = pd.read_csv("data/microbiome.csv")
mb | Day_01/01_Pandas/1. Introduction to Pandas.ipynb | kialio/gsfcpyboot | mit |
Notice that read_csv automatically considered the first row in the file to be a header row.
We can override default behavior by customizing some the arguments, like header, names or index_col. | pd.read_csv("data/microbiome.csv", header=None).head() | Day_01/01_Pandas/1. Introduction to Pandas.ipynb | kialio/gsfcpyboot | mit |
read_csv is just a convenience function for read_table, since csv is such a common format: | mb = pd.read_table("data/microbiome.csv", sep=',') | Day_01/01_Pandas/1. Introduction to Pandas.ipynb | kialio/gsfcpyboot | mit |
The sep argument can be customized as needed to accomodate arbitrary separators. For example, we can use a regular expression to define a variable amount of whitespace, which is unfortunately very common in some data formats:
sep='\s+'
For a more useful index, we can specify the first two columns, which together provide a unique index to the data. | mb = pd.read_csv("data/microbiome.csv", index_col=['Taxon','Patient'])
mb.head() | Day_01/01_Pandas/1. Introduction to Pandas.ipynb | kialio/gsfcpyboot | mit |
This is called a hierarchical index, which we will revisit later in the tutorial.
If we have sections of data that we do not wish to import (for example, known bad data), we can populate the skiprows argument: | pd.read_csv("data/microbiome.csv", skiprows=[3,4,6]).head() | Day_01/01_Pandas/1. Introduction to Pandas.ipynb | kialio/gsfcpyboot | mit |
Conversely, if we only want to import a small number of rows from, say, a very large data file we can use nrows: | pd.read_csv("data/microbiome.csv", nrows=4) | Day_01/01_Pandas/1. Introduction to Pandas.ipynb | kialio/gsfcpyboot | mit |
Alternately, if we want to process our data in reasonable chunks, the chunksize argument will return an iterable object that can be employed in a data processing loop. For example, our microbiome data are organized by bacterial phylum, with 15 patients represented in each: | data_chunks = pd.read_csv("data/microbiome.csv", chunksize=15)
mean_tissue = {chunk.Taxon[0]:chunk.Tissue.mean() for chunk in data_chunks}
mean_tissue | Day_01/01_Pandas/1. Introduction to Pandas.ipynb | kialio/gsfcpyboot | mit |
Most real-world data is incomplete, with values missing due to incomplete observation, data entry or transcription error, or other reasons. Pandas will automatically recognize and parse common missing data indicators, including NA and NULL. | !cat data/microbiome_missing.csv
pd.read_csv("data/microbiome_missing.csv").head(20) | Day_01/01_Pandas/1. Introduction to Pandas.ipynb | kialio/gsfcpyboot | mit |
Above, Pandas recognized NA and an empty field as missing data. | pd.isnull(pd.read_csv("data/microbiome_missing.csv")).head(20) | Day_01/01_Pandas/1. Introduction to Pandas.ipynb | kialio/gsfcpyboot | mit |
Unfortunately, there will sometimes be inconsistency with the conventions for missing data. In this example, there is a question mark "?" and a large negative number where there should have been a positive integer. We can specify additional symbols with the na_values argument: | pd.read_csv("data/microbiome_missing.csv", na_values=['?', -99999]).head(20) | Day_01/01_Pandas/1. Introduction to Pandas.ipynb | kialio/gsfcpyboot | mit |
These can be specified on a column-wise basis using an appropriate dict as the argument for na_values.
Microsoft Excel
Since so much financial and scientific data ends up in Excel spreadsheets (regrettably), Pandas' ability to directly import Excel spreadsheets is valuable. This support is contingent on having one or two dependencies (depending on what version of Excel file is being imported) installed: xlrd and openpyxl (these may be installed with either pip or easy_install).
Importing Excel data to Pandas is a two-step process. First, we create an ExcelFile object using the path of the file: | mb_file = pd.ExcelFile('data/microbiome/MID1.xls')
mb_file | Day_01/01_Pandas/1. Introduction to Pandas.ipynb | kialio/gsfcpyboot | mit |
Then, since modern spreadsheets consist of one or more "sheets", we parse the sheet with the data of interest: | mb1 = mb_file.parse("Sheet 1", header=None)
mb1.columns = ["Taxon", "Count"]
mb1.head() | Day_01/01_Pandas/1. Introduction to Pandas.ipynb | kialio/gsfcpyboot | mit |
There is now a read_excel convenience function in Pandas that combines these steps into a single call: | mb2 = pd.read_excel('data/microbiome/MID2.xls', sheetname='Sheet 1', header=None)
mb2.head() | Day_01/01_Pandas/1. Introduction to Pandas.ipynb | kialio/gsfcpyboot | mit |
There are several other data formats that can be imported into Python and converted into DataFrames, with the help of buitl-in or third-party libraries. These include JSON, XML, HDF5, relational and non-relational databases, and various web APIs. These are beyond the scope of this tutorial, but are covered in Python for Data Analysis.
Pandas Fundamentals
This section introduces the new user to the key functionality of Pandas that is required to use the software effectively.
For some variety, we will leave our digestive tract bacteria behind and employ some baseball data. | baseball = pd.read_csv("data/baseball.csv", index_col='id')
baseball.head() | Day_01/01_Pandas/1. Introduction to Pandas.ipynb | kialio/gsfcpyboot | mit |
Notice that we specified the id column as the index, since it appears to be a unique identifier. We could try to create a unique index ourselves by combining player and year: | player_id = baseball.player + baseball.year.astype(str)
baseball_newind = baseball.copy()
baseball_newind.index = player_id
baseball_newind.head() | Day_01/01_Pandas/1. Introduction to Pandas.ipynb | kialio/gsfcpyboot | mit |
This looks okay, but let's check: | baseball_newind.index.is_unique | Day_01/01_Pandas/1. Introduction to Pandas.ipynb | kialio/gsfcpyboot | mit |
So, indices need not be unique. Our choice is not unique because some players change teams within years. | pd.Series(baseball_newind.index).value_counts() | Day_01/01_Pandas/1. Introduction to Pandas.ipynb | kialio/gsfcpyboot | mit |
The most important consequence of a non-unique index is that indexing by label will return multiple values for some labels: | baseball_newind.ix['wickmbo012007'] | Day_01/01_Pandas/1. Introduction to Pandas.ipynb | kialio/gsfcpyboot | mit |
We will learn more about indexing below.
We can create a truly unique index by combining player, team and year: | player_unique = baseball.player + baseball.team + baseball.year.astype(str)
baseball_newind = baseball.copy()
baseball_newind.index = player_unique
baseball_newind.head()
baseball_newind.index.is_unique | Day_01/01_Pandas/1. Introduction to Pandas.ipynb | kialio/gsfcpyboot | mit |
We can create meaningful indices more easily using a hierarchical index; for now, we will stick with the numeric id field as our index.
Manipulating indices
Reindexing allows users to manipulate the data labels in a DataFrame. It forces a DataFrame to conform to the new index, and optionally, fill in missing data if requested.
A simple use of reindex is to alter the order of the rows: | baseball.reindex(baseball.index[::-1]).head() | Day_01/01_Pandas/1. Introduction to Pandas.ipynb | kialio/gsfcpyboot | mit |
Notice that the id index is not sequential. Say we wanted to populate the table with every id value. We could specify and index that is a sequence from the first to the last id numbers in the database, and Pandas would fill in the missing data with NaN values: | id_range = range(baseball.index.values.min(), baseball.index.values.max())
baseball.reindex(id_range).head() | Day_01/01_Pandas/1. Introduction to Pandas.ipynb | kialio/gsfcpyboot | mit |
Missing values can be filled as desired, either with selected values, or by rule: | baseball.reindex(id_range, method='ffill', columns=['player','year']).head()
baseball.reindex(id_range, fill_value='mr.nobody', columns=['player']).head() | Day_01/01_Pandas/1. Introduction to Pandas.ipynb | kialio/gsfcpyboot | mit |
Keep in mind that reindex does not work if we pass a non-unique index series.
We can remove rows or columns via the drop method: | baseball.shape
baseball.drop([89525, 89526])
baseball.drop(['ibb','hbp'], axis=1) | Day_01/01_Pandas/1. Introduction to Pandas.ipynb | kialio/gsfcpyboot | mit |
Indexing and Selection
Indexing works analogously to indexing in NumPy arrays, except we can use the labels in the Index object to extract values in addition to arrays of integers. | # Sample Series object
hits = baseball_newind.h
hits
# Numpy-style indexing
hits[:3]
# Indexing by label
hits[['womacto01CHN2006','schilcu01BOS2006']] | Day_01/01_Pandas/1. Introduction to Pandas.ipynb | kialio/gsfcpyboot | mit |
We can also slice with data labels, since they have an intrinsic order within the Index: | hits['womacto01CHN2006':'gonzalu01ARI2006']
hits['womacto01CHN2006':'gonzalu01ARI2006'] = 5
hits | Day_01/01_Pandas/1. Introduction to Pandas.ipynb | kialio/gsfcpyboot | mit |
In a DataFrame we can slice along either or both axes: | baseball_newind[['h','ab']]
baseball_newind[baseball_newind.ab>500] | Day_01/01_Pandas/1. Introduction to Pandas.ipynb | kialio/gsfcpyboot | mit |
The indexing field ix allows us to select subsets of rows and columns in an intuitive way: | baseball_newind.ix['gonzalu01ARI2006', ['h','X2b', 'X3b', 'hr']]
baseball_newind.ix[['gonzalu01ARI2006','finlest01SFN2006'], 5:8]
baseball_newind.ix[:'myersmi01NYA2006', 'hr'] | Day_01/01_Pandas/1. Introduction to Pandas.ipynb | kialio/gsfcpyboot | mit |
Similarly, the cross-section method xs (not a field) extracts a single column or row by label and returns it as a Series: | baseball_newind.xs('myersmi01NYA2006') | Day_01/01_Pandas/1. Introduction to Pandas.ipynb | kialio/gsfcpyboot | mit |
Operations
DataFrame and Series objects allow for several operations to take place either on a single object, or between two or more objects.
For example, we can perform arithmetic on the elements of two objects, such as combining baseball statistics across years: | hr2006 = baseball[baseball.year==2006].xs('hr', axis=1)
hr2006.index = baseball.player[baseball.year==2006]
hr2007 = baseball[baseball.year==2007].xs('hr', axis=1)
hr2007.index = baseball.player[baseball.year==2007]
hr2006 = pd.Series(baseball.hr[baseball.year==2006].values, index=baseball.player[baseball.year==2006])
hr2007 = pd.Series(baseball.hr[baseball.year==2007].values, index=baseball.player[baseball.year==2007])
hr_total = hr2006 + hr2007
hr_total | Day_01/01_Pandas/1. Introduction to Pandas.ipynb | kialio/gsfcpyboot | mit |
Pandas' data alignment places NaN values for labels that do not overlap in the two Series. In fact, there are only 6 players that occur in both years. | hr_total[hr_total.notnull()] | Day_01/01_Pandas/1. Introduction to Pandas.ipynb | kialio/gsfcpyboot | mit |
While we do want the operation to honor the data labels in this way, we probably do not want the missing values to be filled with NaN. We can use the add method to calculate player home run totals by using the fill_value argument to insert a zero for home runs where labels do not overlap: | hr2007.add(hr2006, fill_value=0) | Day_01/01_Pandas/1. Introduction to Pandas.ipynb | kialio/gsfcpyboot | mit |
Operations can also be broadcast between rows or columns.
For example, if we subtract the maximum number of home runs hit from the hr column, we get how many fewer than the maximum were hit by each player: | baseball.hr - baseball.hr.max() | Day_01/01_Pandas/1. Introduction to Pandas.ipynb | kialio/gsfcpyboot | mit |
Or, looking at things row-wise, we can see how a particular player compares with the rest of the group with respect to important statistics | baseball.ix[89521]["player"]
stats = baseball[['h','X2b', 'X3b', 'hr']]
diff = stats - stats.xs(89521)
diff[:10] | Day_01/01_Pandas/1. Introduction to Pandas.ipynb | kialio/gsfcpyboot | mit |
We can also apply functions to each column or row of a DataFrame | stats.apply(np.median)
stat_range = lambda x: x.max() - x.min()
stats.apply(stat_range) | Day_01/01_Pandas/1. Introduction to Pandas.ipynb | kialio/gsfcpyboot | mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.