Outils pour utilisateurs

Outils du site


issue140:python

Différences

Ci-dessous, les différences entre deux révisions de la page.

Lien vers cette vue comparative

Prochaine révision
Révision précédente
issue140:python [2018/12/28 18:08] – créée auntieeissue140:python [2019/01/08 16:16] (Version actuelle) auntiee
Ligne 1: Ligne 1:
-Pandas and Python and Code ... Oh My!+**Pandas and Python and Code ... Oh My!
  
 I try to keep abreast of new happenings in the Python and programming worlds in general.  Lately, I have been seeing a number of Python articles having to do with Data Science or Machine Learning that involve a Python library called Pandas.  I'd heard of it before, but never took the time to find out more about it.  Recently, I learned about it, and I am glad I did! I try to keep abreast of new happenings in the Python and programming worlds in general.  Lately, I have been seeing a number of Python articles having to do with Data Science or Machine Learning that involve a Python library called Pandas.  I'd heard of it before, but never took the time to find out more about it.  Recently, I learned about it, and I am glad I did!
Ligne 10: Ligne 10:
 • NumPy 1.9.0 or higher • NumPy 1.9.0 or higher
 • python-dateutil 2.5.0 or higher • python-dateutil 2.5.0 or higher
 +• pytz**
 +
 +Pandas et Python et Code ... Oh mon D... !
 +
 +En général, j'essaie de me tenir au courant des nouveautés dans les mondes de Python et de la programmation. Récemment, j'ai vu bon nombre d'articles sur Python au sujet de la Science des données et l'apprentissage des machines, qui utilisaient une bibliothèque Python appelée Pandas. J'en avais entendu parlé avant, mais je n'avais jamais pris le temps d'en savoir plus à son sujet. Récemment, je me suis renseigné et je suis content de l'avoir fait !
 +
 +Pandas, pour citer leur propre page Web, « est une bibliothèque Open Source, sous licence BSD, fournissant des outils pour les structures de données et leur analyse, à haute performance et faciles à utiliser, pour le langage de programmation Python. »
 +
 +Vous pouvez en découvrir beaucoup plus à son sujet sur https://pandas.pydata.org/. Il y a une quantité d'informations sur Internet à son sujet. Pour l'installer, vous pouvez faire un pip install pandas. Il y a, bien sûr, des dépendances pour Pandas. Ce sont :
 +• Python 2.7 ou + (au 1er janvier 2019, elle ne marchera que sous Python 3.5 ou +)
 +• setuptools 24.2.0 ou +
 +• NumPy 1.9.0 ou +
 +• python-dateutil 2.5.0 ou +
 • pytz • pytz
  
-So, given that Pandas is such an important library for Data Science, I plan to spend a few articles on it.  Now, I am not going to try to teach you a large amount about Pandas in this quick article.  I'm only going to try to show you some of the neat things that Pandas can do.  We'll go into Pandas in depth in later articles.+**So, given that Pandas is such an important library for Data Science, I plan to spend a few articles on it.  Now, I am not going to try to teach you a large amount about Pandas in this quick article.  I'm only going to try to show you some of the neat things that Pandas can do.  We'll go into Pandas in depth in later articles.
  
 Pandas can deal with three different types of data structures -  Pandas can deal with three different types of data structures - 
Ligne 19: Ligne 32:
 • Panel • Panel
  
-A Series data structure is a 1D labeled array which is size-immutable and contains homogeneous data (same data type).  A DataFrame structure is a 2D labeled tabular structure which is size-mutable, which contains heterogeneous data (data of different types) and is a container for a Series structure.  A Panel is a 3D labeled size-mutable array which contains heterogeneous data and is a container for a DataFrame structure.  All Pandas data structures are value mutable (can be changed).  Size-mutable is only available to DataFrames and Panel structures.+A Series data structure is a 1D labeled array which is size-immutable and contains homogeneous data (same data type).  A DataFrame structure is a 2D labeled tabular structure which is size-mutable, which contains heterogeneous data (data of different types) and is a container for a Series structure.  A Panel is a 3D labeled size-mutable array which contains heterogeneous data and is a container for a DataFrame structure.  All Pandas data structures are value mutable (can be changed).  Size-mutable is only available to DataFrames and Panel structures.**
  
