0% found this document useful (0 votes)
2 views

Pandas Basic

This document is a beginner's guide to using Pandas DataFrames, covering topics such as loading, inspecting, analyzing, and modifying data. It includes practical examples and methods for data manipulation, as well as installation instructions for Python, VS Code, and Jupyter. The document serves as a foundational resource for data analysis using Pandas.

Uploaded by

Alex Andrade
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Pandas Basic

This document is a beginner's guide to using Pandas DataFrames, covering topics such as loading, inspecting, analyzing, and modifying data. It includes practical examples and methods for data manipulation, as well as installation instructions for Python, VS Code, and Jupyter. The document serves as a foundational resource for data analysis using Pandas.

Uploaded by

Alex Andrade
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

PANDAS

DATAFRAMEPara iniciantes

2025
CONTEÚDO

1. Introdução pandas Dataframe .................................................... 04


2. Carregando dados em um DataFrame ....................................... 05
3. Inspecionando um DataFrame .................................................... 06
4. Acessando dados ........................................................................ 07
5. Analisando dados .........................................................................08
6. Modificando DataFrame .............................................................. 10
7. Tratando os dados do DataFrame .............................................. 12
ANEXO I - Instalando Python ........................................................... 18
ANEXO II - Instalando VS Code ....................................................... 22
ANEXO III - Instalando Jupyter ........................................................ 40
Referências ...................................................................................... 48
In this section, we will cover:
Loading data into a DataFrame:
Learn how to import datasets using the pd.read_csv() method, with
practical examples.

Inspecting DataFrames:
Explore essential methods to examine DataFrames, including .shape,

.columns, and .info() to understand their structure and details.


Analyzing data:

Discover techniques to check data types with .dtypes, summarize


statistics with .describe(), and identify missing values with

.isnull().sum().
Modifying DataFrames:

Master methods to add new columns, remove unnecessary ones, and

clean your dataset.

Pandas - Documentation

Arquivo para este exercício

ENCONTROU ALGUM ERRO, TEM ALGUMA SUGESTÃO?


ENTRE EM CONTATO:
REGILENE MARIANO
Introduction to Pandas DataFrames

Learn what a DataFrame is and how it compares to other structures,


such as spreadsheets or SQL tables.

DataFrame
A DataFrame is a two-dimensional data structure, similar to a table,
used in Pandas for storing and manipulating data. It consists of rows
and columns, allowing easy access and manipulation of data.

How it compares to other structures


Compared to spreadsheets, like Excel, a DataFrame offers greater
flexibility and processing power, especially for large volumes of data.

In relation to SQL tables, both are similar, but the DataFrame allows
faster and more dynamic operations within the Python environment,
while SQL tables are manipulated directly in databases.

4
Loading Data csv into a DataFrame

pd.read_csv()
df_car = pd.read_csv(‘.. /dado/df_car_raw’)
df_car.head()

Vamos subir um nível na hierarquia de diretórios com .. (dois pontinhos)

O caminho ../dados/df_car_raw.csv funciona assim:

1. .. sobe um nível (de aula01/ para projeto01/)

2. dados/df_car_raw.csv entra na pasta dados/ e acessa o arquivo.

5
Inspecting DataFrames
1. Shape
df_car.shape

The .shape attribute returns the number of rows and columns

2. Columns
df_car.columns

The .columns attribute lists the column names

3. Info
df_car.info

The .info() method provides a summary of the DataFrame, including column names, non- 6
null counts, and data types.
Accessing Data

1. Accessing Columns

You can access a single column (a Pandas Series)

To access multiple columns, use double square brackets

7
Analyzing Data

1. Checking Data Types

Each column in a DataFrame can have its own data type

Check the data type of a single column

Filter only numerical columns


df_car.select_dtypes(include=['number']).head() This command was used after
the data transformation

Convert data types (astype)


df_car['km'] = df_car['km'].astype(int)

Filter only categorical columns (strings/objects)

8
2. Descriptive Statistics
df_car.describe()

Quickly summarize numerical columns using .describe()

3. Checking for Missing Values


df_car.isnull().sum()

Identify missing values in each column

9
Modifying DataFrames
1. Adding New Columns

Let's create a new column called "descricao" by combining "marca", "modelo", and "ano"

df_car['descricao'] = df_car['marca'] + ' ' + df_car['modelo'] + ' (' + df_car['ano'].astype(str) + ')'

df_car['marca'] Car brand ( ex: FIAT )


