0% ont trouvé ce document utile (0 vote)
6 vues16 pages

Introduction aux DataFrames en Python

Transféré par

Israa Al
Copyright
© All Rights Reserved
Nous prenons très au sérieux les droits relatifs au contenu. Si vous pensez qu’il s’agit de votre contenu, signalez une atteinte au droit d’auteur ici.
Formats disponibles
Téléchargez aux formats PDF, TXT ou lisez en ligne sur Scribd
0% ont trouvé ce document utile (0 vote)
6 vues16 pages

Introduction aux DataFrames en Python

Transféré par

Israa Al
Copyright
© All Rights Reserved
Nous prenons très au sérieux les droits relatifs au contenu. Si vous pensez qu’il s’agit de votre contenu, signalez une atteinte au droit d’auteur ici.
Formats disponibles
Téléchargez aux formats PDF, TXT ou lisez en ligne sur Scribd

data_frames-1

January 20, 2024

1 Les DataFrames dans Python


1.1 Défintion d’un DataFrame
Un data frame est une structure bidimensionnelle. Cela signifie que les données sont alignées de
façon tabulaire en colonnes et en lignes. Le format de ces structures est comparable aux diction-
naires Python. Les valeurs sont en effet les Séries tandis que les clés sont les noms des colonnes.
La structure d’un data frame est généralement similaire à une feuille de calcul Excel ou une table
SQL. La syntaxe de création de data frame est : pandas. DataFrame (data, index, columns).

1.2 Pandas
Pandas est une bibliothèque open-source permettant la manipulation et l’analyse de données de
manière simple et intuitive en Python. Elle a été développée par Wes McKinney en 2008 alors
qu’il travaillait chez AQR Capital Management. À la fin de l’année 2009, elle a été mise en open
source et est aujourd’hui activement utilisée dans le domaine de la Big data et de la data science
car celle-ci offre des performances et une productivité élevée à ces utilisateurs.

[1]: ## charger la librairies pandas dans le notebook


import pandas as pd

[2]: ## création d'un data frame avec pandas


notes = {
"Mathématiques": [Link]([18.0, 20.0, 17.0,19.5]),
"Sciences Physiques": [Link]([15.0, 7.0, 10.0,20.0]),
}

[3]: df = [Link](notes)
df

[3]: Mathématiques Sciences Physiques


0 18.0 15.0
1 20.0 7.0
2 17.0 10.0
3 19.5 20.0

Exécuter la commande suivante et commentez

1
[4]: df = [Link](notes)
df

---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-4-9ff437970de2> in <cell line: 1>()
----> 1 df = [Link](notes)
2 df

/usr/local/lib/python3.10/dist-packages/pandas/__init__.py in __getattr__(name)
262 return _SparseArray
263
--> 264 raise AttributeError(f"module 'pandas' has no attribute '{name}'")
265
266

AttributeError: module 'pandas' has no attribute 'dataframe'

2 Accéder à une colonne dans un DataFrame


Pour accéder à une colonne il suffit de taper le nom de la colonne entre deux accolades ou bien
mettre son nom après le noms de la DataFrame

[5]: df["Mathématiques"]

[5]: 0 18.0
1 20.0
2 17.0
3 19.5
Name: Mathématiques, dtype: float64

[6]: [Link]ématiques

[6]: 0 18.0
1 20.0
2 17.0
3 19.5
Name: Mathématiques, dtype: float64

3 Importer des données format .csv dans Pandas


Le format CSV (Comma Separated Values) est très populaire pour le stockage des données. Un
grand nombre de stockage de données se présentent sous la forme de fichiers CSV qui peuvent
être utilisés soit directement dans un tableur comme Excel, soit chargés dans des langages de
programmation comme R ou Python. Les dataframes de Pandas sont assez puissants pour traiter
des données tabulaires bidimensionnelles.

