DataFrame
A DataFrame is a 2D table of labelled rows and columns — pandas' main object.
Syntax
pd.DataFrame({'col': [values]})A DataFrame is a table: labelled columns, a row index, and cells of data. Each column is a Series and may have its own type.
Creating one
The easiest way is a dictionary of columns. Use .head(), .info() and .describe() to inspect it.
Example
import pandas as pd
df = pd.DataFrame({
'name': ['Ann', 'Bob', 'Cara'],
'age': [34, 29, 41],
'city': ['Paris', 'Rome', 'Oslo'],
})
print(df.shape) # (3, 3)
print(df.columns.tolist()) # ['name', 'age', 'city']
print(df['age'].mean()) # 34.666...
df.head()When to use it
- A data scientist loads a customer transaction table into a DataFrame to inspect dtypes, check for nulls, and compute summary statistics before modelling.
- An ML engineer builds a feature matrix by constructing a DataFrame from a dict of arrays, then passes .values to a scikit-learn model.
- A reporting analyst creates a DataFrame from a JSON API response to group, filter, and export results to a new CSV file.
More examples
Create DataFrame from a dict
Builds a DataFrame from a dictionary where keys become column names, then inspects each column's data type.
import pandas as pd
df = pd.DataFrame({
'name': ['Alice', 'Bob', 'Carol'],
'age': [28, 34, 45],
'score': [88.5, 72.0, 95.3]
})
print(df)
print(df.dtypes)Quick data overview
Uses shape, head, and describe to get an immediate overview of a dataset's size, sample rows, and numerical statistics.
import pandas as pd
df = pd.read_csv('titanic.csv')
print(df.shape) # rows, columns
print(df.head(3)) # first 3 rows
print(df.describe()) # count, mean, std, min, maxAdd and drop columns
Adds a computed revenue column from two existing columns and then removes the qty column, showing how to engineer and prune DataFrame features.
import pandas as pd
df = pd.DataFrame({'price': [100, 200, 150], 'qty': [3, 1, 2]})
df['revenue'] = df['price'] * df['qty']
df = df.drop(columns=['qty'])
print(df)
Discussion