df_car['modelo'] Car model ( ex: HB20 COMFORT 1.0 )

df_car['ano'].astype(str) Converts the year to a string (to avoid an error when adding an
int and a str)

We use + to concatenate the texts.

Let's check the new column 'descricao'

2. Dropping Columns
Remove unnecessary columns

If you want to view the DataFrame without the column but without permanently removing
it, use

df_car.drop(['descricao'], axis=1)

10
Let's remove the new column "descricao" from the DataFrame df_car
df_car.drop(['descricao'], axis=1, inplace=True)

'descricao' → The name of the column to be removed.


axis=1 → Specifies that we are removing a column (not a row).
inplace=True → Makes the change directly in df_car without needing to reassign

11
Transforming Data

1.Clean "ano" column


str.replace():
Method widely used in pandas for string manipulation in text columns of a DataFrame.

How it works:
str.replace() is used to replace a substring within strings in a DataFrame or Series
column. It accepts two main parameters:
1. The pattern (regex or string) to be replaced
2. The replacement string

df_car['ano'] = df_car['ano'].str.replace(r'\n\|', '', regex=True)

r'\n\|' is the pattern (regex) you want to remove.


'' is the replacement string (in this case, you want to remove it completely).

12
2. Clean "km" column

df_car['ano'] = df_car['ano'].str.replace(r'\n\|', '', regex=True)

df_car['km'] = df_car['km'].str.replace(r' km', '', regex=True).astype(float)

13
3. Clean "preco" column

print(df_car[['preco']])

df_car['preco'] = df_car['preco'].str.replace(r'R\$', '', regex=True).str.replace(r'\.', '', regex=True).str.replace(r'\s', '',


regex=True).astype(float)

r'R\$'
Removes the "R$" symbol (we need to use \ to escape the $ symbol).
r'\.'
Removes the dots (used to separate thousands).
r'\s'
Removes the spaces.
astype(float)
Converts the values to float so that you can perform calculations.

Now, the "preco" column should contain only numeric values! 14


Let's remove the second group (the number after the slash /) and also remove the slash.

df_car['ano'] = df_car['ano'].str.replace(r'/\d+', '', regex=True)

r'/\d+'
This pattern (regex) matches the slash / followed by one or more digits (\d+).
What will be removed is the slash and the numbers after it.
‘‘
Replaces the matched pattern (slash and numbers) with an empty string, meaning we
remove the slash and the second year.

15
Conclusion

In this article, we covered:

Loading and inspecting DataFrames


Accessing specific rows and columns
Performing basic operations like adding and dropping columns
Transformation and cleaning of some data

These techniques form the foundation of data analysis with Pandas. In the next lesson,
we’ll explore label-based indexing using .loc and positional indexing with .iloc to access
specific rows and columns.

16
ANEXOS

17
PYHTON - INSTALAÇÃO

FAÇA DOWNLOAD DA VERSÃO MAIS RECENTE DO PYTHON

PYHTON.ORG

DEPOIS DO DOWNLOAD EXECUTE O INSTALADOR

FAÇA AS SEGUINTES ESCOLHAS

18
CUSTOMIZE INSTALLATION

OPTIONAL FEATURES

ADVANCED OPTIONS

19
CLOSE

20
2.POWER SHELL

ABRA O POWER SHELL


Python --version

SE NÃO APARECE A VERSÃO DO PYTHON, REINICIE A MÁQUINA OU REINSTALE O


PYTHON

21
ANEXO II
Instalando VS CODE

VS CODE - Download

EXECUTE O INSTALADOR

FAÇA AS SEGUINTES ESCOLHAS

22
23
24
4. POWER SHELL- ExecutionPolicy

Abra o Power Shell como Administrador

Digite
Get-ExecutionPolicy

Caso o teu apareça Restricted

Precisamos dar permissão pro VS code criar e ativar ambientes virtuais

25
PS C:\Windows\system32> SET-ExecutionPolicy AllSigned -Force

Resposta esperada: AllSigned

26
5.AMBIENTE VIRTUAL

No VS Code vamos criar um ambiente virtual para testar a permissão AllSigned

Crie um diretório chamado “projeto”

No VS Code:

File > open Folder

Abra a pasta “projeto”

Yes, we trust

27
View > Terminal

Criar ambiente virtual


python -m venv venv

Ativar o Ambiente Virtual


.\venv\Scripts\activate

Escolha A - Sempre permitir