2
Pour lire un fichier csv avec Pandas on utilise la fonction read_csv() . Elle est fournie avec un
certain nombre de paramètres différents pour personnaliser la façon dont vous souhaitez lire le
fichier.
Dans l’exemple suivant, nous chargerons un fichier csv stockant les données sur les espèces et le
poids des animaux capturés sur le site du désert de Chihuahuan près de Portal, Arizona, États-Unis.
Chaque ligne contient les informations relatives à un seul animal, et les colonnes représentent les
caractéristiques étudiées.

[ ]: df = pd.read_csv("[Link]
df

[ ]: record_id month day year plot_id species_id sex hindfoot_length \


0 1 7 16 1977 2 NL M 32.0
1 2 7 16 1977 3 NL M 33.0
2 3 7 16 1977 2 DM F 37.0
3 4 7 16 1977 7 DM M 36.0
4 5 7 16 1977 3 DM M 35.0
… … … … … … … … …
35544 35545 12 31 2002 15 AH NaN NaN
35545 35546 12 31 2002 15 AH NaN NaN
35546 35547 12 31 2002 10 RM F 15.0
35547 35548 12 31 2002 7 DO M 36.0
35548 35549 12 31 2002 5 NaN NaN NaN

weight
0 NaN
1 NaN
2 NaN
3 NaN
4 NaN
… …
35544 NaN
35545 NaN
35546 14.0
35547 51.0
35548 NaN

[35549 rows x 9 columns]

[ ]: # Afficher les 5 premières lignes d'un DataFrame


[Link](5)

[ ]: record_id month day year plot_id species_id sex hindfoot_length \


0 1 7 16 1977 2 NL M 32.0
1 2 7 16 1977 3 NL M 33.0
2 3 7 16 1977 2 DM F 37.0
3 4 7 16 1977 7 DM M 36.0

3
4 5 7 16 1977 3 DM M 35.0

weight
0 NaN
1 NaN
2 NaN
3 NaN
4 NaN

[ ]: [Link]()

---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-12-1f32a228f651> in <cell line: 1>()
----> 1 [Link]()

/usr/local/lib/python3.10/dist-packages/pandas/core/[Link] in␣
↪__getattr__(self, name)

5900 ):
5901 return self[name]
-> 5902 return object.__getattribute__(self, name)
5903
5904 def __setattr__(self, name: str, value) -> None:

AttributeError: 'DataFrame' object has no attribute 'HEAD'

[ ]: # Afficher les 5 dernières lignes d'un DataFrame


[Link](5)

[ ]: record_id month day year plot_id species_id sex hindfoot_length \


35544 35545 12 31 2002 15 AH NaN NaN
35545 35546 12 31 2002 15 AH NaN NaN
35546 35547 12 31 2002 10 RM F 15.0
35547 35548 12 31 2002 7 DO M 36.0
35548 35549 12 31 2002 5 NaN NaN NaN

weight
35544 NaN
35545 NaN
35546 14.0
35547 51.0
35548 NaN

[ ]: # Afficher le nombre de ligne et le nombre de colonne d'un DataFrame


[Link]

4
[ ]: (35549, 9)

[ ]: # Afficher les infos du DataFrame


[Link]()

