issue142:python
Différences
Ci-dessous, les différences entre deux révisions de la page.
Les deux révisions précédentesRévision précédenteProchaine révision | Révision précédente | ||
issue142:python [2019/02/24 19:49] – d52fr | issue142:python [2019/03/06 17:42] (Version actuelle) – andre_domenech | ||
---|---|---|---|
Ligne 4: | Ligne 4: | ||
I'm going to try to show you how to use Pandas and Python, how to deal with data without ever having to open the dataset in a spreadsheet even if there are some cells that don't contain good data, using some of the tricks we learned over the last two months, and giving you some new skills at the same time.** | I'm going to try to show you how to use Pandas and Python, how to deal with data without ever having to open the dataset in a spreadsheet even if there are some cells that don't contain good data, using some of the tricks we learned over the last two months, and giving you some new skills at the same time.** | ||
+ | |||
+ | Quand les enfants apprennent-ils vraiment des mots ? | ||
+ | |||
+ | Ce mois-ci, nous allons regarder un jeu de données différent. Celui que nous avons utilisé le mois dernier était, en majeure partie, parfait et complet. Cependant, ce n'est pas comme ça que ça marche dans le monde réel. Des données manqueront dans des champs, ou n' | ||
+ | |||
+ | Je vais essayer de vous montrer comment utiliser Pandas et Python, comment traiter les données sans jamais devoir ouvrir le jeu de données dans un tableur - même si certaines cellules ne contiennent pas des données correctes -, en utilisant quelques astuces que nous avons apprises dans les deux derniers mois, et en vous donnant en même temps quelques nouvelles compétences. | ||
**We' | **We' | ||
If you open ' | If you open ' | ||
+ | |||
+ | Nous utiliserons un jeu de données avec des données manquantes. Ce jeu de données peut être trouvé sur kaggle.com sous l' | ||
+ | |||
+ | Si vous ouvrez le fichier « main_data.csv » dans votre éditeur de texte favori, vous verrez quelque chose comme ce qui est présenté ci-dessous. | ||
**I'm sure you realize that I'm showing only the first 5 lines of the file here, but it gives you a pretty good idea of what we will be looking at. If you have never looked at a .csv file in a text editor before, you will see that (in this case) the first line shows the names of each column, separated by commas, and that there will be 11 columns of data. You can also scroll down to the bottom and see that there are 732 lines, which means that there are 731 lines (rows) of data. | **I'm sure you realize that I'm showing only the first 5 lines of the file here, but it gives you a pretty good idea of what we will be looking at. If you have never looked at a .csv file in a text editor before, you will see that (in this case) the first line shows the names of each column, separated by commas, and that there will be 11 columns of data. You can also scroll down to the bottom and see that there are 732 lines, which means that there are 731 lines (rows) of data. | ||
Ligne 14: | Ligne 24: | ||
Next page, top right, is the breakdown of the columns and their meanings.** | Next page, top right, is the breakdown of the columns and their meanings.** | ||
+ | |||
+ | Je suis sûr que vous réalisez que je ne vous ai montré ici que les 5 premières lignes du fichier, mais cela vous donne une idée assez bonne de ce que nous regarderons. Si vous n'avez jamais vu de fichier .csv dans un éditeur de texte, vous verrez que (dans ce cas-ci) la première ligne montre les noms des colonnes, séparés par des virgules, et qu'il y aura 11 colonnes de données. Vous pouvez aussi descendre vers le bas de la liste et voir qu'il y a 732 lignes, ce qui veut dire 731 lignes de données. | ||
+ | |||
+ | Si vous regardez la quatrième ligne du fichier, vous verrez « #N/A » dans l' | ||
+ | |||
+ | À la page suivante, en haut à droite, sont présentés les entêtes de colonnes et leur signification. | ||
**So for this particular article, we will be interested in the following columns... | **So for this particular article, we will be interested in the following columns... | ||
Ligne 36: | Ligne 52: | ||
print(df.isnull().sum(axis=0))** | print(df.isnull().sum(axis=0))** | ||
+ | |||
+ | Bien ! Pour cet article précis, nous nous intéresserons aux colonnes suivantes... | ||
+ | |||
+ | « Word_NW », « Translation », « AoA », « VSoA », « Lex_cat », « Freq », « CDS_freq » | ||
+ | |||
+ | où se trouvent le mot norvégien, sa traduction en anglais, l'âge de l' | ||
+ | |||
+ | Maintenant que nous savons ce que nous avons, et ce qui va nous intéresser, | ||
+ | |||
+ | import pandas as pd | ||
+ | |||
+ | csvfile = ' | ||
+ | |||
+ | rawdata = pd.read_csv(csvfile) | ||
+ | |||
+ | # Créer notre DataFrame simple du début | ||
+ | |||
+ | df = pd.DataFrame(rawdata) | ||
+ | |||
+ | Maintenant que notre DataFrame est en place, nous devons connaître jusqu' | ||
+ | |||
+ | print(df.isnull().sum(axis=0)) | ||
**I went to the Internet to get an easy way to explain the ' | **I went to the Internet to get an easy way to explain the ' | ||
Ligne 56: | Ligne 94: | ||
Now, the next question would be what to do with those null values. We can simply replace the null values with the mean or average of the " | Now, the next question would be what to do with those null values. We can simply replace the null values with the mean or average of the " | ||
- | **So, rather than mess with our main DataFrame, we'll create one that contains only the columns we are interested in, then fix the data there. First, we'll create a list of the column names we are interested in... | + | Je suis allé sur Internet pour trouver une explication simple du paramètre « axis » et, grâce à un message sur StackOverFlow, la réponse « facile » est que axis=0 est l'ensemble des données de toutes les lignes dans chaque colonne et que axis=1 est celui des données de toutes les colonnes dans chaque ligne. Ainsi, la requête signifie : donnez-moi la somme de toutes les valeurs nulles de chaque colonne de notre Dataframe. |
+ | Cette « requête » nous donne la sortie suivante : | ||
+ | ID_CDI_I | ||
+ | ID_CDI_II | ||
+ | Word_NW | ||
+ | Word_CDI | ||
+ | Translation | ||
+ | AoA 36 | ||
+ | VSoA 27 | ||
+ | Lex_cat | ||
+ | Broad_lex | ||
+ | Freq 10 | ||
+ | CDS_freq | ||
+ | dtype: int64 | ||
+ | |||
+ | Maintenant, la question suivante est : que faire de ces valeurs nulles ? Nous pouvons simplement remplacer les valeurs nulles par la médiane ou la moyenne des valeurs « utiles » dans chaque colonne numérique qui nous intéresse, et par « inconnu » dans les colonnes de texte. Ça faussera un peu les données, mais nous devrions pouvoir vivre avec. | ||
+ | |||
+ | **So, rather than mess with our main DataFrame, we'll create one that contains only the columns we are interested in, then fix the data there. First, we'll create a list of the column names we are interested in... | ||
cols_to_use = [' | cols_to_use = [' | ||
Ligne 75: | Ligne 130: | ||
5434: SettingWithCopyWarning: | 5434: SettingWithCopyWarning: | ||
+ | |||
+ | Aussi, au lieu d' | ||
+ | |||
+ | cols_to_use = [' | ||
+ | |||
+ | Maintenant, créons une nouvelle DataFrame avec ces seules colonnes : | ||
+ | |||
+ | df2 = df[cols_to_use] | ||
+ | |||
+ | print(df2) | ||
+ | |||
+ | Ensuite, nous pouvons corriger les valeurs nulles dans les colonnes numériques. | ||
+ | |||
+ | df2[' | ||
+ | |||
+ | Cependant, ceci nous donne un avertissement : | ||
+ | |||
+ | 5434: SettingWithCopyWarning: | ||
**See the caveats in the documentation: | **See the caveats in the documentation: | ||
- | | + | |
+ | self._update_inplace(new_data) | ||
This is due to what is called a chained assignment. Now, we know this is a copy that we are dealing with, so we can safely thank Pandas for the warning, and run the command again. It will work this time. Now do the rest of the numerical columns... | This is due to what is called a chained assignment. Now, we know this is a copy that we are dealing with, so we can safely thank Pandas for the warning, and run the command again. It will work this time. Now do the rest of the numerical columns... | ||
Ligne 94: | Ligne 168: | ||
However, if we are running this in script from an IDE, this will fail and only the last 5 commands will work. There is a command that we could use...** | However, if we are running this in script from an IDE, this will fail and only the last 5 commands will work. There is a command that we could use...** | ||
+ | |||
+ | Voyez les mises en garde dans la documentation : http:// | ||
+ | |||
+ | self._update_inplace(new_data) | ||
+ | |||
+ | Ceci est dû à ce qui est appelé une affectation en chaîne. Nous savons que c'est avec une copie que nous allons travailler ; aussi, nous pouvons sans risque remercier Pandas pour son avertissement, | ||
+ | |||
+ | df2[' | ||
+ | |||
+ | df2[' | ||
+ | |||
+ | df2[' | ||
+ | |||
+ | df2[' | ||
+ | |||
+ | Et saisissons « unknown » dans la colonne « lex_cat ». | ||
+ | |||
+ | df2[' | ||
+ | |||
+ | Cependant, si nous lançons ceci dans un script depuis un environnement de développement, | ||
**df2.is_copy = False | **df2.is_copy = False | ||
Ligne 108: | Ligne 202: | ||
Again, it WILL work today, but we don't know for how long. So, the easiest way to work around this is to turn off the warnings all together, again, for use in a script.** | Again, it WILL work today, but we don't know for how long. So, the easiest way to work around this is to turn off the warnings all together, again, for use in a script.** | ||
+ | |||
+ | df2.is_copy = False | ||
+ | |||
+ | Mais, elle est maintenant obsolète ; elle fonctionnera éventuellement aujourd' | ||
+ | |||
+ | site-packages/ | ||
+ | |||
+ | object.__getattribute__(self, | ||
+ | |||
+ | site-packages/ | ||
+ | |||
+ | | ||
+ | |||
+ | À nouveau, cela fonctionne bien aujourd' | ||
**pd.set_option(' | **pd.set_option(' | ||
Ligne 127: | Ligne 235: | ||
Now, finally, we have mostly clean data that we can work with. Make your terminal pretty wide so we can see all our data at one time (next page, top) and let's do our first query of the DataFrame and find out how many words the typical Norwegian child knows by the age of 18 months and what they are...** | Now, finally, we have mostly clean data that we can work with. Make your terminal pretty wide so we can see all our data at one time (next page, top) and let's do our first query of the DataFrame and find out how many words the typical Norwegian child knows by the age of 18 months and what they are...** | ||
+ | |||
+ | pd.set_option(' | ||
+ | |||
+ | Cela étant dit, n' | ||
+ | |||
+ | Enfin, assurez-vous que nous avons tout traité en lançant à nouveau notre requête de somme : | ||
+ | |||
+ | print(df2.isnull().sum(axis=0)) | ||
+ | |||
+ | Word_NW | ||
+ | Translation | ||
+ | AoA 0 | ||
+ | VSoA 0 | ||
+ | Lex_cat | ||
+ | Freq 0 | ||
+ | CDS_freq | ||
+ | dtype: int64 | ||
+ | |||
+ | Maintenant, enfin, nous avons presque entièrement nettoyé les données avec lesquelles nous voulons travailler. Assurez-vous que votre terminal est grandement ouvert de sorte que vous puissiez voir toutes nos données d'un coup (page suivante, en haut) et faisons notre première requête sur la DataFrame pour découvrir combien de mots, et lesquels, un enfant norvégien typique connaît à l'age de 18 mois : | ||
**print(df2[df2.AoA < 18]) | **print(df2[df2.AoA < 18]) | ||
Ligne 139: | Ligne 266: | ||
So all you Daddies out there can take heart that your name is (on average) the third word a child learns, and don't let the fact that ' | So all you Daddies out there can take heart that your name is (on average) the third word a child learns, and don't let the fact that ' | ||
+ | |||
+ | print(df2[df2.AoA < 18]) | ||
+ | |||
+ | C'est plutôt sympa, mais ça serait mieux si la sortie était triée d' | ||
+ | |||
+ | print(df2[df2.AoA < 18].sort_values(' | ||
+ | |||
+ | C'est beaucoup mieux. Ainsi, entre 12 et 13 mois, l' | ||
+ | |||
+ | print(df2[df2.AoA < 18].sort_values([' | ||
+ | |||
+ | Comme ça, vous les papas qui traînez par ici, vous pouvez être rassurés car votre nom est (en moyenne) le troisième mot que l' | ||
**To make life easier for you all, I've created a full script that does everything we just did and threw in some wait-for-keypress statements, so you can visualize the data. It is on Pastebin at https:// | **To make life easier for you all, I've created a full script that does everything we just did and threw in some wait-for-keypress statements, so you can visualize the data. It is on Pastebin at https:// | ||
I'll leave you with this information and let you experiment on your own. Next time, we'll dust off some of our Page skills and create a GUI that will make it easier to play with data using a very powerful custom widget called ' | I'll leave you with this information and let you experiment on your own. Next time, we'll dust off some of our Page skills and create a GUI that will make it easier to play with data using a very powerful custom widget called ' | ||
+ | |||
+ | Pour vous simplifier la vie, j'ai créé un script complet qui fait tout ce que nous venons de faire et j'ai mis dedans quelques déclarations attendre-l' | ||
+ | |||
+ | Je vous quitte avec cette information et vous laisse faire vos propres expériences. La prochaine fois, nous allons dépoussiérer quelques-unes de nos connaissances sur Page et créer une interface utilisateur graphique (GUI) qui facilitera les essais sur les données en utilisant un très puissant gadget personnalisé appelé « pandastable ». Jusque-là, amusez-vous bien et continuez à apprendre. | ||
+ | |||
+ | |||
+ | **//Page 21, encart du haut à droite :// | ||
+ | |||
+ | Main data | ||
+ | ID_CDI_I: Word ID from the Norwegian adaptation of the MacArthur-Bates Communicative Development Inventories, | ||
+ | ID_CDI_II: Word ID from the Norwegian adaptation of the MacArthur-Bates Communicative Development Inventories, | ||
+ | Word_NW: The word in Norwegian | ||
+ | Word_CDI: The form of the word found in the Norwegian adaptation of the MacArthur-Bates Communicative Development Inventories | ||
+ | Translation: | ||
+ | AoA: how old a child generally is was when they learn this word, in months ( Estimated from the MacArthur-Bates Communicative Development Inventories) | ||
+ | VSoA: how many other words a child generally knows when they learn this word ( rounded up to the nearest 10) | ||
+ | Lex_cat: the specific part of speech of the word | ||
+ | Broad_lex: the broad part of speech of the word | ||
+ | Freq: a measure of how commonly this word occurs in Norwegian | ||
+ | CDS_freq: a measure of how commonly this word occurs when a Norwegian adult is talking to a Norwegian child** | ||
+ | |||
+ | //Page 21, traduction de l' | ||
+ | |||
+ | Données principales | ||
+ | ID_CDI_I: Identifiant de mot dans l' | ||
+ | ID_CDI_II: Identifiant de mot dans l' | ||
+ | Word_NW: Le mot en norvégien | ||
+ | Word_CDI: La forme du mot trouvée dans l' | ||
+ | Translation: | ||
+ | AoA: L'âge qu'a, en général, un enfant quand il apprend ce mot, en mois (estimation d' | ||
+ | VSoA: Nombre d' | ||
+ | Lex_cat: La nature grammaticale précise du mot | ||
+ | Broad_lex: La catégorie grammaticale du mot | ||
+ | Freq: Mesure de la fréquence d' | ||
+ | CDS_freq: Mesure de la fréquence d' | ||
issue142/python.1551034173.txt.gz · Dernière modification : 2019/02/24 19:49 de d52fr