O ambiente virtual é ativado

28
O ambiente virtual está ativo

Para sair do Virtual Ambiente

deactivate

Read more:
Ambiente Virtual no VSCode com Python - Tutorial Completo

venv - Creation of virtual environments in Python

What is a Python Virtual Environment

Python Virtual Environment | Introduction

29
6.CONFIGURAÇÃO DO VS CODE

Manage > Setting

Salve qualquer alteração com:

CTRL + S

Manage > Setting > Compact Folders

Desmarque a opção Compact Folders

30
Observe que o JSON de configurações também refletiu as alterações

Explore os atalhos do VS CODE

Manage > Keyboard Shortcuts

Por exemplo: Copy Line

Este atalho copia linhas pra cima ou para baixo

PDF com atalhos VS Code

31
6.1. ARQUIVOS PYTHON SÃO MÓDULOS PYTHON

Create New File

Módulos python tem extensão .py

No exemplo:

aula1.py

Explore criação de files e folders

6.2. EXTENSÕES NO VS CODE

Python

VS Code IDE para Python

32
O que essa extensão faz?
Executa o código
Seleciona ambiente virtual
Debug

Extensão Code Runner

33
Configurando Extensão Code Runner

A extensão está executando no OUTPUT, para executar no TERMINAL, vamos configurar


ela em Manage > Seting > JSON

Manage > Setting > JSON

34
Acrescente a seguinte linha de configuração
"code-runner.runInTerminal": true

Salve a alteração CTRL + S

Execute o código novamente


Saída esperada:
Terminal

35
Em Manage > Setting > Json

Digite:
"code-runner.executorMap"

Apague todos os itens e deixe apenas Python


"python": "cls ; python -u"

Salve as alterações CTRL + S

Essas alterações o terminal é limpo, em seguida mostra a saída do código, ao mesmo


tempo.

36
Em Manage > Setting > JSON
Acrescente:
"code-runner.ignoreSelection": true

Extensão com Tema

Em Extensions digite om

Para o itálico, selecione o Default

37
Novamente em Extensions > Material Icon Theme

Em ícone escolha Material Icon Theme

Agora as pastas tem ícone ^^

38
Novamente Manage > Setting > JSON

Acrescente:

"python.defaultInterpreterPath": "python"

39
ANEXOS III

Instalando Extensão Jupyter

O que vamos fazer:

1.Criar o ambiente virtual

python -m venv venv

2. Ativar ambiente virtual

venv\Scripts\activate

3. Instalar Extensão do Jupyter

4. Instalar o Jupyter no ambiente virtual


pip install jupyter

5. Escolher Kernel

6. Escolher ambente virtual onde o Kernel funcionará

7. Pandas
import pandas as pd

40
1. Crie o ambiente virtual
No terminal
python -m venv venv

2. Ativar ambiente virtual

venv\Scripts\activate

3. Instalar extensão do Jupyter

Instalação do jupyter no VS CODE

No VS Code, abra a paleta de comandos (Ctrl + Shift + P).

Digite "Extensions: Install Extensions" e pressione Enter.


Pesquise por Jupyter e instale a extensão oficial da Microsoft.

41
Installe Jupyter no ambiente virtual
Abra um Notebook no VS Code

No VS Code, pressione Ctrl + Shift + P.


Digite "Jupyter: Create New Notebook" e selecione essa opção.
Quando o notebook abrir, clique na parte superior direita e selecione seu
ambiente virtual como kernel.

42
Um novo Notebook será criado

No terminal digite:

pip install jupyter

Quando terminar digite:

pip show jupyter

43
Quando terminar digite:

pip install pandas

Quando terminar digite:

pip show pandas

Selecione Select Kernel


Escolha o interpretador pyhton do seu ambiente virtual (deve ter o nome venv
ou o caminho correspondente)

44
import pandas as pd

CTRL + S para salvar

Adicione a extensão .ipynb ao seu notebook

45
Jupyter no navegador
No terminal digite:

jupyter notebook

46
Pronto! Você já pode usar seu notebook no navegador

47
Referências

Pyhton para iniciantes


Pyhton para Análise de Dados
Curso Python - Luiz Otávio Miranda
Pyhton do Zero
Pyhton do Zero - Canal Refatorando
Python Brasil - Lista de Exercícios
PEP 8 - Guia de Estilo Para Python
Como Escrever Melhor seu Código em Python - PEP8
Pandas documentation

You might also like