<class '[Link]'>
RangeIndex: 35549 entries, 0 to 35548
Data columns (total 9 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 record_id 35549 non-null int64
1 month 35549 non-null int64
2 day 35549 non-null int64
3 year 35549 non-null int64
4 plot_id 35549 non-null int64
5 species_id 34786 non-null object
6 sex 33038 non-null object
7 hindfoot_length 31438 non-null float64
8 weight 32283 non-null float64
dtypes: float64(2), int64(5), object(2)
memory usage: 2.4+ MB

[ ]: # Séléctionner des colonnes dans un DataFrame


df[['month','day','year','plot_id']]

[ ]: month day year plot_id


0 7 16 1977 2
1 7 16 1977 3
2 7 16 1977 2
3 7 16 1977 7
4 7 16 1977 3
… … … … …
35544 12 31 2002 15
35545 12 31 2002 15
35546 12 31 2002 10
35547 12 31 2002 7
35548 12 31 2002 5

[35549 rows x 4 columns]

[ ]: # Séléctionner la colonne avec la méthode loc


print([Link][:,'day'])

0 16
1 16
2 16
3 16
4 16
..

5
35544 31
35545 31
35546 31
35547 31
35548 31
Name: day, Length: 35549, dtype: int64

[ ]: # Séléctionner plusieurs colonnes avec la méthode loc


print([Link][:,['day','month']])

day month
0 16 7
1 16 7
2 16 7
3 16 7
4 16 7
… … …
35544 31 12
35545 31 12
35546 31 12
35547 31 12
35548 31 12

[35549 rows x 2 columns]

[ ]: print([Link][:,['Day','month']])

---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-18-9b2c74ffd3cc> in <cell line: 1>()
----> 1 print([Link][:,['Day','month']])

/usr/local/lib/python3.10/dist-packages/pandas/core/[Link] in␣
↪__getitem__(self, key)

1065 if self._is_scalar_access(key):
1066 return [Link]._get_value(*key, takeable=self._takeable)
-> 1067 return self._getitem_tuple(key)
1068 else:
1069 # we by definition only have the 0th axis

/usr/local/lib/python3.10/dist-packages/pandas/core/[Link] in␣
↪_getitem_tuple(self, tup)

1254 return self._multi_take(tup)


1255
-> 1256 return self._getitem_tuple_same_dim(tup)
1257
1258 def _get_label(self, label, axis: int):

6
/usr/local/lib/python3.10/dist-packages/pandas/core/[Link] in␣
↪_getitem_tuple_same_dim(self, tup)

922 continue
923
--> 924 retval = getattr(retval, [Link])._getitem_axis(key,␣
↪axis=i)

925 # We should never have [Link] < [Link], as that␣


↪should

926 # be handled by the _getitem_lowerdim call above.

/usr/local/lib/python3.10/dist-packages/pandas/core/[Link] in␣
↪_getitem_axis(self, key, axis)

1299 raise ValueError("Cannot index with multidimensional␣


↪key")

1300
-> 1301 return self._getitem_iterable(key, axis=axis)
1302
1303 # nested tuple slicing

/usr/local/lib/python3.10/dist-packages/pandas/core/[Link] in␣
↪_getitem_iterable(self, key, axis)

1237
1238 # A collection of keys
-> 1239 keyarr, indexer = self._get_listlike_indexer(key, axis)
1240 return [Link]._reindex_with_indexers(
1241 {axis: [keyarr, indexer]}, copy=True, allow_dups=True

/usr/local/lib/python3.10/dist-packages/pandas/core/[Link] in␣
↪_get_listlike_indexer(self, key, axis)

1430 axis_name = [Link]._get_axis_name(axis)


1431
-> 1432 keyarr, indexer = ax._get_indexer_strict(key, axis_name)
1433
1434 return keyarr, indexer

/usr/local/lib/python3.10/dist-packages/pandas/core/indexes/[Link] in␣
↪_get_indexer_strict(self, key, axis_name)

6068 keyarr, indexer, new_indexer = self.


↪_reindex_non_unique(keyarr)

6069
-> 6070 self._raise_if_missing(keyarr, indexer, axis_name)
6071
6072 keyarr = [Link](indexer)

/usr/local/lib/python3.10/dist-packages/pandas/core/indexes/[Link] in␣
↪_raise_if_missing(self, key, indexer, axis_name)

6131

7
6132 not_found = list(ensure_index(key)[missing_mask.
↪nonzero()[0]].unique())

-> 6133 raise KeyError(f"{not_found} not in index")


6134
6135 @overload

KeyError: "['Day'] not in index"

[ ]: # Renommer une colonne dans un DataFrame


[Link](columns = {'plot_id':'PlotID'}, inplace = True)

[ ]: [Link](5)

[ ]: record_id month day year PlotID species_id sex hindfoot_length weight


0 1 7 16 1977 2 NL M 32.0 NaN
1 2 7 16 1977 3 NL M 33.0 NaN
2 3 7 16 1977 2 DM F 37.0 NaN
3 4 7 16 1977 7 DM M 36.0 NaN
4 5 7 16 1977 3 DM M 35.0 NaN

3.1 Filtrer les données dans un data frame


[ ]: # Séléctionner les records dont le hindfoot_length est strictement supérieur à␣
↪48

df[df['hindfoot_length']>48]

[ ]: record_id month day year PlotID species_id sex hindfoot_length \


10 11 7 16 1977 5 DS F 53.0
29 30 7 17 1977 10 DS F 52.0
90 91 8 20 1977 11 DS F 50.0
99 100 8 20 1977 5 DS F 54.0
148 149 8 21 1977 20 DS M 50.0
… … … … … … … .. …
29312 29313 3 14 1999 2 DS F 52.0
29435 29436 4 17 1999 2 DS F 51.0
29572 29573 5 15 1999 2 DS M 50.0
29705 29706 6 12 1999 2 DS M 49.0
30424 30425 3 4 2000 1 DO F 64.0

weight
10 NaN
29 NaN
90 NaN
99 NaN
148 NaN
… …
29312 153.0

8
29435 131.0
29572 96.0
29705 102.0
30424 35.0

[1635 rows x 9 columns]

[ ]: # en utilisant la méthode loc


print([Link][df['hindfoot_length']>48])

record_id month day year PlotID species_id sex hindfoot_length \


10 11 7 16 1977 5 DS F 53.0
29 30 7 17 1977 10 DS F 52.0
90 91 8 20 1977 11 DS F 50.0
99 100 8 20 1977 5 DS F 54.0
148 149 8 21 1977 20 DS M 50.0
… … … … … … … .. …
29312 29313 3 14 1999 2 DS F 52.0
29435 29436 4 17 1999 2 DS F 51.0
29572 29573 5 15 1999 2 DS M 50.0
29705 29706 6 12 1999 2 DS M 49.0
30424 30425 3 4 2000 1 DO F 64.0

weight
10 NaN
29 NaN
90 NaN
99 NaN
148 NaN
… …
29312 153.0
29435 131.0
29572 96.0
29705 102.0
30424 35.0

[1635 rows x 9 columns]

[ ]: [Link]('hindfoot_length>48')

[ ]: record_id month day year PlotID species_id sex hindfoot_length \


10 11 7 16 1977 5 DS F 53.0
29 30 7 17 1977 10 DS F 52.0
90 91 8 20 1977 11 DS F 50.0
99 100 8 20 1977 5 DS F 54.0
148 149 8 21 1977 20 DS M 50.0
… … … … … … … .. …
29312 29313 3 14 1999 2 DS F 52.0

9
29435 29436 4 17 1999 2 DS F 51.0
29572 29573 5 15 1999 2 DS M 50.0
29705 29706 6 12 1999 2 DS M 49.0
30424 30425 3 4 2000 1 DO F 64.0

weight
10 NaN
29 NaN
90 NaN
99 NaN
148 NaN
… …
29312 153.0
29435 131.0
29572 96.0
29705 102.0
30424 35.0

[1635 rows x 9 columns]

[ ]: [Link][df['hindfoot_length']>48]

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-24-24bb9469f974> in <cell line: 1>()
----> 1 [Link][df['hindfoot_length']>48]

TypeError: 'method' object is not subscriptable

[ ]: [Link](hindfoot_length>48)

---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-25-85de14cc3214> in <cell line: 1>()
----> 1 [Link](hindfoot_length>48)

NameError: name 'hindfoot_length' is not defined

[ ]: [Link](df['hindfoot_length']>48)

---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-26-2d5d9f12cc45> in <cell line: 1>()
----> 1 [Link](df['hindfoot_length']>48)

10
/usr/local/lib/python3.10/dist-packages/pandas/util/_decorators.py in␣
↪wrapper(*args, **kwargs)

329 stacklevel=find_stack_level(),
330 )
--> 331 return func(*args, **kwargs)
332
333 # error: "Callable[[VarArg(Any), KwArg(Any)], Any]" has no

/usr/local/lib/python3.10/dist-packages/pandas/core/[Link] in query(self,␣
↪expr, inplace, **kwargs)

4469 if not isinstance(expr, str):


4470 msg = f"expr must be a string to be evaluated, {type(expr)}␣
↪given"

-> 4471 raise ValueError(msg)


4472 kwargs["level"] = [Link]("level", 0) + 2
4473 kwargs["target"] = None

ValueError: expr must be a string to be evaluated, <class '[Link].


↪Series'> given

[ ]: # Filtrer les données avec deux conditions


df[(df['hindfoot_length']>48) & (df['sex']=='F')]

[ ]: record_id month day year PlotID species_id sex hindfoot_length \


10 11 7 16 1977 5 DS F 53.0
29 30 7 17 1977 10 DS F 52.0
90 91 8 20 1977 11 DS F 50.0
99 100 8 20 1977 5 DS F 54.0
152 153 8 21 1977 16 DS F 50.0
… … … … … … … .. …
29037 29038 1 16 1999 2 DS F 51.0
29166 29167 2 20 1999 2 DS F 50.0
29312 29313 3 14 1999 2 DS F 52.0
29435 29436 4 17 1999 2 DS F 51.0
30424 30425 3 4 2000 1 DO F 64.0

weight
10 NaN
29 NaN
90 NaN
99 NaN
152 NaN
… …
29037 136.0
29166 140.0
29312 153.0
29435 131.0

11
30424 35.0

[751 rows x 9 columns]

[ ]: # Avec la méthode loc


[Link][(df['hindfoot_length']>48) & (df['sex']=='F')]

[ ]: record_id month day year PlotID species_id sex hindfoot_length \


10 11 7 16 1977 5 DS F 53.0
29 30 7 17 1977 10 DS F 52.0
90 91 8 20 1977 11 DS F 50.0
99 100 8 20 1977 5 DS F 54.0
152 153 8 21 1977 16 DS F 50.0
… … … … … … … .. …
29037 29038 1 16 1999 2 DS F 51.0
29166 29167 2 20 1999 2 DS F 50.0
29312 29313 3 14 1999 2 DS F 52.0
29435 29436 4 17 1999 2 DS F 51.0
30424 30425 3 4 2000 1 DO F 64.0

weight
10 NaN
29 NaN
90 NaN
99 NaN
152 NaN
… …
29037 136.0
29166 140.0
29312 153.0
29435 131.0
30424 35.0

[751 rows x 9 columns]

[ ]: # Avec la méthode Query


[Link]('hindfoot_length>48 and sex =="F"')

[ ]: record_id month day year PlotID species_id sex hindfoot_length \


10 11 7 16 1977 5 DS F 53.0
29 30 7 17 1977 10 DS F 52.0
90 91 8 20 1977 11 DS F 50.0
99 100 8 20 1977 5 DS F 54.0
152 153 8 21 1977 16 DS F 50.0
… … … … … … … .. …
29037 29038 1 16 1999 2 DS F 51.0
29166 29167 2 20 1999 2 DS F 50.0

12
29312 29313 3 14 1999 2 DS F 52.0
29435 29436 4 17 1999 2 DS F 51.0
30424 30425 3 4 2000 1 DO F 64.0

weight
10 NaN
29 NaN
90 NaN
99 NaN
152 NaN
… …
29037 136.0
29166 140.0
29312 153.0
29435 131.0
30424 35.0

[751 rows x 9 columns]

[ ]: # Avec la méthode Query


[Link]('hindfoot_length>48 & sex =="F"')

[ ]: record_id month day year PlotID species_id sex hindfoot_length \


10 11 7 16 1977 5 DS F 53.0
29 30 7 17 1977 10 DS F 52.0
90 91 8 20 1977 11 DS F 50.0
99 100 8 20 1977 5 DS F 54.0
152 153 8 21 1977 16 DS F 50.0
… … … … … … … .. …
29037 29038 1 16 1999 2 DS F 51.0
29166 29167 2 20 1999 2 DS F 50.0
29312 29313 3 14 1999 2 DS F 52.0
29435 29436 4 17 1999 2 DS F 51.0
30424 30425 3 4 2000 1 DO F 64.0

weight
10 NaN
29 NaN
90 NaN
99 NaN
152 NaN
… …
29037 136.0
29166 140.0
29312 153.0
29435 131.0
30424 35.0

13
[751 rows x 9 columns]

[ ]: [Link][(df['hindfoot_length']>48) | (df['sex']=='F')]

[ ]: record_id month day year PlotID species_id sex hindfoot_length \


2 3 7 16 1977 2 DM F 37.0
6 7 7 16 1977 2 PE F NaN
8 9 7 16 1977 1 DM F 34.0
9 10 7 16 1977 6 PF F 20.0
10 11 7 16 1977 5 DS F 53.0
… … … … … … … .. …
35539 35540 12 31 2002 15 PB F 26.0
35540 35541 12 31 2002 15 PB F 24.0
35541 35542 12 31 2002 15 PB F 26.0
35542 35543 12 31 2002 15 PB F 27.0
35546 35547 12 31 2002 10 RM F 15.0

weight
2 NaN
6 NaN
8 NaN
9 NaN
10 NaN
… …
35539 23.0
35540 31.0
35541 29.0
35542 34.0
35546 14.0

[16574 rows x 9 columns]

[ ]: # Avec la méthode isin


year_filtered = [1977,1999,2000,2002]
df[[Link](year_filtered)]

[ ]: record_id month day year PlotID species_id sex hindfoot_length \


0 1 7 16 1977 2 NL M 32.0
1 2 7 16 1977 3 NL M 33.0
2 3 7 16 1977 2 DM F 37.0
3 4 7 16 1977 7 DM M 36.0
4 5 7 16 1977 3 DM M 35.0
… … … … … … … … …
35544 35545 12 31 2002 15 AH NaN NaN
35545 35546 12 31 2002 15 AH NaN NaN
35546 35547 12 31 2002 10 RM F 15.0

14
35547 35548 12 31 2002 7 DO M 36.0
35548 35549 12 31 2002 5 NaN NaN NaN

weight
0 NaN
1 NaN
2 NaN
3 NaN
4 NaN
… …
35544 NaN
35545 NaN
35546 14.0
35547 51.0
35548 NaN

[5419 rows x 9 columns]

[ ]: df_year= df[[Link](year_filtered)]

[ ]: df_year.shape

[ ]: (5419, 9)

[ ]: df_year['year'].value_counts()

[ ]: 2002 2229
2000 1552
1999 1135
1977 503
Name: year, dtype: int64

[ ]: # Filtrer les 3 grandes valeurs de hindfoot_length


[Link](3, 'hindfoot_length')

[ ]: record_id month day year PlotID species_id sex hindfoot_length \


10573 10574 7 23 1985 12 NL NaN 70.0
30424 30425 3 4 2000 1 DO F 64.0
1693 1694 3 31 1979 8 DS F 58.0

weight
10573 NaN
30424 35.0
1693 123.0

[ ]: # Filtrer les 3 petites valeurs de hindfoot_Length


[Link](3, 'hindfoot_length')

15
[ ]: record_id month day year PlotID species_id sex hindfoot_length \
31399 31400 9 30 2000 19 PB M 2.0
10066 10067 3 16 1985 19 RM M 6.0
19566 19567 1 8 1992 19 BA M 6.0

weight
31399 30.0
10066 16.0
19566 8.0

[ ]:

16

Vous aimerez peut-être aussi