From 71c9d64a242626b8872f2eea8afa0edac51064b9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nacho=20L=C3=B3pez?= <145539062+KrilinZ@users.noreply.github.com> Date: Mon, 3 Aug 2026 14:15:09 +0200 Subject: [PATCH 1/2] docs(readme): rewrite for clarity, SEO and AI answer engines --- README.md | 211 ++++++++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 181 insertions(+), 30 deletions(-) diff --git a/README.md b/README.md index 8985ea1..a0784fb 100644 --- a/README.md +++ b/README.md @@ -1,43 +1,194 @@ -# Pandas for machine learning + +
-Pandas is the best and most popular [Python](https://4geeks.com/lesson/intro-to-python) library for machine learning. This library offers a wide variety of functions that will help you manipulate data, optimize your machine-learning algorithm, and much more. This tutorial will help you to get familiar with this library and master the most used functionalities with code samples and video tutorials that will help you to create your first data frame, clean a dataset of information, read CSV files, etc. +# Pandas tutorial exercises -> This Pandas tutorial [is interactive using LearnPack](https://4geeks.com/learnpack) and also features an [AI mentor named Rigobot](https://4geeks.com/rigobot), which reads your code and answers all your questions immediately. +[![Certified by 4Geeks](https://img.shields.io/badge/4Geeks-certified-2563eb?style=flat-square)](https://github.com/4GeeksAcademy/python-pandas-tutorial) +[![LearnPack autograded](https://img.shields.io/badge/LearnPack-autograded-2563eb?style=flat-square)](https://github.com/learnpack/learnpack) +[![Open in Codespaces](https://img.shields.io/badge/Open%20in-Codespaces-fb5a1f?style=flat-square&logo=github)](https://github.com/codespaces/new/?repo=4GeeksAcademy/python-pandas-tutorial) -The exercises in this tutorial have been created after about 60 hours of development by many experts in machine learning and they have been carefully reviewed by our [contributors](https://github.com/4GeeksAcademy/python-functions-programming-exercises/graphs/contributors) to make sure you have the most accurate and important information that will help you start your machine learning career. +
-## Content table +🇬🇧 English  Â·  [🇪🇸 Español](https://github.com/4GeeksAcademy/python-pandas-tutorial/blob/HEAD/README.es.md) + -In this tutorial, we will see the most important and basic functions provided by Pandas that will help you work with data in machine learning. The following are some of the topics that will be covered in this tutorial. +This interactive Pandas tutorial ships 22 exercises, 18 of them graded automatically by pytest, that you solve inside a single `app.py` file. You practice Series, `date_range`, `apply`, DataFrames, `iloc`, `loc`, `head`, `tail`, column filtering, `del`, `value_counts` and `groupby` on two real CSV datasets included in the repository: 800 PokĂ©mon and 1,016,395 US baby-name records. Beginner level, around 3 hours. -| Exercise | Description of the topic | -|---------------|----------------------------------------------------------------------------------------------------------------------------------------------------| -|Install Pandas | These exercises cover how to install Pandas, how to import the Pandas library in a Python file, and how to create your first Python script. | -|DataSets | These exercises explain what datasets are and how to work with them. | -|Series | These exercises explain what Series are in Pandas and how to use them. | -|DataFrames | These exercises explain how to create an information DataFrame and what functions can be used to work with them. | -|Clean DataSets | This class covers what data cleaning is, the functions Pandas offers to clean up a dataset, and the best practices to use when cleaning a dataset. | + +## đź“‹ About this tutorial -## 🌱 How to start these exercises? +- **Difficulty:** beginner +- **Estimated duration:** 3 hours +- **Exercises:** 22 steps, 18 with automated tests +- **Technologies:** pandas, Python 3.10, pytest 6.2.5 +- **Grading:** incremental — LearnPack runs the tests of the current step against your `app.py` +- **Instruction languages:** English and Spanish (every exercise has `README.md` and `README.es.md`) +- **Datasets included:** `pokemon_data.csv` (800 rows, 12 columns) and `us_baby_names_right.csv` (1,016,395 rows) + -You can start this tutorial quickly using our `learn in one click` technology for your local machine or in the cloud in 2 simple steps, [click here to get started](https://s.4geeks.com/start?repo=https://github.com/4GeeksAcademy/python-pandas-tutorial&lang=us&utm_source=github&utm_medium=organic&utm_content=readme). +## 🎯 What will you learn? +Pandas is the library that turns a raw CSV file into something you can actually ask questions to. This tutorial takes you from an empty terminal to grouped aggregations over a million rows, in five blocks: -## Contributors +- **Environment.** Why an isolated environment matters, how to create one with `pipenv shell`, and how to install pandas inside it instead of polluting your global Python. +- **Series.** The one-dimensional structure: build a `pd.Series` from a Python list, generate a range of dates with `pd.date_range`, and transform every value at once with `Series.apply`. +- **DataFrames.** The two-dimensional table: create one from a list of lists, create one from a list of dictionaries, and load one from disk with `pd.read_csv`. +- **Reading and filtering.** Inspect data with `head` and `tail`, reach a single cell with `iloc`, select columns and row ranges with square brackets, and filter rows with boolean conditions inside `loc`. +- **Cleaning.** Drop a leftover index column with `del`, count how often each category appears with `value_counts`, and aggregate rows with `groupby(...).sum()`. -We would like to express our deepest gratitude to the following contributors for their invaluable support in making this tutorial possible. +![Diagram showing two pandas Series, one labelled apples with the values 3, 2, 0, 1 and another labelled oranges with the values 0, 3, 7, 2, being combined into a single DataFrame with both columns side by side and a shared index from 0 to 3](https://raw.githubusercontent.com/4GeeksAcademy/python-pandas-tutorial/main/.learn/assets/series_dataframe.png) -| Contributor | GitHub account | -|-------------------|-----------------------------------------------------| -| Alejandro Sanchez | [alesanchezr](https://github.com/alesanchezr) | -| MartĂ­n Suárez | [kiddopro](https://github.com/kiddopro) | -| Lorena Gubaira | [Lorenagubaira](https://github.com/Lorenagubaira) | -| Tomas Gonzalez | [tommygonzaleza](https://github.com/tommygonzaleza) | -| Hernán GarcĂ­a | [hernanjkd](https://github.com/hernanjkd) | -| Ernesto Gonzalez | [UmiKami](https://github.com/UmiKami) | -| Hector Chocobar | [hchocobar](https://github.com/hchocobar) | -| Charly ChacĂłn | [Charlytoc](https://github.com/Charlytoc) | -| AgustĂ­n Fernández | [Dasher83](https://github.com/Dasher83) | -| Ignacio Cordoba | [nachovz](https://github.com/nachovz) | +By the end you can answer questions such as "how many PokĂ©mon are legendary?" or "how many distinct baby names appear in a million-row dataset?" in two or three lines of code. -This tutorial and many other exercises are designed for students as part of the 4Geeks Academy's [Coding Bootcamp](https://4geeksacademy.com/us/coding-bootcamp). Currently, we have two courses available. The first one is the [Full Stack Developer Course](https://4geeksacademy.com/us/coding-bootcamps/part-time-full-stack-developer). In this course, you will learn technologies like HTML5, CSS3, JavaScript, Python, Flask, SQL and many others. The second one is the [Data Science Bootcamp](https://4geeksacademy.com/us/coding-bootcamps/datascience-machine-learning), where you will learn technologies like Python, Algorithms' basics, Pandas, SQL Database, and many other technologies. You can find more information about these courses and the upcoming **Blockchain and Web3** course on the official [4Geeks Academy](http://4geeksacademy.com/) web page. +## đź‘€ What will you build? + +There is no toy project at the end: you write real pandas code from the second exercise onward, always in the same `app.py` file at the root of the repository. These are the 22 steps, in order: + +- **Getting set up** — `00 Welcome`, `01 New Terminal`, `01.2 Pipenv`, `02 Install`. The tutorial engine takes over the first terminal, so you open a second one, run `pipenv shell` to enter an isolated environment, and install the library with `pipenv install pandas`. The install step is graded by looking for `pandas` inside `Pipfile.lock`. +- **Your first script** — `02.1 Create a Script`, `02.2 Import`. Create `app.py`, print `Hello World`, then `import pandas as pd`, load `.learn/assets/pokemon_data.csv` into a variable called `data_frame` and print it. +- **Datasets** — `03 Datasets`. Open the included PokĂ©mon CSV and read it as a human: 800 rows, one per PokĂ©mon, with columns for name, both types, HP, attack, defense, special attack, special defense, speed, generation and whether it is legendary. +- **Series** — `04 Series`, `04.1 Date Range`, `04.2 Series Apply`. Turn a list of ten ages into a Series, generate the twelve days between `2021-05-01` and `2021-05-12`, and divide every element of a Series by two with `apply`. +- **DataFrames from scratch** — `05 DataFrames`, `05.1 DataFrame Dict`. Build a car table with the columns `Brand`, `Model` and `Color` from a two-dimensional list, then rebuild it from a list of dictionaries and add a fourth row for a red Tesla Model S. +- **Exploring the PokĂ©mon dataset** — `05.2 DataFrame iLoc`, `05.3 DataFrame Head`, `05.4 DataFrame Tail`, `05.5 Print Columns`, `05.6 Loc Function`, `05.7 Filter and Count`. Print one single cell by position, the first three rows, the last three rows, the `Name` and `Type 1` columns for the first ten PokĂ©mon, every PokĂ©mon with an attack above 80, and finally count how many legendary PokĂ©mon exist. +- **Cleaning a million rows** — `06 Clean Datasets`, `06.1 Remove Column`, `06.2 Value Counts`, `06.3 Group By`. Load `us_baby_names_right.csv` (1,016,395 US birth records with name, year, gender, state and count), print its first five rows, delete the unnamed leftover index column, compare how many female and male records it holds, and count how many different names it contains. + +## 🎓 What do you need before starting? + +- **Basic Python.** Variables, lists, dictionaries, `print()` and running a file with `python app.py` is enough. If lists and loops still feel unfamiliar, do [Learn Python Loops and lists](https://4geeks.com/en/interactive-exercise/python-loops-lists-exercises) first. +- **No maths, statistics or machine-learning background.** Every exercise is solved with pandas functions, not with formulas. +- **A GitHub account** if you want to run everything in the cloud. The prepared environment already includes Python 3.10, pipenv, pytest and pandas, so there is nothing to install on your computer. +- **Around 3 hours** and a terminal you are willing to keep open. + +## âś… How does the automatic grading work? + +18 of the 22 steps ship a `test.py` next to their instructions, and grading is incremental: when you press the test button, LearnPack runs only the tests of the exercise you are on. Those tests check three different things. + +- **The source of your file.** Most tests read `app.py` as text and look for specific pieces: the regular expression `import\s*pandas\s*as\s*pd`, a call to `print(`, and depending on the exercise the words `loc`, `del`, `head`, `groupby`, `sum`, `len` or the exact dataset path `.learn/assets/pokemon_data.csv`. +- **The terminal output.** Your script is executed and its standard output is captured, then compared against the expected block character by character, column alignment included. This is why the exercises tell you exactly how many rows to print. +- **That you did not cheat.** `04.1`, `05.2`, `05.7` and `06.3` add an anti-hardcoding test: `05.2`, `05.7` and `06.3` require at least one `print(` whose argument does not start with a digit, and `04.1` rejects the text `DatetimeIndex(` anywhere in your file. Pasting the expected result fails even though the output would look perfect. + +17 exercises also include a hidden `solution.hide.py`, so you can compare your approach with the reference one after you pass. + +## đź’ˇ What mistakes should you avoid? + +1. **Importing pandas any other way.** Nearly every test runs the regular expression `import\s*pandas\s*as\s*pd` over your file, so `import pandas` or `from pandas import read_csv` fails even when the output is correct. +2. **Working outside the repository root.** The datasets are referenced as `.learn/assets/...`, a path relative to the project root, so `app.py` must sit next to `learn.json` and be executed from there. +3. **Returning instead of printing.** Grading captures standard output, so every result has to go through `print()`. A value that is only stored in a variable counts as no output at all. +4. **Hardcoding the expected answer.** A file whose only output is `print(65)` fails `05.7`, because the test demands at least one `print(` that is not followed directly by a digit — the same check runs in `05.2` and `06.3`. And `04.1` fails if the text `DatetimeIndex(` appears anywhere in your code. +5. **Printing the wrong number of rows.** `05.3` and `05.4` expect exactly three rows, `05.5` expects the first ten, and `06` and `06.1` expect five. Any other slice produces a different output block and fails. +6. **Forgetting `pipenv shell`.** The environment is not permanent: every time you open a new terminal you have to enter it again, or pandas will look uninstalled. +7. **Starting a new script on every exercise.** From `05.3` onward several statements say "use the same DataFrame variable you used in the previous exercise": you keep editing the same `app.py`. + +## âť“ Frequently asked questions + +### Do I need to know machine learning to follow this Pandas tutorial? + +No. The tutorial only assumes basic Python. Pandas is the data-handling step that comes *before* any model: you load a CSV, look at it, filter it and clean it. Nothing here trains a model or requires statistics. + +### Can I do the exercises without installing Python on my computer? + +Yes. The repository includes a dev container configuration with Python 3.10, Node.js 22 and the tutorial engine already installed, so opening it in a cloud environment such as GitHub Codespaces gives you a working terminal in a couple of minutes. Installing locally is optional and documented in the repository. + +### What is the difference between a Series and a DataFrame? + +A Series is one-dimensional, like a labelled list: `pd.Series([23, 45, 7])` gives you values with an index next to them. A DataFrame is two-dimensional, like a table or a spreadsheet, and each of its columns is in fact a Series. Exercises `04` to `04.2` cover Series; from `05` onward everything is DataFrames. + +### Why does my exercise fail if the terminal output looks correct? + +Because the comparison is literal. The tests look for the expected text inside your standard output, so a missing column, a different number of rows or a value printed with a different type produces a mismatch. Read the expected result block in the exercise and reproduce it exactly, including how many rows you print. + +### What datasets are included? + +Two, both inside `.learn/assets/`. `pokemon_data.csv` has 800 rows and 12 columns and is used from exercise `02.2` to `05.7`. `us_baby_names_right.csv` holds 1,016,395 US birth records taken from a well-known [Kaggle dataset](https://www.kaggle.com/kaggle/us-baby-names) and is used in the whole `06` cleaning block. + +### Can I use Jupyter Notebook or Google Colab instead? + +You can experiment anywhere you like, but the grading only reads `app.py` in the project root and the standard output it produces when executed, so to pass the tests your final code has to live in that file. + + +## 📝 Related tutorials + +- [Learn Python Interactively (beginner)](https://4geeks.com/en/interactive-exercise/python-beginner-exercises) +- [Learn Python Loops and lists Interactively](https://4geeks.com/en/interactive-exercise/python-loops-lists-exercises) +- [Learn Python Functions Interactively](https://4geeks.com/en/interactive-exercise/python-function-exercises) +- [Master Python by practice](https://4geeks.com/en/interactive-exercise/master-python-exercises) +- [Learn Object Oriented Programming with Python](https://4geeks.com/en/interactive-exercise/object-oriented-programing-with-python) +- [Linear Algebra in Python and NumPy](https://4geeks.com/en/interactive-exercise/linear-algebra-in-python-and-numpy) + +## 🚀 How to start + +The fastest path is the one-click launcher, which prepares the whole environment in the cloud for you: + +1. Open the [one-click launcher](https://s.4geeks.com/start?repo=https://github.com/4GeeksAcademy/python-pandas-tutorial&lang=us&utm_source=github&utm_medium=organic&utm_content=readme) and choose where you want to run the tutorial. + +2. Wait for the container to build. It installs Python 3.10, Node.js 22, pandas, pytest and the tutorial engine. + +3. Open a **new** terminal (menu → Terminal → New Terminal), because the tutorial engine keeps the first one busy. + +4. Follow the instructions on screen and press the test button on each exercise. + +You can also open the repository directly in [GitHub Codespaces](https://github.com/codespaces/new/?repo=4GeeksAcademy/python-pandas-tutorial) using the included `.devcontainer` configuration. + +## đź’» Local installation + +If you prefer to work on your own machine, you need Node.js 20+ and Python 3.10+ available in your terminal. + +1. Install the tutorial engine and its Python plugin: + + ```bash + npm i @learnpack/learnpack@5 -g + learnpack plugins:install @learnpack/python + ``` + +2. Clone the repository and move into it: + + ```bash + git clone https://github.com/4GeeksAcademy/python-pandas-tutorial.git + cd python-pandas-tutorial + ``` + +3. Create the environment and install the dependencies the exercises expect: + + ```bash + pipenv shell + pipenv install pandas + pip install pytest==6.2.5 pytest-testdox mock + ``` + +4. Start the tutorial and open the address it prints: + + ```bash + learnpack start + ``` + +> đź’ˇ Remember that `pipenv shell` has to be run again in every new terminal session. + +## 📚 How the exercises are organized + +Each step lives in its own folder under [`.learn/exercises`](https://github.com/4GeeksAcademy/python-pandas-tutorial/tree/HEAD/.learn/exercises), named with the number that fixes its position in the tutorial: + +- `README.md` and `README.es.md`: the instructions, in English and Spanish. +- `test.py`: the pytest file that grades the step, present in 18 of the 22 folders. +- `solution.hide.py`: the reference solution, present in 17 folders and hidden until you finish. + +The datasets and the screenshots used by the instructions are in `.learn/assets/`, and the tutorial metadata (title, description, difficulty, duration and grading mode) is in [`learn.json`](https://github.com/4GeeksAcademy/python-pandas-tutorial/blob/HEAD/learn.json). Your own code always goes in a single `app.py` file at the root of the project. + +## 🤝 Contributors + +Thanks to the people who built and reviewed these exercises: + +- Jose Mora — [@josemoracard](https://github.com/josemoracard) +- Alejandro Sanchez — [@alesanchezr](https://github.com/alesanchezr) +- Charly ChacĂłn — [@Charlytoc](https://github.com/Charlytoc) +- Tomas Gonzalez — [@tommygonzaleza](https://github.com/tommygonzaleza) +- MartĂ­n Suárez — [@kiddopro](https://github.com/kiddopro) +- Lorena Gubaira — [@Lorenagubaira](https://github.com/Lorenagubaira) +- Ehiber Graterol — [@ehiber](https://github.com/ehiber) +- Jennifer Toledo — [@jatv93](https://github.com/jatv93) +- Ernesto Gonzalez — [@UmiKami](https://github.com/UmiKami) +- Rodolfo Pacheco — [@rvpacheco](https://github.com/rvpacheco) +- Hernán GarcĂ­a — [@hernanjkd](https://github.com/hernanjkd) +- Deimian Vásquez — [@deimianvasquez](https://github.com/deimianvasquez) + +You can see the full list in the [contributors graph](https://github.com/4GeeksAcademy/python-pandas-tutorial/graphs/contributors). This tutorial is part of the interactive exercises maintained by [4Geeks Academy](https://4geeksacademy.com/us/coding-bootcamps/datascience-machine-learning) and is powered by [LearnPack](https://4geeks.com/en/learnpack) and the [Rigobot](https://4geeks.com/en/rigobot) AI mentor. Found a mistake or want to add an exercise? Open an [issue](https://github.com/4GeeksAcademy/python-pandas-tutorial/issues) or a pull request. + From 3c7ab18bebf0715abf6dc74ccf75380d1ce4dae2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nacho=20L=C3=B3pez?= <145539062+KrilinZ@users.noreply.github.com> Date: Mon, 3 Aug 2026 14:15:10 +0200 Subject: [PATCH 2/2] docs(readme): rewrite for clarity, SEO and AI answer engines --- README.es.md | 209 +++++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 179 insertions(+), 30 deletions(-) diff --git a/README.es.md b/README.es.md index 825c44b..8c87cb3 100644 --- a/README.es.md +++ b/README.es.md @@ -1,45 +1,194 @@ -# Pandas for machine learning +
+ +# Tutorial de Pandas: Interactivo, auto-corregido y con mentor de inteligencia artificial + +[![Certificado por 4Geeks](https://img.shields.io/badge/4Geeks-certificado-2563eb?style=flat-square)](https://github.com/4GeeksAcademy/python-pandas-tutorial) +[![Autocorregido con LearnPack](https://img.shields.io/badge/LearnPack-autocorregido-2563eb?style=flat-square)](https://github.com/learnpack/learnpack) +[![Abrir en Codespaces](https://img.shields.io/badge/Abrir%20en-Codespaces-fb5a1f?style=flat-square&logo=github)](https://github.com/codespaces/new/?repo=4GeeksAcademy/python-pandas-tutorial) + +
+ +🇪🇸 Español  Â·  [🇬🇧 English](https://github.com/4GeeksAcademy/python-pandas-tutorial/blob/HEAD/README.md) + + +Este tutorial interactivo de Pandas trae 22 ejercicios, 18 de ellos corregidos automáticamente con pytest, que resuelves dentro de un Ăşnico archivo `app.py`. Practicas Series, `date_range`, `apply`, DataFrames, `iloc`, `loc`, `head`, `tail`, filtrado de columnas, `del`, `value_counts` y `groupby` sobre dos datasets CSV reales incluidos en el repositorio: 800 PokĂ©mon y 1.016.395 registros de nombres de bebĂ©s en EE. UU. Nivel principiante, unas 3 horas. + + +## đź“‹ Sobre este tutorial + +- **Dificultad:** principiante +- **DuraciĂłn estimada:** 3 horas +- **Ejercicios:** 22 pasos, 18 con tests automáticos +- **TecnologĂ­as:** pandas, Python 3.10, pytest 6.2.5 +- **CorrecciĂłn:** incremental — LearnPack ejecuta los tests del paso actual sobre tu `app.py` +- **Idiomas de las instrucciones:** español e inglĂ©s (cada ejercicio tiene `README.es.md` y `README.md`) +- **Datasets incluidos:** `pokemon_data.csv` (800 filas, 12 columnas) y `us_baby_names_right.csv` (1.016.395 filas) -Pandas es la mejor y más popular biblioteca de [Python](https://4geeks.com/es/lesson/que-es-python-tutorial) para machine learning. Esta biblioteca ofrece una amplia variedad de funciones que te ayudarán a manipular datos, optimizar tu algoritmo de machine learning y mucho más. Este **tutorial de python pandas** te ayudaremos a familiarizarte con esta biblioteca y dominar las funcionalidades más utilizadas con ejemplos de cĂłdigo y tutoriales en video que te ayudarán a crear tu primer marco de datos (data frame), limpiar un dataset de informaciĂłn, leer archivos CSV, entre otras cosas... +## 🎯 ÂżQuĂ© vas a aprender? + +Pandas es la biblioteca que convierte un CSV en bruto en algo a lo que de verdad puedes hacerle preguntas. Este tutorial te lleva desde una terminal vacĂ­a hasta agregaciones agrupadas sobre un millĂłn de filas, en cinco bloques: + +- **Entorno.** Por quĂ© conviene aislar cada proyecto, cĂłmo crear el entorno con `pipenv shell` e instalar pandas dentro de Ă©l en lugar de ensuciar tu Python global. +- **Series.** La estructura de una dimensiĂłn: crear una `pd.Series` a partir de una lista de Python, generar un rango de fechas con `pd.date_range` y transformar todos los valores de golpe con `Series.apply`. +- **DataFrames.** La tabla de dos dimensiones: construir uno desde una lista de listas, construirlo desde una lista de diccionarios y cargarlo desde disco con `pd.read_csv`. +- **Leer y filtrar.** Asomarte a los datos con `head` y `tail`, llegar a una celda concreta con `iloc`, seleccionar columnas y rangos de filas con corchetes y filtrar filas con condiciones lĂłgicas dentro de `loc`. +- **Limpieza.** Eliminar una columna Ă­ndice sobrante con `del`, contar cuántas veces aparece cada categorĂ­a con `value_counts` y agrupar filas con `groupby(...).sum()`. + +![Diagrama que muestra dos Series de pandas, una llamada apples con los valores 3, 2, 0 y 1 y otra llamada oranges con los valores 0, 3, 7 y 2, combinándose en un Ăşnico DataFrame con ambas columnas juntas y un Ă­ndice compartido del 0 al 3](https://raw.githubusercontent.com/4GeeksAcademy/python-pandas-tutorial/main/.learn/assets/series_dataframe.png) + +Al terminar puedes responder preguntas como "Âżcuántos PokĂ©mon son legendarios?" o "Âżcuántos nombres distintos hay en un dataset de un millĂłn de filas?" con dos o tres lĂ­neas de cĂłdigo. + +## đź‘€ ÂżQuĂ© vas a construir? -> Este tutorial de pandas [es interactivo usando LearnPack](https://4geeks.com/es/learnpack-es) y tambien cuenta con un [mentor AI llamado Rigobot](https://4geeks.com/es/rigobot), que lee tu codigo y responde todas tus preguntas inmediatamente. +AquĂ­ no hay un proyecto final de juguete: escribes cĂłdigo real de pandas desde el segundo ejercicio, siempre en el mismo archivo `app.py` en la raĂ­z del repositorio. Estos son los 22 pasos, en orden: -Los ejercicios en este tutorial han sido creados en aproximadamente 80 horas de desarrollo por expertos en machine learning y revisados cuidadosamente por nuestros [colaboradores](https://github.com/4GeeksAcademy/python-functions-programming-exercises/graphs/contributors) para asegurarnos de que tengas la informaciĂłn más precisa e importante que te ayudará a comenzar tu carrera en machine learning. +- **Puesta a punto** — `00 Welcome`, `01 New Terminal`, `01.2 Pipenv`, `02 Install`. El motor del tutorial ocupa la primera terminal, asĂ­ que abres una segunda, entras al entorno aislado con `pipenv shell` e instalas la biblioteca con `pipenv install pandas`. Ese paso se corrige buscando `pandas` dentro del `Pipfile.lock`. +- **Tu primer script** — `02.1 Create a Script`, `02.2 Import`. Creas `app.py`, imprimes `Hello World` y despuĂ©s haces `import pandas as pd`, cargas `.learn/assets/pokemon_data.csv` en una variable llamada `data_frame` y la imprimes. +- **Datasets** — `03 Datasets`. Abres el CSV de PokĂ©mon incluido y lo lees como humano: 800 filas, una por PokĂ©mon, con columnas de nombre, sus dos tipos, HP, ataque, defensa, ataque especial, defensa especial, velocidad, generaciĂłn y si es legendario. +- **Series** — `04 Series`, `04.1 Date Range`, `04.2 Series Apply`. Conviertes una lista de diez edades en una Series, generas los doce dĂ­as que van del `2021-05-01` al `2021-05-12` y divides entre dos todos los elementos de una Series con `apply`. +- **DataFrames desde cero** — `05 DataFrames`, `05.1 DataFrame Dict`. Montas una tabla de coches con las columnas `Brand`, `Model` y `Color` a partir de una lista bidimensional, y luego la rehaces desde una lista de diccionarios añadiendo una cuarta fila para un Tesla Model S rojo. +- **Explorar el dataset de PokĂ©mon** — `05.2 DataFrame iLoc`, `05.3 DataFrame Head`, `05.4 DataFrame Tail`, `05.5 Print Columns`, `05.6 Loc Function`, `05.7 Filter and Count`. Imprimes una celda concreta por posiciĂłn, las tres primeras filas, las tres Ăşltimas, las columnas `Name` y `Type 1` de los diez primeros PokĂ©mon, todos los que tienen un ataque superior a 80 y, por Ăşltimo, cuentas cuántos legendarios hay. +- **Limpiar un millĂłn de filas** — `06 Clean Datasets`, `06.1 Remove Column`, `06.2 Value Counts`, `06.3 Group By`. Cargas `us_baby_names_right.csv` (1.016.395 registros de nacimientos en EE. UU. con nombre, año, gĂ©nero, estado y cantidad), imprimes sus cinco primeras filas, borras la columna Ă­ndice sin nombre que sobra, comparas cuántos registros femeninos y masculinos hay y cuentas cuántos nombres diferentes contiene. -## Contenidos a revisar en el tutorial de pandas +## 🎓 ÂżQuĂ© necesitas antes de empezar? -En este tutorial, veremos las funciones más importantes y básicas proporcionadas por Pandas que te ayudarán a trabajar con datos en machine learning. A continuaciĂłn, algunos de los temas que se cubrirán en este tutorial son: +- **Python básico.** Con variables, listas, diccionarios, `print()` y saber ejecutar un archivo con `python app.py` te sobra. Si las listas y los bucles todavĂ­a se te resisten, pasa antes por [Aprende listas y bucles de Python](https://4geeks.com/es/interactive-exercise/python-loops-lists-exercises-es). +- **Nada de matemáticas, estadĂ­stica ni machine learning.** Todos los ejercicios se resuelven con funciones de pandas, no con fĂłrmulas. +- **Una cuenta de GitHub** si quieres trabajar en la nube. El entorno preparado ya trae Python 3.10, pipenv, pytest y pandas, asĂ­ que no tienes que instalar nada en tu ordenador. +- **Unas 3 horas** y una terminal que puedas dejar abierta. -| Ejercicio | DescripciĂłn del tema | -|---------------|----------------------------------------------------------------------------------------------------------------------------------------------------| -|**Instalar Pandas** | Estos ejercicios cubren cĂłmo instalar Pandas, cĂłmo importar la biblioteca Pandas en un archivo de Python, y cĂłmo crear tu primer script en Python. | -|**DataSets** | Estos ejercicios explican quĂ© son los conjuntos de datos y cĂłmo trabajar con ellos. | -|**Series** | Estos ejercicios explican quĂ© son las **series** en Pandas y cĂłmo usarlas. | -|**DataFrames** | Estos ejercicios explican cĂłmo crear un **DataFrame** de informaciĂłn y quĂ© funciones se pueden usar para trabajar con ellos. | -|**Clean DataSets** | Esta clase cubre quĂ© es la limpieza de datos, las funciones que Pandas ofrece para limpiar un DataSet, y las mejores prácticas para limpiar un DataSet. | +## âś… ÂżCĂłmo funciona la correcciĂłn automática? -## 🌱 ÂżCĂłmo iniciar este tutorial de pandas? +18 de los 22 pasos incluyen un `test.py` junto a sus instrucciones, y la correcciĂłn es incremental: al pulsar el botĂłn de test, LearnPack ejecuta solo los tests del ejercicio en el que estás. Esos tests comprueban tres cosas distintas. -Puedes iniciar este tutorial rápidamente usando nuestra tecnologĂ­a `aprende en un clic` para tu máquina local o en la nube en 2 pasos sencillos, [haz click aqui para empezar](https://s.4geeks.com/start?repo=https://github.com/4GeeksAcademy/python-pandas-tutorial&lang=es&utm_source=github&utm_medium=organic&utm_content=readme). +- **El cĂłdigo fuente de tu archivo.** La mayorĂ­a abre `app.py` como texto y busca piezas concretas: la expresiĂłn regular `import\s*pandas\s*as\s*pd`, una llamada a `print(` y, segĂşn el ejercicio, las palabras `loc`, `del`, `head`, `groupby`, `sum`, `len` o la ruta exacta del dataset `.learn/assets/pokemon_data.csv`. +- **La salida de la terminal.** Tu script se ejecuta y se captura su salida estándar para compararla con el bloque esperado carácter a carácter, alineaciĂłn de columnas incluida. Por eso los enunciados te dicen exactamente cuántas filas imprimir. +- **Que no hayas hecho trampa.** `04.1`, `05.2`, `05.7` y `06.3` añaden un test antitrampas: `05.2`, `05.7` y `06.3` exigen al menos un `print(` cuyo argumento no empiece por un dĂ­gito, y `04.1` rechaza el texto `DatetimeIndex(` en cualquier parte del archivo. Pegar el resultado esperado hace fallar el ejercicio aunque la salida parezca perfecta. -## Colaboradores +17 ejercicios incluyen además un `solution.hide.py` oculto, para que compares tu soluciĂłn con la de referencia cuando ya hayas aprobado. -Queremos expresar nuestro más profundo agradecimiento a los siguientes colaboradores por su valioso apoyo en la creaciĂłn de este tutorial. +## đź’ˇ ÂżQuĂ© errores deberĂ­as evitar? -| Colaborador | Cuenta de GitHub | -|-------------------|-----------------------------------------------------| -| Alejandro Sanchez | [alesanchezr](https://github.com/alesanchezr) | -| MartĂ­n Suárez | [kiddopro](https://github.com/kiddopro) | -| Lorena Gubaira | [Lorenagubaira](https://github.com/Lorenagubaira) | -| Tomas Gonzalez | [tommygonzaleza](https://github.com/tommygonzaleza) | -| Hernán GarcĂ­a | [hernanjkd](https://github.com/hernanjkd) | -| Ernesto Gonzalez | [UmiKami](https://github.com/UmiKami) | -| Hector Chocobar | [hchocobar](https://github.com/hchocobar) | -| Charly ChacĂłn | [Charlytoc](https://github.com/Charlytoc) | -| AgustĂ­n Fernández | [Dasher83](https://github.com/Dasher83) | -| Ignacio Cordoba | [nachovz](https://github.com/nachovz) | +1. **Importar pandas de cualquier otra forma.** Casi todos los tests aplican la expresiĂłn regular `import\s*pandas\s*as\s*pd` sobre tu archivo, asĂ­ que `import pandas` o `from pandas import read_csv` fallan aunque la salida sea correcta. +2. **Trabajar fuera de la raĂ­z del repositorio.** Los datasets se referencian como `.learn/assets/...`, una ruta relativa a la raĂ­z del proyecto, asĂ­ que `app.py` tiene que estar junto a `learn.json` y ejecutarse desde ahĂ­. +3. **Devolver en lugar de imprimir.** La correcciĂłn captura la salida estándar, o sea que todo resultado tiene que pasar por `print()`. Un valor que solo se guarda en una variable cuenta como si no hubieras impreso nada. +4. **Escribir a mano la respuesta esperada.** Un archivo cuya Ăşnica salida sea `print(65)` falla en `05.7`, porque el test exige al menos un `print(` que no vaya seguido directamente de un dĂ­gito — la misma comprobaciĂłn se ejecuta en `05.2` y `06.3`. Y `04.1` falla si el texto `DatetimeIndex(` aparece en cualquier parte de tu cĂłdigo. +5. **Imprimir un nĂşmero de filas distinto.** `05.3` y `05.4` esperan exactamente tres filas, `05.5` espera los diez primeros elementos y `06` y `06.1` esperan cinco. Cualquier otro corte genera otro bloque de salida y no pasa. +6. **Olvidar `pipenv shell`.** El entorno no es permanente: cada vez que abras una terminal nueva tienes que volver a entrar, o parecerá que pandas no está instalado. +7. **Empezar un script nuevo en cada ejercicio.** A partir de `05.3` varios enunciados dicen "usa la misma variable DataFrame del ejercicio anterior": sigues editando el mismo `app.py`. -Este tutorial y muchos otros ejercicios están diseñados para estudiantes como parte del [Bootcamp de ProgramaciĂłn](https://4geeksacademy.com/us/coding-bootcamp) de 4Geeks Academy. Actualmente, tenemos dos cursos disponibles. El primero es el Curso de [Desarrollador Full Stack](https://4geeksacademy.com/us/coding-bootcamps/part-time-full-stack-developer), en este curso aprenderás tecnologĂ­as como HTML5, CSS3, JavaScript, Python, Flask, SQL y muchas otras. El segundo es el [Bootcamp de Data Science](https://4geeksacademy.com/us/coding-bootcamps/datascience-machine-learning) donde aprenderás tecnologĂ­as como Python, fundamentos de algoritmos, Pandas, bases de datos SQL y muchas otras tecnologĂ­as. Puedes encontrar más informaciĂłn sobre estos cursos y el prĂłximo curso de Blockchain y Web3 en la página web oficial de [4Geeks Academy](http://4geeksacademy.com/). +## âť“ Preguntas frecuentes + +### ÂżNecesito saber machine learning para hacer este tutorial de Pandas? + +No. Solo se da por supuesto Python básico. Pandas es el paso de manejo de datos que va *antes* de cualquier modelo: cargas un CSV, lo miras, lo filtras y lo limpias. AquĂ­ no se entrena ningĂşn modelo ni hace falta estadĂ­stica. + +### ÂżPuedo hacer los ejercicios sin instalar Python en mi ordenador? + +SĂ­. El repositorio incluye una configuraciĂłn de dev container con Python 3.10, Node.js 22 y el motor del tutorial ya instalados, asĂ­ que abrirlo en un entorno en la nube como GitHub Codespaces te da una terminal lista en un par de minutos. Instalarlo en local es opcional y está documentado en el repositorio. + +### ÂżCuál es la diferencia entre una Series y un DataFrame? + +Una Series es unidimensional, como una lista etiquetada: `pd.Series([23, 45, 7])` te da los valores con un Ă­ndice al lado. Un DataFrame es bidimensional, como una tabla o una hoja de cálculo, y cada una de sus columnas es en realidad una Series. Los ejercicios `04` a `04.2` cubren las Series; a partir del `05` todo son DataFrames. + +### ÂżPor quĂ© falla mi ejercicio si la salida de la terminal parece correcta? + +Porque la comparaciĂłn es literal. Los tests buscan el texto esperado dentro de tu salida estándar, asĂ­ que una columna de menos, un nĂşmero de filas distinto o un valor impreso con otro tipo ya provocan que no coincida. Lee el bloque de resultado esperado del enunciado y reprodĂşcelo tal cual, incluidas las filas que imprimes. + +### ÂżQuĂ© datasets vienen incluidos? + +Dos, ambos dentro de `.learn/assets/`. `pokemon_data.csv` tiene 800 filas y 12 columnas y se usa desde el ejercicio `02.2` hasta el `05.7`. `us_baby_names_right.csv` contiene 1.016.395 registros de nacimientos en EE. UU. sacados de un [dataset conocido de Kaggle](https://www.kaggle.com/kaggle/us-baby-names) y se usa en todo el bloque `06` de limpieza. + +### ÂżPuedo usar Jupyter Notebook o Google Colab en lugar de app.py? + +Puedes experimentar donde quieras, pero la correcciĂłn solo lee el `app.py` de la raĂ­z del proyecto y la salida estándar que produce al ejecutarse, asĂ­ que para aprobar los tests tu cĂłdigo final tiene que acabar en ese archivo. + + +## 📝 Tutoriales relacionados +- [Aprende Python Interactivamente (principiante)](https://4geeks.com/es/interactive-exercise/python-beginner-exercises-es) +- [Aprende listas y bucles de Python Interactivamente](https://4geeks.com/es/interactive-exercise/python-loops-lists-exercises-es) +- [Aprende las funciones de Python Interactivamente](https://4geeks.com/es/interactive-exercise/python-function-exercises-es) +- [Domina Python Practicando](https://4geeks.com/es/interactive-exercise/master-python-exercises-es) +- [Aprende ProgramaciĂłn Orientada a Objetos con Python](https://4geeks.com/es/interactive-exercise/aprende-programacion-orientada-a-objetos-con-python) +- [Aprende las Mejores Prácticas de Python](https://4geeks.com/es/interactive-exercise/aprende-las-mejores-practicas-de-python) + +## 🚀 CĂłmo empezar + +El camino más rápido es el lanzador de un clic, que te prepara todo el entorno en la nube: + +1. Abre el [lanzador de un clic](https://s.4geeks.com/start?repo=https://github.com/4GeeksAcademy/python-pandas-tutorial&lang=es&utm_source=github&utm_medium=organic&utm_content=readme) y elige dĂłnde quieres ejecutar el tutorial. + +2. Espera a que se construya el contenedor. Instala Python 3.10, Node.js 22, pandas, pytest y el motor del tutorial. + +3. Abre una terminal **nueva** (menĂş → Terminal → New Terminal), porque el motor del tutorial mantiene ocupada la primera. + +4. Sigue las instrucciones en pantalla y pulsa el botĂłn de test en cada ejercicio. + +TambiĂ©n puedes abrir el repositorio directamente en [GitHub Codespaces](https://github.com/codespaces/new/?repo=4GeeksAcademy/python-pandas-tutorial), que usa la configuraciĂłn `.devcontainer` incluida. + +## đź’» InstalaciĂłn local + +Si prefieres trabajar en tu propia máquina, necesitas Node.js 20 o superior y Python 3.10 o superior disponibles en tu terminal. + +1. Instala el motor del tutorial y su plugin de Python: + + ```bash + npm i @learnpack/learnpack@5 -g + learnpack plugins:install @learnpack/python + ``` + +2. Clona el repositorio y entra en la carpeta: + + ```bash + git clone https://github.com/4GeeksAcademy/python-pandas-tutorial.git + cd python-pandas-tutorial + ``` + +3. Crea el entorno e instala las dependencias que esperan los ejercicios: + + ```bash + pipenv shell + pipenv install pandas + pip install pytest==6.2.5 pytest-testdox mock + ``` + +4. Arranca el tutorial y abre la direcciĂłn que aparece en pantalla: + + ```bash + learnpack start + ``` + +> đź’ˇ Recuerda que `pipenv shell` hay que volver a ejecutarlo en cada terminal nueva. + +## 📚 CĂłmo están organizados los ejercicios + +Cada paso vive en su propia carpeta dentro de [`.learn/exercises`](https://github.com/4GeeksAcademy/python-pandas-tutorial/tree/HEAD/.learn/exercises), numerada para fijar su posiciĂłn en el tutorial: + +- `README.es.md` y `README.md`: las instrucciones, en español e inglĂ©s. +- `test.py`: el archivo de pytest que corrige el paso, presente en 18 de las 22 carpetas. +- `solution.hide.py`: la soluciĂłn de referencia, presente en 17 carpetas y oculta hasta que terminas. + +Los datasets y las capturas que usan los enunciados están en `.learn/assets/`, y los metadatos del tutorial (tĂ­tulo, descripciĂłn, dificultad, duraciĂłn y modo de correcciĂłn) están en [`learn.json`](https://github.com/4GeeksAcademy/python-pandas-tutorial/blob/HEAD/learn.json). Tu cĂłdigo siempre va en un Ăşnico archivo `app.py` en la raĂ­z del proyecto. + +## 🤝 Colaboradores + +Gracias a las personas que crearon y revisaron estos ejercicios: + +- Jose Mora — [@josemoracard](https://github.com/josemoracard) +- Alejandro Sanchez — [@alesanchezr](https://github.com/alesanchezr) +- Charly ChacĂłn — [@Charlytoc](https://github.com/Charlytoc) +- Tomas Gonzalez — [@tommygonzaleza](https://github.com/tommygonzaleza) +- MartĂ­n Suárez — [@kiddopro](https://github.com/kiddopro) +- Lorena Gubaira — [@Lorenagubaira](https://github.com/Lorenagubaira) +- Ehiber Graterol — [@ehiber](https://github.com/ehiber) +- Jennifer Toledo — [@jatv93](https://github.com/jatv93) +- Ernesto Gonzalez — [@UmiKami](https://github.com/UmiKami) +- Rodolfo Pacheco — [@rvpacheco](https://github.com/rvpacheco) +- Hernán GarcĂ­a — [@hernanjkd](https://github.com/hernanjkd) +- Deimian Vásquez — [@deimianvasquez](https://github.com/deimianvasquez) + +Puedes ver la lista completa en el [gráfico de colaboradores](https://github.com/4GeeksAcademy/python-pandas-tutorial/graphs/contributors). Este tutorial forma parte de los ejercicios interactivos que mantiene [4Geeks Academy](https://4geeksacademy.com/us/coding-bootcamps/datascience-machine-learning) y funciona con [LearnPack](https://4geeks.com/es/learnpack) y el mentor de IA [Rigobot](https://4geeks.com/es/rigobot). ÂżHas encontrado un error o quieres añadir un ejercicio? Abre un [issue](https://github.com/4GeeksAcademy/python-pandas-tutorial/issues) o una pull request. +