-All of that dry information is nice, but to really appreciate how easy Pandas makes dealing with data, let's play a little bit.  One of the best things about Pandas is that many times, you can do much of the work in a Python shell.+Ainsi, étant donné que Pandas est une bibliothèque aussi importante pour la Science des données, je prévois de faire quelques articles dessus. Et je ne vais pas essayer de vous apprendre une part étendue de Pandas dans ce court article. Je vais juste essayer de vous montrer quelques-uns des trucs chouettes que Pandas peut faire. Nous approfondirons Pandas dans les prochains articles. 
 + 
 +Pandas peut gérer trois types de structures de données : 
 +• Series 
 +• DataFrame 
 +• Panel 
 + 
 +Une structure de données « Series » est un tableau étiqueté à une dimension de taille non modifiable et qui contient des données homogènes (des données de même type). Une structure « Dataframe » est une structure tabulaire étiquetée à deux dimensions de taille modifiable, qui contient des données hétérogènes (des données de types différents) et qui est un conteneur pour une structure Series. Un « Panel » est un tableau étiqueté en trois dimensions de taille modifiable qui contient des données hétérogènes et qui est un conteneur pour une structure Dataframe. Toutes les structures de données de Pandas sont mutables en valeur (elles peuvent être modifiées). Les modifications de taille ne sont possibles que pour les structures Dataframe et Panel. 
 + 
 +**All of that dry information is nice, but to really appreciate how easy Pandas makes dealing with data, let's play a little bit.  One of the best things about Pandas is that many times, you can do much of the work in a Python shell.
  
 So, assuming you've gotten the Pandas library, open up a Python3 shell.  The first thing you need to do is import the Pandas library. So, assuming you've gotten the Pandas library, open up a Python3 shell.  The first thing you need to do is import the Pandas library.
Ligne 27: Ligne 49:
 >>> import pandas as pd >>> import pandas as pd
  
-Just for those who haven't been doing Python for a while, like most of you, we use the 'as pd' to create an alias to the library so we don't have to refer to all the commands by typing 'pandas.command' We can just type 'pd.command'.+Just for those who haven't been doing Python for a while, like most of you, we use the 'as pd' to create an alias to the library so we don't have to refer to all the commands by typing 'pandas.command' We can just type 'pd.command'.** 
 + 
 +C'est bien, toute cette information brute, mais pour apprécier réellement comment Pandas facilite la gestion des données, jouons un peu avec. Une des meilleures choses à propos de Pandas est que, souvent, vous pouvez faire la plupart de votre travail dans un shell Python. 
 + 
 +Aussi, en présumant que vous avez récupéré la bibliothèque Pandas, ouvrons un shell Python3. La première chose que vous devez faire est d'importer la bibliothèque Pandas. 
 + 
 +>>> import pandas as pd 
 + 
 +Juste pour ceux qui n'auraient rien fait avec Python depuis un moment, comme la plupart d'entre vous, nous utilisons « as pd » pour créer un alias pour la bibliothèque ; ainsi, nous n'avons pas à taper la référence « pandas.command » dans toutes les commandes. Nous n'avons qu'à saisir « pd.command ».
  
-Series Data Structures+**Series Data Structures
  
 Now let's create a simple list of random ten integers and name it 'data'. Now let's create a simple list of random ten integers and name it 'data'.
