-
Notifications
You must be signed in to change notification settings - Fork 11
/
python-pandas.qmd
1530 lines (1245 loc) · 46.9 KB
/
python-pandas.qmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
title: Introduction to Python and Pandas
author: Kevin Nota, Robin Warner, and Maxime Borry
---
::: {.callout-note}
This session is typically ran held in parallel to the Introduction to R and Tidyverse. Participants of the summer schools chose which to attend based on their prior experience. We recommend the [introduction to R session](r-tidyverse.qmd) if you have no experience with neither R nor Python.
:::
::: {.callout-note collapse="true" title="Self guided: chapter environment setup"}
For this chapter's exercises, if not already performed, you will need to download the chapter's dataset, decompress the archive, and create and activate the conda environment.
Do this, use `wget` or right click and save to download this Zenodo archive: [10.5281/zenodo.11394586](https://doi.org/10.5281/zenodo.11394586), and unpack
```bash
tar xvf python-pandas.tar.gz
cd python-pandas/
```
You can then create the subsequently activate environment with
```bash
conda env create -f python-pandas.yml
conda activate python-pandas
```
:::
Over the last few years, _Python_ has gained popularity thanks to the numerous libraries (packages with pre-written functions) in bioinformatics, statistical data analysis, and machine learning.
While a few years ago, it was often necessary to go to _R_ for performing routine data manipulation and analysis tasks, nowadays _Python_ has a vast ecosystem of useful libraries for working on metagenomic data.
Existing libraries exist for many different file formats encountered in metagenomics, such as fasta, fastq, sam, bam, etc.
Furthermore, python is fast and extremely useful for writing programs that can be easily called from the command line like many existing tools.
This tutorial/walkthrough will provide a short introduction to the popular libraries for data analysis `pandas` ([(https://pandas.pydata.org/](https://pandas.pydata.org/)).
This library has functions for reading and manipulating _tabular data_ similar to the _`data.frame()`_ in _R_ together with some basic data plotting.
This will set the base for learning Python and use it for data analysis.
There are many IDEs in which Python code can be written.
For data analysis, Jupyter is powerful and popular which looks and functions similar to R markdown, where code is written in code blocks with space in text blocks for annotations.
In this tutorial/walkthrough, we will use these notebooks for running and visualising Python code.
Learning objectives:
- Get familiar with the Python code syntax and use Jupyter Notebook for executing code
- Get a kickstart to utilising the endless possibilities of data analysis in Python that can be applied to our data
## Working in a Jupyter environment
This tutorial/walkthrough is using a Jupyter Notebook ([https://jupyter.org](https://jupyter.org)) for writing and executing Python code and for annotating.
Jupyter notebooks have two types of cells: _Markdown_ and _Code_.
The _Markdown cell_ syntax is very similar to _R markdown_.
The markdown cells are used for annotating code, which is important for sharing work with collaborators, reproducibility, and documentation.
Change the directory to the the working directory of this tutorial/walkthrough.
```bash
cd python-pandas_lecture/
```
To launch jupyter, run the following command in the terminal.
This will open a browser window with jupyter running.
```bash
jupyter notebook
```
Jupyter Notebook should have a file structure with all the files from the working directory.
Open the `student-notebook.ipynb` notebook by clicking on it.
This notebook has exactly the same code as written in this book chapter and is only a support so that it is not necessary to copy and paste the code.
It is of course also possible to copy the code from this chapter into a fresh notebook file by clicking on: `File` > `New` > `Notebook`.
::: {.callout-note title="Note If the notebook is not there" collapse="true"}
If you cannot find `student-notebook.ipynb`, it is possible the working directory is not correct.
Make sure that `pwd` returns `/<path>/<to>/python-pandas/python-pandas_lecture`.
:::
### Creating and running cells
There are multiple ways of making a new cells in jupyter, such as typing the letter `b`, or using the cursor on the bottom of the page that says _`click to add cell`_.
The cells can be assigned to `code` or `markdown` using the drop down menu at the top.
Code cells are always in edit mode.
Code can be run with pressing `Shift + Enter` or click on the `▶` botton.
To make an markdown cell active, double-click on a markdown cell, it switches from display mode to edit mode.
To leave the editing mode by running the cell.
::: {.callout-tip collapse="true" title="Clear your code cells"}
Before starting it might be nice to clear the output of all code cells, by clicking on:
`edit` > `Clear outputs of All Cells`
:::
### Markdown cell syntax
Here a few examples of the syntax for the Markdown cells are shown, such as making words **bold**, or _italics_.
For a more comprehensive list with syntax check out this Jupyter Notebook cheat-sheet ([https://www.ibm.com/docs/en/watson-studio-local/1.2.3?topic=notebooks-markdown-jupyter-cheatsheet](https://www.ibm.com/docs/en/watson-studio-local/1.2.3?topic=notebooks-markdown-jupyter-cheatsheet)).
List of _markdown cell_ examples:
- `**bold**` : **bold**
- `_italics_` : _italics_
Code
- \`inline code\` : `inline code`
LaTeX maths
- `$ x = \frac{\pi}{42} $` : $$ x = \frac{\pi}{42} $$
URL links
- `[link](https://www.python.org/)` : [link](https://www.python.org/)
Images
- `![](https://www.spaam-community.org/assets/media/SPAAM-Logo-Full-Colour_ShortName.svg)` ![](https://www.spaam-community.org/assets/media/SPAAM-Logo-Full-Colour_ShortName.svg)
::: {.callout-note collapse="true" title="All roads lead to Rome"}
In many cases, there are multiple syntaxes, or 'ways of doing things,' that will give the same results.
For each section in this tutorial/walkthrough, one way is presented.
:::
### code cell syntax
The _code cells_ can interpret many different coding languages including _Python_ and _Bash_.
The syntax of the code cells is the same as the syntax of the coding languages, in our case _python_.
Below are some examples of Python _code cells_ with some useful basic python functions:
::: {.callout-tip collapse="true" title="Python function print()"}
`print()` is a python function for printing lines in the terminal
`print()` is the same as `echo` in bash
:::
```{.python eval=False}
print("Hello World from Python!")
```
::: {.callout-note collapse="true"}
## Expand to see output
```
Hello World from Python!
```
:::
::: {.callout-tip collapse="true" title="Running bash code in Jupyter"}
It is also possible to run bash commands in Jupyter, by adding a *!* at the start of the line.
```{.python eval=False}
! echo "Hello World from bash!"
```
```
Hello World from bash!
```
:::
Stings or numbers can be stored as a variable by using the *=* sign.
```{.python eval=False}
i = 0
```
Ones a variable is set in one _code cell_ they are stored and can be accessed in other downstream _code cells_.
To see what value a variable contains, the `print()` function can be used.
```{.python eval=False}
print(i)
```
::: {.callout-note collapse="true"}
## Expand to see output
```
0
```
:::
You can also print multiple things together in one `print` statement such as a number and a string.
```{.python eval=True}
print("The number is", i, "Wow!")
```
::: {.callout-note collapse="true"}
## Expand to see output
```
The number is, 0, Wow!
```
:::
## Pandas
### Getting started
Pandas is a Python library used for data manipulation and analysis.
We can import the library like this.
```{.python eval=False}
import pandas as pd
```
::: {.callout-tip collapse="true"}
## Why import as pd?
We set `pandas` to the alias `pd` because we are lazy and do not want to write the full word too many times.
:::
Now that `Pandas` is imported, we can check if it worked correctly, and check which version is running by runing `.__version__`.
```{.python eval=False}
pd.__version__
```
::: {.callout-note collapse="true"}
## Expand to see output
'2.2.2'
:::
### Pandas data structures
The primary data structures in `Pandas` are the `Series` and the `DataFrame`.
A Series is a one-dimensional array-like object containing a value of the same type and can be imagined as one column in a table @fig-pythonpandas-figpandasseries.
Each element in the `series` is associated with an index from 0 to the number of elements, but these can be changed to labels.
A `DataFrame` is two-dimensional, and can change in size after it is created by adding and removing rows and columns, which can hold different types of data such as numbers and strings @fig-pythonpandas-figpandasdataframe.
The columns and rows are labelled.
By default, rows are unnamed and are indexed similarly to a `series`.
![A single row or column (1-dimensional data) is a `Series`. The dark grey squares are the index or row names, and the light grey squares are the elements.](assets/images/chapters/python-pandas/01_table_series.svg){#fig-pythonpandas-figpandasseries}
![A dataframe with columns and rows. The dark grey squares are the index/row names and the column names. The light grey squares are the values.](assets/images/chapters/python-pandas/01_table_dataframe.svg){#fig-pythonpandas-figpandasdataframe}
::: {.callout-tip collapse="true" title="More details on pandas"}
For a more in detail pandas getting started tutorial click here ([https://pandas.pydata.org/docs/getting_started/index.html#](https://pandas.pydata.org/docs/getting_started/index.html#))
:::
## Reading data with Pandas
Pandas can read in _csv_ (comma separated values) files, which are tables in text format.
It is called _c_sv because each value is separated from the others through a comma.
```verbatim
A,B
5,6
8,4
```
Another common tabular separator are _tsv_, where each value is separated by a _tab_ `\t`.
```verbatim
A\tB
5\t6
8\t4
```
The dataset that is used in this tutorial/walkthrough is called `"all_data.tsv"`, and is tab-separated.
Pandas by default assume that the file is comma delimited, but this can be change by using the `sep= ` argument.
::: {.callout-tip collapse="true" title="Pandas function pd.read_csv()"}
`pd.read_csv()` is the pandas function to read in tabular tables.
The `sep=` can be specified argument, `sep=,` is the default.
:::
```{.python eval=False}
df = pd.read_csv("../all_data.tsv", sep="\t")
df
```
::: {.callout-note collapse="true"}
## Expand to see output
```{r}
#| echo: false
#| results: 'asis'
#| message: false
#| warning: false
library(tidyverse)
library(gt)
# Load the data from CSV
data <- read_csv("assets/images/chapters/python-pandas/table_1_all_data.csv")
# Create the table with gt
data %>%
gt() %>%
tab_options(
table.width = pct(100),
table.layout = "fixed",
container.overflow.x = "scroll"
)
```
:::
::: {.callout-tip collapse="true"}
## Help
When you are unsure what arguments a function can take, it is possible to get a _help documentation_ using `help(pd.read_csv)`
:::
In most cases, data will be read in with the `pd.read_csv()` function, however, internal Python data structures can also be transformed into a pandas data frame.
For example using a nested list, were each row in the datafram is a list `[]`.
```{.python eval=False}
df = pd.DataFrame([[5,6], [8,4]], columns=["A", "B"])
df
```
::: {.callout-note collapse="true"}
## Expand to see output
| |A|B|
|-|-|-|
|0|5|6|
|1|8|4|
:::
Another usful transformation is from a dictionary ([https://docs.python.org/3/tutorial/datastructures.html#dictionaries](https://docs.python.org/3/tutorial/datastructures.html#dictionaries)) to pd.Dataframe.
```{.python eval=False}
table_data = {'A' : [5, 6]
'B' : [8, 4]}
df = pd.DataFrame(table_data)
df
```
::: {.callout-note collapse="true"}
## Expand to see output
| |A|B|
|-|-|-|
|0|5|6|
|1|8|4|
:::
There are many ways to turn a `DataFrame` back into a dictonary ([https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_dict.html#pandas.DataFrame.to_dict](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_dict.html#pandas.DataFrame.to_dict)), which might be very handy for certain purposes.
## Data exploration
The data for this tutorial/walkthrough is from a customer personality analysis of a company trying to better understand how to modify their product catalogue.
Here is the link to the original source ([https://www.kaggle.com/datasets/imakash3011/customer-personality-analysis](https://www.kaggle.com/datasets/imakash3011/customer-personality-analysis)) for more information.
### Columns
To display all the column names from the imported `DataFrame`, the attribute `columns` can be called.
```python{.python eval=False}
df.columns
```
::: {.callout-note collapse="true"}
## Expand to see output
```
Index(['ID', 'Year_Birth', 'Education', 'Marital_Status', 'Income', 'Kidhome',
'Teenhome', 'MntWines', 'MntFruits', 'MntMeatProducts',
'MntFishProducts', 'MntSweetProducts', 'MntGoldProds',
'NumWebPurchases', 'NumCatalogPurchases', 'NumStorePurchases',
'NumWebVisitsMonth', 'Complain', 'Z_CostContact', 'Z_Revenue'],
dtype='object')
```
:::
Each column has its own data types which are highly optimised.
A column with only integers has the data type `int64`.
Columns with decimal numbers are called `float64`.
A column with only strings, or a combination of strings and `integers` or `floats` is called an `object`.
```{.python eval=False}
df.dtypes
```
::: {.callout-note collapse="true"}
## Expand to see output
```
ID int64
Year_Birth int64
Education object
Marital_Status object
Income float64
Kidhome int64
Teenhome int64
MntWines int64
MntFruits int64
MntMeatProducts int64
MntFishProducts int64
MntSweetProducts int64
MntGoldProds int64
NumWebPurchases int64
NumCatalogPurchases int64
NumStorePurchases int64
NumWebVisitsMonth int64
Complain int64
Z_CostContact int64
Z_Revenue int64
dtype: object
```
:::
::: {.callout-tip collapse="true"}
## What does 64 stand for?
The 64 indicates the number of bits the integers are stored in.
64 bits is the largest pandas handels.
When it is known that a value is in a certain range, it is possible to change the bits to 8, 16, or 32.
This chosing the correct range might reduce memory usage, to be save, 64 range is so large it will incorporate most user cases.
```python{.python eval=False}
df['Kidhome'] = df['Kidhome'].astype('int8')
```
:::
### Inspecting the DataFrame
To quickly check how many rows and columns the `DataFrame` has, we can access the `shape` attribute.
```{.python eval=False}
df.shape
```
::: {.callout-note collapse="true"}
## Expand to see output
```
(1754, 20)
```
:::
The `.shape` attribute of a DataFrame provides a tuple representing its dimensions.
A tuple is a Python data structure that is used to store ordered items.
In the case of shape, the first item is always the row, and the second item is the columns.
To print, or access the rows or columns the index can be used.
`.shape[0]` gives the number of rows, and `.shape[1]` gives the number of columns.
```{.python eval=False}
df.shape[0]
```
::: {.callout-note collapse="true"}
## Expand to see output
```
1754
```
:::
```{.python eval=False}
df.shape[1]
```
::: {.callout-note collapse="true"}
## Expand to see output
```
20
```
:::
:::{.callout-tip}
It is often useful to have a quick look at the first rows, to get, for example, an idea of the data was read correctly.
This can be done with the `head()` function.
:::
```{.python eval=False}
df.head()
```
::: {.callout-note collapse="true"}
## Expand to see output
```{r}
#| echo: false
#| results: 'asis'
#| message: false
#| warning: false
library(tidyverse)
library(gt)
# Load the data from CSV
data <- read_csv("assets/images/chapters/python-pandas/table_2_all_data_head.csv")
# Create the table with gt
data %>%
gt() %>%
tab_options(
table.width = pct(100),
table.layout = "fixed",
container.overflow.x = "scroll"
)
```
:::
:::{.callout-tip collapse="true"}
## Fuctions and attributes
The difference between calling a function and an atribute is the `()`.
`.head()` is a function and will perform an action.
While `.shape` is an attribute and will return a value that is already stored in the `DataFrame`.
:::
What we can see it that, unlike _R_, _Python_ and in extension _Pandas_ is 0-indexed instead of 1-indexed.
### Accessing rows and columns
It is possible to access parts of the data in `DataFrames` in different ways.
The first method is sub-setting rows using the row name and column name.
This can be done with the `.loc`, which _loc_ ates row(s) by providing the row name and column name `[row, column]`.
When the rows are not named, the row index can be used instead.
To print the second row, this would be index 1 since the index in Python starts at 0.
To print the all the columns, the `:` is used.
```{.python eval=False}
df.loc[1, :]
```
::: {.callout-note collapse="true"}
## Expand to see output
```
ID 2174
Year_Birth 1954
Education Graduation
Marital_Status Single
Income 46344.0
Kidhome 1
Teenhome 1
MntWines 11
MntFruits 1
MntMeatProducts 6
MntFishProducts 2
MntSweetProducts 1
MntGoldProds 6
NumWebPurchases 1
NumCatalogPurchases 1
NumStorePurchases 2
NumWebVisitsMonth 5
Complain 0
Z_CostContact 3
Z_Revenue 11
Name: 1, dtype: object
```
:::
To print a range of rows, the first and last index can be written with a `:`.
To print the second and third row, this would be `[1:2, :]`.
```{.python eval=False}
df.loc[1:2]
```
::: {.callout-note collapse="true"}
## Expand to see output
```{r}
#| echo: false
#| results: 'asis'
#| message: false
#| warning: false
library(tidyverse)
library(gt)
# Load the data from CSV
data <- read_csv("assets/images/chapters/python-pandas/table_3_all_data_first_2_lines.csv")
# Create the table with gt
data %>%
gt() %>%
tab_options(
table.width = pct(100),
table.layout = "fixed",
container.overflow.x = "scroll"
)
```
:::
To print all the rows with a certain column name works the same as subsetting rows, but then adding the column name after the comma.
```{.python eval=False}
df.loc[:, "Year_Birth"]
```
::: {.callout-note collapse="true"}
## Expand to see output
```
0 1957
1 1954
2 1965
3 1984
4 1967
...
1749 1977
1750 1974
1751 1967
1752 1981
1753 1956
```
:::
It is important to notice that almost all operations on `DataFrames` are not in place, meaning that the `DataFrame` is not modified.
To keep the changes, the `DataFrame` has to be actively stored using the same name or a new variable.
To save the changes, a new `DataFrame` has to be created, or the existing `DataFrame` has to be overwritten.
This can be done by directing the output to a variable with `=`.
To make a new `DataFrame` with only the "Education" and "Marital_Status" columns, the column names have to be placed in a list `['colname1', 'colname2']`.
```{.python eval=False}
df.head()
new_df = df.loc[:, ["Education", "Marital_Status"]]
new_df
```
::: {.callout-note collapse="true"}
## Expand to see output
||Education|Marital_Status|
|-|-|-|
|0|Graduation|Single|
|1|Graduation|Single|
|2|Graduation|Together|
|3|Graduation|Together|
|4|Master|Together|
|…|…|…|
|1749|Graduation|Together|
|1750|Graduation|Married|
|1751|Graduation|Married|
|1752|Graduation|Divorced|
|1753|Master|Together|
|1754 rows × 2 columns|
:::
It is also possible to remove rows and columns from a `DataFrame`.
This can be done with the function `drop()`.
To remove the columns `Z_CostContact` and `Z_Revenue` and keep those changes, it is necessary to overwrite the `DataFrame`.
To make sure `Pandas` understands that the its `columns` that need to be removed, the `axis` can be specified.
Rows are called `axis=0`, and columns are called `axis=1`.
In most cases `Pandas` will guess correctly without specifying the axis, since in this case the no row is called `Z_CostContact` or `Z_Revenue`.
It is however good practice to add the axis to make sure `Pandas` is operating as expected.
```{.python eval=False}
df = df.drop("Z_CostContact", axis=1)
df = df.drop("Z_Revenue", axis=1)
```
::: {.callout-tip collapse="true"}
## Can be done in one go
```
df = df.drop(["Z_CostContact", "Z_Revenue"], axis=1)
```
:::
### Conditional subsetting
So far, all the subsetting has been based on `row names` and column names.
However, in many cases, it is more helpful to look only at data that contain certain items.
This can be done using conditional subsetting, which is based on Boolean values `True` or `False`.
pandas will interpret a series of True and `False` values by printing only the rows or columns where a `True` is present and ignoring all rows or columns with a `False`.
For example, if we are only interested in individuals in the table who graduated, we can test each string in the column Education to see if it is equal (==) to Graduation.
This will return a series with Boolean values `True` or `False`.
```{.python eval=False}
education_is_grad = (df["Education"] == "Graduation")
education_is_grad
```
:::{.callout-note collapse="true"}
## Expand to see output
```
0 True
1 True
2 True
3 True
4 False
...
1749 True
1750 True
1751 True
1752 True
1753 False
Name: Education, Length: 1754, dtype: bool
```
:::
To quicky check if the `True` and `False` values are correct, it can be useful to print out this column.
```{.python eval=False}
df["Education"]
```
:::{.callout-note collapse="true"}
## Expand to see output
```
0 Graduation
1 Graduation
2 Graduation
3 Graduation
4 Master
… …
1749 Graduation
1750 Graduation
1751 Graduation
1752 Graduation
1753 Master
Name: Education, length: 1754, dtype: object
```
:::
It is possible to provide pandas with multiple conditions at the same time.
This can be done by combining multiple statements with `&`.
```{.python eval=False}
two_at_once = (df["Education"] == "Graduation") & (df["Marital_Status"] == "Single")
two_at_once
```
::: {.callout-note collapse="true"}
## Expand to see output
```
0 True
1 True
2 False
3 False
4 False
...
1749 False
1750 False
1751 False
1752 False
1753 False
Length: 1754, dtype: bool
```
:::
To find out the total number of Graduated singles, the `.sum()` can be used.
```{.python eval=False}
sum(two_at_once)
```
::: {.callout-note collapse="true"}
## Expand to see output
```
252
```
:::
These `Series` of Booleans can be used to subset the dataframe to rows where the condition(s) are _True_:
```{.python eval=False}
df[two_at_once]
```
:::{.callout-note collapse="true"}
## Expand to see output
```{r}
#| echo: false
#| results: 'asis'
#| message: false
#| warning: false
library(tidyverse)
library(gt)
# Load the data from CSV
data <- read_csv("assets/images/chapters/python-pandas/table_4_all_data_conditional_subset.csv")
# Create the table with gt
data %>%
gt() %>%
tab_options(
table.width = pct(100),
table.layout = "fixed",
container.overflow.x = "scroll"
)
```
252 rows × 20 columns
:::
It is not actually necessary to create a `series` every time for subsetting the table and it can be done in one go by combining the conditions within the _`df[]`_.
```python
df[(df["Education"] == "Master") & (df["Marital_Status"] == "Single")]
```
:::{.callout-note collapse="true"}
## Expand to see output
```{r}
#| echo: false
#| results: 'asis'
#| message: false
#| warning: false
library(tidyverse)
library(gt)
# Load the data from CSV
data <- read_csv("assets/images/chapters/python-pandas/table_5_all_data_conditional_subset2.csv")
# Create the table with gt
data %>%
gt() %>%
tab_options(
table.width = pct(100),
table.layout = "fixed",
container.overflow.x = "scroll"
)
```
75 rows × 20 columns
:::
### Describing a DataFrame
Sometimes is is nice to get a quick overview of the data in a table, such as `means` and `counts`.
`Pandas` has a native function to do just that, it will output a `count`, `mean`, `standard deviation`, `minimum`, `25th percentile (Q1)`, `median (50th percentile or Q2)`, `75th percentile (Q3)`, and `maximum` for each numeric columns.
```{.python eval=False}
df.describe()
```
:::{.callout-note collapse="true"}
## Expand to see output
```{r}
#| echo: false
#| results: 'asis'
#| message: false
#| warning: false
library(tidyverse)
library(gt)
# Load the data from CSV
data <- read_csv("assets/images/chapters/python-pandas/table_6_Describing_df.csv")
# Create the table with gt
data %>%
gt() %>%
tab_options(
table.width = pct(100),
table.layout = "fixed",
container.overflow.x = "scroll"
)
```
8 rows × 18 columns
:::
We can also directly calculate the relevant statistics on numberic columns or rows we are interested in using the functions `max()`, `min()`, `mean()`, `median()` etc..
```{.python eval=False}
df["MntWines"].max()
```
:::{.callout-note collapse="true"}
## Expand to see output
```
1492
```
:::
```{.python eval=False}
df[["Kidhome", "Teenhome"]].mean()
```
:::{.callout-note collapse="true"}
## Expand to see output
```
Kidhome 0.456100
Teenhome 0.480616
dtype: float64
```
:::
There are also ceartin functions that are usfule for non-numeric columns.
To know which stings are present in a `object`, the fuction `unique()` can be used, this will returns an `array` with the unique values in the column or row.
```{.python eval=False}
df["Education"].unique()
```
:::{.callout-note collapse="true"}
## Expand to see output
```
array(['Graduation', 'Master', 'Basic', '2n Cycle'], dtype=object)
```
:::
To know how often a value is present in a column or row, the function `value_counts()` can be used.
This will print a `series` for all the unique values and print a count.
```{.python eval=False}
df["Marital_Status"].value_counts()
```
:::{.callout-note collapse="true"}
## Expand to see output
```
Marital_Status
Married 672
Together 463
Single 382
Divorced 180
Widow 53
Alone 2
Absurd 2
Name: count, dtype: int64
```
:::
### Getting summary statistics on grouped data
`Pandas` is equipped with lots of useful functions which make complicated tasks very easy and fast.
One of these functions is `.groupby()` with the arguments `by=...`, which will group a `DataFrame` using a categorical column (for example `Education` or `Marital_Status`).
This makes it possible to perform operations on a group directly without the need for subsetting.
For example, to get a mean income value for the different Education levels in the `DataFrame` can be done by specifying the column name for the grouping variable by `.groupby(by='Education')` and specifying the column name to perform this action on `[Income]` followed by the `sum()` function.
```{.python eval=False}
df.groupby(by="Education")["Income"].mean()
```
:::{.callout-note collapse="true"}
## Expand to see output
```
Education
2n Cycle 47633.190000
Basic 20306.259259
Graduation 52720.373656
Master 52917.534247
Name: Income, dtype: float6
```
:::
### Subsetting Questions and Exercises
Here there are several exercises to try conditional subsetting.
Try to first before seeing the awnsers.
::: {.callout-tip title="Question" appearance="simple"}
How many Single people are there in the table that also greduated? And how many are single?
:::
::: {.callout-note collapse="true" title="Answer"}
```{.python eval=False}
sum(df["Marital_Status"] == "Single")
```
::: {.callout-note collapse="true"}
## Expand to see output
```
382
```
:::
:::
::: {.callout-tip title="Question" appearance="simple"}
Subset the `DataFrame` with people born before 1970 and after 1970 and store both `DataFrames`
:::
::: {.callout-note collapse="true" title="Answer"}
```{.python eval=False}
df_before = df[df["Year_Birth"] < 1970]
df_after = df[df["Year_Birth"] >= 1970]
```
:::
::: {.callout-tip title="Question" appearance="simple"}
How many people are in the two `DataFrames`?
:::
::: {.callout-note collapse="true" title="Answer"}
```{.python eval=False}
print("n(before) =", df_before.shape[0])
print("n(after) =", df_after.shape[0])
```
::: {.callout-note collapse="true"}
## Expand to see output
```
n(before) = 804
n(after) = 950
```
:::
:::
::: {.callout-tip title="Question" appearance="simple"}
Do the total number of people sum up to the original `DataFrame` total?
:::
::: {.callout-note collapse="true" title="Answer"}
```{.python eval=False}
df_before.shape[0] + df_after.shape[0] == df.shape[0]
```
:::{.callout-note collapse="true"}
## Expand to see output
True
:::
```{.python eval=False}
print("n(sum) =", df_before.shape[0] + df_after.shape[0])
print("n(expected) =", df.shape[0])
```
:::{.callout-note collapse="true"}
## Expand to see output
```
n(sum) = 1754
n(expected) = 1754
```
:::
:::
::: {.callout-tip title="Question" appearance="simple"}
How does the mean income of the two groups differ?
:::
::: {.callout-note collapse="true" title="Answer"}
```{.python eval=False}
print("income(before) =", df_before["Income"].mean())
print("income(after) =", df_after["Income"].mean())
```
:::{.callout-note collapse="true"}
## Expand to see output
income(before) = 55513.38113207547
income(after) = 47490.29255319149
:::
:::
::: {.callout-tip title="Question" appearance="simple"}
**Bonus**: Can you find something else that differs a lot between the two groups?
:::
::: {.callout-note collapse="true" title="Answer"}