I recently found this url The Big List of D3.js Examples. As d3.js is getting popular - their website is pretty nice -, I was curious if I could easily use it through Python. After a couple of searches (many in fact), I discovered vincent and some others. It ended up doing a quick review. Every script was tested with Python 3.
Contents:
Use of IPython (qt)console
The QtConsole looks like a command line window but is able to display images inline using matplotlib:
La Khan Academy propose des leçons de 10 minutes sur de nombreux sujets parmi lesquels Python. Voici quelques pointeurs (en anglais):
2014-05-28 - Les liens vers la Khan Academy sont cassés et je n'ai pas réussi à les retrouver sur leur site. Ils sont néanmoins accessibles sur YouTube : listes. Les autres vidéos sont accessibles depuis les suggestions.
I often had to implement an edit distance and I most of time chose to use uniform weights : every modification costs 1. That's the easy solution. However, I was looking for a quick way to give different weights to every comparison between twwo characters.
So I went to the site Gutenberg and downloaded a few texts. I then did the following:
L'exercice est le suivant : on récupère deux tableaux depuis le site http://www.data.gouv.fr/. On récupère les deux fichiers suivants :
Ministère Libellé Catégorie d'emploi Emploi ETPPLF 1 Affaires étrangères 1101 Titulaires et CDI en administration centrale 3 059 1 Affaires étrangères 1102 Titulaires et CDI dans le réseau 2 895 1 Affaires étrangères 1103 CDD et volontaires internationaux 2 877 1 Affaires étrangères 1104 Militaires 712 1 Affaires étrangères 1105 Agents de droit local 4 962 ...
On cherche à mesurer l'évolution des effectifs entre ces deux années même si la liste des ministères et des catégories évolue.
On est amené presque tous les jours à compter les pièces dans son porte-monnaie pour payer la baguette, le fromage ou la bouteille de vin. Comment écrire un algorithme qui donne la liste des pièces qu'il faut piocher dans son porte-monnaie pour payer ? On s'intéressera seulement au cas où on cherche à composer le montant juste. Cela revient à chercher un sous-ensemble S de pièces dans l'ensemble P des pièces du portefeuille pour composer le montant M :
Une façon naïve de construire l'ensemble S est de procéder comme on le fait souvent, c'est-à-dire à prendre la pièce la plus grosse, de voir si elle dépasse le montant N puis de passer à la seconde plus grande et ainsi de suite. Soit :
Lorsqu'on apprend à programmer, on a souvent une idée précise de l'objectif à atteindre et pourtant, on reste perplexe devant l'écran ne sachant pas par où commencer. Par exemple, si on dispose d'une matrice de trois colonnes :
x | y | poids |
A | C | 3 |
A | D | 1 |
A | E | 4 |
B | D | 6 |
Par exemple, si x=A et y=D, on aura 1 / (3 + 1 + 4) = 0.125. Maintenant, comment s'y prend-on ?
Tout d'abord, on cherche à calculer un ratio de trucs qui ne sont pas des nombres entiers. Un dictionnaire est tout indiqué pour stocker ces trucs car il permet d'associer n'importe quoi (valeur) à presque n'importe quoi (clé). La valeur est une somme d'entiers, la clé est un couple de lettres ou une lettre. Sans me soucier des petits détails, voilà ce que j'ai envie d'écrire comme premier jet :
l = [ ['A','B', 3], ['A','C', 1], ['A','E', 4], ['B','D', 6], ] def transition(l): d = {} for x,y,n in l : d [x,y] += n # erreur ici : KeyError: ('A', 'B') d [x] += n for x,y in d : d[x,y] /= d [x] return d print (transition(l))
Bien sûr ça ne marche pas (voir l'erreur ci-dessus). Mais j'ai foi en moi. La logique est bonne. Lorsque j'écris d [a,b] += n, je suppose que le couple (x,y) existe dans le dictionnaire même la toute première fois. Et c'est pas possible ! Il est vide au début.
When I try to avoid coding and to use existing tools, I usually decompose my problem in smaller ones I think people already solved. I usually skip the documentation until I find an example for each of them. That's how I proceed to use pandas. I imagine how I would do it using SQL and I try to write it using this module. My problem was the following one:
SELECT location, MIN(commute) AS minc, MAX(commute) AS maxc FROM data
Which I was able to solve this way (after a couple of tries and a glass of wine to avoid losing my temper):
data = [ { "name":"hugo", "location":"paris", "commute":55 }, { "name":"marcel", "location":"paris", "commute":45 }, { "name":"jack", "location":"lyon", "commute":25 }, { "name":"hugo", "location":"lyon", "commute":20 }, ] df = pandas.DataFrame(data) agg = df.groupby ( "location", as_index=False).agg ( { "commute": [ ("minc",min), ("maxc", max) ] } ) # first glass of wine print (agg)
Then, I wanted to write this:
SELECT A.*, B.minc, B.maxc FROM data AS A INNER JOIN ( SELECT location, MIN(commute) AS minc, MAX(commute) AS maxc FROM data) AS B
Which I converted into after a second glass of wine:
agg = df.groupby ( "location", as_index=False).agg ( { "commute": [ ("minc",min), ("maxc", max) ] } ) agg.columns = ["minc", "maxc"] # the second glass of wine join = df.merge (agg, left_on="location", right_on = "location") print (join)
But you could write it that way:
agg = df.groupby ( "location").agg ( { "commute": [ ("minc",min), ("maxc", max) ] } ) agg.columns=["minc","maxc"] join = df.merge (agg, left_on="location", right_index= True) print (join)
Last precision: the instruction agg.columns=["minc","maxc"] rename the column name. However, it works in this case just because we aggregated only one column (commute). When several columns are aggregated, the order of the column in the resulting matrix is not always the same. So do not do the following:
def sums(l) : return ",".join(l) agg = df.groupby ( "location", as_index=False).agg ( { "name":sums, "commute": [ ("minc",min), ("maxc", max) ] } ) agg.columns=["name","minc","maxc"] # glass of whisky
I often get frustrated about tools, it takes me so many tries to get the data the way I want before I start working on an algorithm using them. Then, you try to apply it on a much bigger dataset and it fails for a couple of bad rows which cannot be parsed because of a string including tabs. After, I got the accent problem... I hate those days.
I was writing a simple GUI in Python, a button start to start a function from a thread, another one to stop the execution. I then realized my program did not stop.
import threading, time class MyThread(threading.Thread): def run(self): while True: time.sleep(1) th = MyThread() th.start()
There are two ways to avoid that issue. The first one is to set up daemon to True.
th = MyThread() th.daemon = True th.start()
The second way is to use a kind of hidden function _stop(not documented). But this function might disappear in the next version of python.
th = MyThread() th.start() th._stop()