Ligne 40: Ligne 70:
  
 That's all there is to it.  Now let's see what it looks like.. That's all there is to it.  Now let's see what it looks like..
 +
 +>>> print(sd)
 +0    20
 +1    10
 +2    42
 +3    73
 +4    90
 +5    18
 +6    37
 +7    26
 +8    19
 +9    98**
 +
 +Structure de données Series
 +
 +Maintenant, créons une liste simple de dix entiers aléatoires et appelons-la « data ».
 +
 +>>> data = [20,10,42,73,90,18,37,26,19,98]
 +
 +Ensuite, nous pouvons créer une structure de données Series de Pandas avec la commande .Series().
 +
 +>>> sd = pd.Series(data)
 +
 +C'est tout ce qu'il y a à faire. Maintenant, regardons à quoi ça ressemble.
  
 >>> print(sd) >>> print(sd)
Ligne 53: Ligne 107:
 9    98 9    98
  
-Notice our list of integers is exactly as we entered it and that there is an index added for us as well.  This is the DEFAULT index.  We can make it different if we wish, which we'll see later.+**Notice our list of integers is exactly as we entered it and that there is an index added for us as well.  This is the DEFAULT index.  We can make it different if we wish, which we'll see later.
  
 Also, you might notice that at the end of the output from almost all of the Pandas code we will be doing, you will see something like dtype: int64.  That is there to show you what the data type is.  I’ve taken it out of the output listings to save space in the article. Also, you might notice that at the end of the output from almost all of the Pandas code we will be doing, you will see something like dtype: int64.  That is there to show you what the data type is.  I’ve taken it out of the output listings to save space in the article.
  
 Now, if we just want a quick peek at the data, we could use the .head() or .tail() command.  Here is an example of the .head command showing the first five items. Now, if we just want a quick peek at the data, we could use the .head() or .tail() command.  Here is an example of the .head command showing the first five items.
 +
 +>>> sd.head(5)
 +0    20
 +1    10
 +2    42
 +3    73
 +4    90**
 +
 +Notez que notre liste d'entiers est exactement comme nous l'avons saisie et qu'il y a aussi un index qui a été ajouté. C'est l'index PAR DÉFAUT. Nous pouvons le faire autrement si nous le souhaitons, ce que nous verrons plus tard.
 +
 +Vous pouvez noter aussi qu'à la fin des sorties de presque tous les codes de Pandas que nous ferons, vous verrez quelque chose comme dtype: int64. C'est là pour vous montrer quel est le type des données. Je l'ai retiré des listings imprimés dans cet article pour gagner de la place.
 +
 +Maintenant, si vous voulez simplement un extrait rapide des données, nous pouvons utiliser la commande .head() ou .tail(). Voici un exemple de la commande .head() montrant les cinq premiers éléments.
  
 >>> sd.head(5) >>> sd.head(5)
Ligne 66: Ligne 133:
 4    90 4    90
  
-The .tail() command works the same way, showing the end of the data list.+**The .tail() command works the same way, showing the end of the data list.
  
 If we want to simply see one item out of our list, we can use the index... If we want to simply see one item out of our list, we can use the index...
- 
  
 >>> print(sd[4]) >>> print(sd[4])
Ligne 75: Ligne 141:
  
 Now assume we want to see items 4, 5 and 6.  We do it this way... Now assume we want to see items 4, 5 and 6.  We do it this way...
 +
 +>>> print(sd.loc[4:6,])
 +4    90
 +5    18
 +6    37**
 +
 +La commande .tail() fonctionne de la même façon, en montrant la fin de la liste.
 +
 +Si vous ne voulez voir qu'un des éléments de la liste, vous pouvez utiliser l'index...
 +
 +>>> print(sd[4])
 +90
 +
 +Maintenant, disons que nous voulons voir les éléments 4,5 et 6. Nous le faisons ainsi...
  
 >>> print(sd.loc[4:6,]) >>> print(sd.loc[4:6,])
Ligne 81: Ligne 161:
 6    37 6    37
  
