Inspeção básica de DataFrame
Use head(), tail(), info(), describe() e shape para entender rapidamente o conteúdo e a estrutura de qualquer DataFrame.
Inspeção básica de DataFrame é uma aula grátis de Pandas & NumPy Academy no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Pandas & NumPy Academy, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Pandas & NumPy Academy inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em inglês.
The First Five Steps with Any DataFrame
Whenever you load a new dataset, a systematic inspection sequence saves hours of debugging. The Pandas toolkit for this includes: head() to see the first rows, tail() for the last rows, info() for column types and nulls, describe() for statistics, and shape for dimensions. Running these five checks takes less than a minute and reveals most data quality issues immediately.
import pandas as pd
# Assume df is loaded from a CSV
print(df.shape) # (rows, cols)
df.head() # first 5 rows
df.info() # dtypes + non-null counts
df.describe() # statisticshead() and tail()
df.head(n) returns the first n rows (default 5) as a DataFrame. df.tail(n) returns the last n rows. Together they help you verify that the data was parsed correctly — checking that column names are in the header row, that numeric columns contain numbers, and that date strings were not misinterpreted. They are non-destructive and return new DataFrames.
import pandas as pd
df = pd.DataFrame({'a': range(20), 'b': range(20, 40)})
print(df.head(3))
# a b
# 0 0 20
# 1 1 21
# 2 2 22
print(df.tail(2))
# a b
# 18 18 38
# 19 19 39info(): Types and Non-Null Counts
df.info() prints a concise summary: the index dtype, the number of non-null values per column, each column's dtype, and the total memory usage. Columns with fewer non-null values than the total row count have missing data. Object dtype often means a string column (or a mixed-type column) that may need cleaning before analysis.
import pandas as pd
import numpy as np
df = pd.DataFrame({'name': ['A', 'B', None],
'score': [80.0, np.nan, 90.0],
'grade': ['A', 'C', 'A']})
df.info()
# Column Non-Null Count Dtype
# name 2 non-null object
# score 2 non-null float64
# grade 3 non-null objectdescribe(): Statistical Summary
df.describe() computes count, mean, std, min, 25th, 50th (median), 75th percentile, and max for all numeric columns. Pass include='all' to also summarise object (string) columns. Pass include='object' to only summarise categoricals. The output is itself a DataFrame, so you can save it or style it for a report.
import pandas as pd
df = pd.DataFrame({'age': [25, 30, 35, 40], 'score': [88, 72, 91, 65]})
print(df.describe().round(1))
# age score
# count 4.0 4.0
# mean 32.5 79.0
# std 6.5 12.0shape, ndim, and size
df.shape is a tuple (nrows, ncols). df.ndim always returns 2 for DataFrames. df.size is the total number of cells. Use len(df) for the number of rows (same as df.shape[0]). These are the simplest sanity checks — confirm the expected row count after loading and after each filtering step.
import pandas as pd
df = pd.DataFrame({'x': range(100), 'y': range(100), 'z': range(100)})
print(df.shape) # (100, 3)
print(len(df)) # 100
print(df.size) # 300
print(df.ndim) # 2dtypes and select_dtypes()
df.dtypes returns a Series mapping each column name to its dtype. df.select_dtypes(include='number') returns a new DataFrame with only numeric columns — useful for computing correlations or applying numeric transformations without accidentally operating on string columns. Pass exclude='object' to drop text columns.
import pandas as pd
df = pd.DataFrame({'a': [1,2], 'b': [1.0,2.0], 'c': ['x','y']})
print(df.dtypes)
# a int64
# b float64
# c object
numeric = df.select_dtypes(include='number')
print(numeric.columns.tolist()) # ['a', 'b']isnull() and Null Counts
df.isnull().sum() gives the count of missing values per column — the quickest way to find which columns need cleaning. Divide by len(df) to get the proportion of missing values. A column with more than 50% missing often needs special treatment: either drop it or apply domain-specific imputation.
import pandas as pd
import numpy as np
df = pd.DataFrame({'a': [1, np.nan, 3], 'b': [np.nan, np.nan, 6]})
print(df.isnull().sum())
# a 1
# b 2
print((df.isnull().sum() / len(df)).round(2))
# a 0.33
# b 0.67value_counts() on a DataFrame Column
Calling df['col'].value_counts() lists the frequency of each unique value in that column, sorted by count. Add normalize=True for percentages. Use dropna=False to also count NaN as a category. This is the fastest way to check for category imbalance or unexpected values in a categorical column.
import pandas as pd
df = pd.DataFrame({'status': ['active','inactive','active','active','banned']})
print(df['status'].value_counts())
# active 3
# inactive 1
# banned 1
print(df['status'].value_counts(normalize=True).round(2))columns and index Inspection
df.columns.tolist() gives a plain Python list of column names — useful for programmatic manipulation or for logging. df.index shows the row labels and their type. Check df.index.is_unique to confirm no duplicate row labels exist, which is a prerequisite for many merge operations and time series calculations.
import pandas as pd
df = pd.DataFrame({'a': [1,2,3]}, index=['x', 'y', 'z'])
print(df.columns.tolist()) # ['a']
print(df.index.tolist()) # ['x', 'y', 'z']
print(df.index.is_unique) # Truesample() for Random Inspection
df.sample(n) returns n randomly selected rows without replacement. df.sample(frac=0.1) returns 10% of the rows. Set random_state= for reproducibility. Random sampling is better than head() for spotting issues in the middle of a large dataset that might not appear in the first few rows.
import pandas as pd
df = pd.DataFrame({'x': range(1000), 'y': range(1000)})
print(df.sample(3, random_state=42))
print(df.sample(frac=0.005, random_state=0)) # 0.5% of rowsmemory_usage() for Size Budgeting
df.memory_usage(deep=True) returns the memory used by each column in bytes. deep=True forces accurate measurement of object-dtype columns whose strings live outside the DataFrame buffer. Sum the values to get total memory. Use this before and after dtype downcasting to confirm you have reduced memory consumption.
import pandas as pd
df = pd.DataFrame({'a': range(10000), 'b': [str(i) for i in range(10000)]})
usage = df.memory_usage(deep=True)
print(usage)
print('Total bytes:', usage.sum())Quick Check
Test your understanding of basic DataFrame inspection from this lesson.
Lesson Recap
In this lesson you learned: head() and tail() let you visually inspect the start and end of a DataFrame, info() reveals dtypes and missing value counts in a single call, and describe() provides statistical summaries for numeric columns. Next up we load data from the most common file formats — CSV, Excel, and JSON — into DataFrames.
Perguntas Frequentes
A aula “Inspeção básica de DataFrame” é grátis?
Sim — o texto completo de “Inspeção básica de DataFrame” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Pandas & NumPy Academy, atualize para CoddyKit PRO. O curso de Pandas & NumPy Academy inclui 4 aulas no total.
O que vou aprender em “Inspeção básica de DataFrame”?
Use head(), tail(), info(), describe() e shape para entender rapidamente o conteúdo e a estrutura de qualquer DataFrame. Você pratica Pandas & NumPy Academy com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Pandas & NumPy Academy?
Nenhuma experiência prévia é necessária. Pandas & NumPy Academy no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.
Quanto tempo leva a aula “Inspeção básica de DataFrame”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Pandas & NumPy Academy?
Sim. Cada aula de Pandas & NumPy Academy inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Criando DataFrames
- Selecionando colunas e linhas
- Adicionando e removendo colunas
- Inspeção básica de DataFrame