-While this command looks somewhat strange, I'll break it down so it makes more sense...+**While this command looks somewhat strange, I'll break it down so it makes more sense...
  
 sd.loc[] is an indexer command.  It works with both the Series and Dataframe data structures.  It can be very powerful.  The command works like this... sd.loc[] is an indexer command.  It works with both the Series and Dataframe data structures.  It can be very powerful.  The command works like this...
Ligne 90: Ligne 170:
  
 Now getting back to custom indexes.  We can create the index as a second parameter to the Series command like this... Now getting back to custom indexes.  We can create the index as a second parameter to the Series command like this...
 +
 +>>> sd = pd.Series(data,index=['One','Two','Three','Four','Five','Six','Seven','Eight','Nine','Ten'])
 +
 +>>> print(sd)
 +One      20
 +Two      10
 +Three    42
 +Four     73
 +Five     90
 +Six      18
 +Seven    37
 +Eight    26
 +Nine     19
 +Ten      98**
 +
 +Comme cette commande paraît un peu étrange, je la détaillerai pour lui donner plus du sens...
 +
 +sd.loc[] est une commande d'indexeur. Elle fonctionne avec les deux structures de données Series et Dataframe. Elle peut être vraiment puissante. La commande fonctionne ainsi...
 +
 +.loc[rowslice,columnslice]
 +
 +Comme nous utilisons une structure Series, nous n'avons qu'une colonne ; aussi, nous ne travaillons qu'avec la portion d'indexeur « ligne » de la commande. Nous en verrons plus de la commande .loc quand nous traiterons les Dataframes.
 +
 +Maintenant, revenons aux index personnalisés. Nous pouvons créer l'index comme deuxième paramètre de la commande Series comme ceci...
  
 >>> sd = pd.Series(data,index=['One','Two','Three','Four','Five','Six','Seven','Eight','Nine','Ten']) >>> sd = pd.Series(data,index=['One','Two','Three','Four','Five','Six','Seven','Eight','Nine','Ten'])
Ligne 105: Ligne 209:
 Ten      98 Ten      98
  
-One of the things that I really like about Pandas, is the built-in Data Analysis Helper functions.  Here is a quick sample...+**One of the things that I really like about Pandas, is the built-in Data Analysis Helper functions.  Here is a quick sample... 
 + 
 +>>> sd.sum() 
 +433 
 +>>> sd.count() 
 +10 
 +>>> sd.min() 
 +10 
 +>>> sd.max() 
 +98 
 +>>> sd.describe() 
 +count    10.000000 
 +mean     43.300000 
 +std      32.107631 
 +min      10.000000 
 +25%      19.250000 
 +50%      31.500000 
 +75%      65.250000 
 +max      98.000000** 
 + 
 +Une des choses que j'apprécie vraiment dans Pandas, c'est les fonctions intégrées du Data Analysis Helper (Aide à l'analyse des données). Voici un exemple rapide...
  
 >>> sd.sum() >>> sd.sum()
Ligne 125: Ligne 249:
 max      98.000000 max      98.000000
  
-DataFrame Data Structures+**DataFrame Data Structures
  
 Now that I’ve shown you some of the things that can be done with a simple Series data structure, let’s look at the DataFrame.  I stated earlier that a DataFrame is a 2D tabular structure.  Think of a spreadsheet or database table and that is pretty much what a DataFrame looks like.  We can create a DataFrame from any of the following: Now that I’ve shown you some of the things that can be done with a simple Series data structure, let’s look at the DataFrame.  I stated earlier that a DataFrame is a 2D tabular structure.  Think of a spreadsheet or database table and that is pretty much what a DataFrame looks like.  We can create a DataFrame from any of the following:
Ligne 134: Ligne 258:
 • Other DataFrames • Other DataFrames
  
-The easiest way to show you a DataFrame in action, let’s create a small dictionary (shown below).+The easiest way to show you a DataFrame in action, let’s create a small dictionary (shown below).**
  
-As you can see, there will be four rows and four columns.  And you can also see that the data types are mixed.  Just as we did when we created the Series data structure, we simply call the .DataFrame command with our data (there are other parameter options that we’ll discuss another time).+Structure de données Dataframe 
 + 
 +Maintenant que je vous ai montré certaines des choses qui peuvent être faites avec une simple structure de données Series, regardons les Dataframes. J'ai indiqué précédemment qu'une Dataframe était une structure tabulaire en deux dimensions. Pensez à un tableur ou à une table de base de données et c'est à peu près à quoi ressemble une Dataframe. Nous pouvons créer une Dataframe à partir de n'importe lequel de ceux-ci : 
 +• Listes 
 +• Dictionnaires 
 +• Séries 
 +• Numpy ndarrays 
 +• Autres DataFrames 
 + 
 +La façon la plus simple de vous montrer une Dataframe en action sera de créer un petit dictionnaire (montré ci-dessous). 
 + 
 +**As you can see, there will be four rows and four columns.  And you can also see that the data types are mixed.  Just as we did when we created the Series data structure, we simply call the .DataFrame command with our data (there are other parameter options that we’ll discuss another time).
  
 >>> df = pd.DataFrame(data2) >>> df = pd.DataFrame(data2)
Ligne 148: Ligne 283:
 2  Mary   41      F   2  Mary   41      F  
 Human Resources Human Resources
 +3  Lois   27      F      Development
 +>>> **
 +
 +Comme vous pouvez le voir, il y a quatre lignes et quatre colonnes. Et vous pouvez voir aussi que les types de données sont variés. Comme nous l'avons fait quand nous avons créé la structure de données Series, nous appelons simplement la commande .Dataframe avec nos données (il y a d'autres paramètres dont nous parlerons une autre fois).
 +
 +>>> df = pd.DataFrame(data2)
 +
 +Maintenant, pour voir à quoi ressemble la structure à Pandas, nous appelons simplement la structure.
 +
 +>>> df
 +   Nom  Age     Sexe   Service
 +0  Greg   65      M      Management
 +1   Sam   34      M      Development
 +2  Mary   41      F      Human Resources
 3  Lois   27      F      Development 3  Lois   27      F      Development
 >>>  >>> 
  
-Like I said earlier, it resembles a spreadsheet.  Pretty much everything we did with the Serial structure, we can do with the DataFrame.  Let’s do something useful with the data.  We’ll create a Serial structure based on the Age column.+**Like I said earlier, it resembles a spreadsheet.  Pretty much everything we did with the Serial structure, we can do with the DataFrame.  Let’s do something useful with the data.  We’ll create a Serial structure based on the Age column.
  
 >>> age = df['Age'] >>> age = df['Age']
Ligne 161: Ligne 310:
  
 Now that we have our age Serial structure, let’s get the sum of the values… Now that we have our age Serial structure, let’s get the sum of the values…
 +
 +>>> age.sum()
 +167**
 +
 +Comme je l'ai déjà dit, cela ressemble à un tableur. À peu près tout ce que nous avons fait avec la structure Series peut être fait avec la Dataframe. Faisons quelque chose d'utile avec les données. Nous créerons une structure Series basée sur la colonne Age.
 +
 +>>> age = df['Age']
 +>>> age
 +0    65
 +1    34
 +2    41
 +3    27
 +
 +Maintenant que nous avons notre structure Series age, additionnons les valeurs...
  
 >>> age.sum() >>> age.sum()
 167 167
  
-It’s SO easy to deal with data this way.+**It’s SO easy to deal with data this way.
  
 As we did with the Serial structure, we can get the data for just one row by using the .loc command. As we did with the Serial structure, we can get the data for just one row by using the .loc command.
Ligne 178: Ligne 341:
 Notice we have to use the index that was created for us automatically.  We can’t do something like df.loc[‘Greg’] since ‘Greg’ is not an index item.  HOWEVER, there is a cool way to fix that.  We can use the .set_index(ColumnName,inplace=True) command to remove the default index and replace it with a column of our choice.  In this case, we’ll use the ‘Name’ column... Notice we have to use the index that was created for us automatically.  We can’t do something like df.loc[‘Greg’] since ‘Greg’ is not an index item.  HOWEVER, there is a cool way to fix that.  We can use the .set_index(ColumnName,inplace=True) command to remove the default index and replace it with a column of our choice.  In this case, we’ll use the ‘Name’ column...
  
->>> df.set_index('Name',inplace=True)+>>> df.set_index('Name',inplace=True)** 
 + 
 +C'est TELLEMENT facile de gérer les données de cette façon. 
 + 
 +Comme nous l'avons fait avec la structure Series, nous obtenons les données d'une seule ligne avec la commande .loc. 
 + 
 +>>> df.loc[0] 
 +Nom                Greg 
 +Age                 65 
 +Sexe                 M 
 +Service    Management 
 +Name: 0, dtype: object 
 + 
 +Notez que nous avons utilisé l'index qui a été créé automatiquement pour nous. Nous ne pouvons pas faire quelque chose comme df.loc[‘Greg’] car ‘Greg’ n'est pas un élément indexable. CEPENDANT, il y a une façon sympa de résoudre cela. Nous pouvons utiliser la commande .set_index(ColumnName,inplace=True) pour enlever l'index par défaut et le remplacer par une colonne de notre choix. Dans ce cas, nous utiliserons la colonne « Nom »... 
 + 
 +>>> df.set_index('Nom',inplace=True)
  
-Now we can see our data structure after the change...+**Now we can see our data structure after the change...
  
 >>> df >>> df
Ligne 197: Ligne 375:
 Gender                 M Gender                 M
 Department    Management Department    Management
 +Name: Greg, dtype: object**
 +
 +Maintenant, vous pouvez voir notre structure de données après la modification...
 +
 +>>> df
 +Nom    Age Sexe       Service                             
 +Greg   65      M       Management
 +Sam    34      M      Development
 +Mary   41      F  Human Resources
 +Lois   27      F      Development
 +
 +Maintenant, notre index est remplacé par la colonne Nom. MAINTENANT, nous pouvons obtenir uniquement l'information sur Greg...
 +
 +>>> df.loc['Greg']
 +Age                   65
 +Sexe                 M
 +Service    Management
 Name: Greg, dtype: object Name: Greg, dtype: object
  
-One of the things we can do with a DataFrame that we can’t with a Serial structure, is get extended information using the .info() command.+**One of the things we can do with a DataFrame that we can’t with a Serial structure, is get extended information using the .info() command.
  
 >>> df.info() >>> df.info()
Ligne 212: Ligne 407:
 memory usage: 208.0+ bytes memory usage: 208.0+ bytes
  
-I hope that I have generated some interest about Pandas.  Next time, we’ll look deeper at the DataFrames in Pandas.  Until then, keep coding!+I hope that I have generated some interest about Pandas.  Next time, we’ll look deeper at the DataFrames in Pandas.  Until then, keep coding!** 
 + 
 +Une des choses que nous pouvons faire avec une Dataframe, que nous ne pouvons pas faire avec une structure Series, c'est d'obtenir une information étendue en utilisant la commande .info(). 
 + 
 +>>> df.info() 
 +<class 'pandas.core.frame.DataFrame'> 
 +RangeIndex: 4 entries, 0 to 3 
 +Data columns (total 4 columns): 
 +Nom          4 non-null object 
 +Age           4 non-null int64 
 +Sexe        4 non-null object 
 +Service    4 non-null object 
 +dtypes: int64(1), object(3) 
 +memory usage: 208.0+ bytes 
 + 
 +J'espère que j'ai généré quelque intérêt pour Pandas. La prochaine fois, nous regarderons plus en détail les Dataframes dans Pandas. Jusque-là, continuez à coder !
  
issue140/python.1546016887.txt.gz · Dernière modification : 2018/12/28 18:08 de auntiee