Teach me pandas dataframe
- User
Teach me pandas dataframe
- Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Teach me pandas dataframe
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Pandas is a powerful and widely-used Python library for data manipulation and analysis. The core data structure in Pandas is the DataFrame, which is essentially a 2-dimensional labeled data structure with columns of potentially different types, similar to a spreadsheet or SQL table. In this tutorial, I'll walk you through the basics of working with Pandas DataFrames, including creating, manipulating, and analyzing data.
Before you begin, you need to install Pandas if you haven't already. You can install it using pip:
pip install pandas
Once installed, you can import Pandas in your Python script or Jupyter notebook:
import pandas as pd
The pd alias is a common convention for referring to Pandas.
A DataFrame can be created in several ways, such as from a dictionary, list of dictionaries, NumPy arrays, or by reading data from files (e.g., CSV, Excel).
data = {
'Name': ['Alice', 'Bob', 'Charlie', 'David'],
'Age': [25, 30, 35, 40],
'City': ['New York', 'Los Angeles', 'Chicago', 'Houston']
}
df = pd.DataFrame(data)
print(df)
Output:
Name Age City
0 Alice 25 New York
1 Bob 30 Los Angeles
2 Charlie 35 Chicago
3 David 40 Houston
Name, Age, City) become the column names.data = [
{'Name': 'Alice', 'Age': 25, 'City': 'New York'},
{'Name': 'Bob', 'Age': 30, 'City': 'Los Angeles'},
{'Name': 'Charlie', 'Age': 35, 'City': 'Chicago'}
]
df = pd.DataFrame(data)
print(df)
Output:
Name Age City
0 Alice 25 New York
1 Bob 30 Los Angeles
2 Charlie 35 Chicago
You can specify a custom index when creating a DataFrame:
data = {
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'City': ['New York', 'Los Angeles', 'Chicago']
}
df = pd.DataFrame(data, index=['a', 'b', 'c'])
print(df)
Output:
Name Age City
a Alice 25 New York
b Bob 30 Los Angeles
c Charlie 35 Chicago
Once you have a DataFrame, you can perform various operations to explore and manipulate the data.
head() to display the first 5 rows (or specify a number).print(df.head(2))
Output:
Name Age City
a Alice 25 New York
b Bob 30 Los Angeles
tail() to display the last 5 rows.print(df.tail(1))
Output:
Name Age City
c Charlie 35 Chicago
info() to get a summary of the DataFrame, including data types and non-null counts.print(df.info())
Output:
<class 'pandas.core.frame.DataFrame'>
Index: 3 entries, a to c
Data columns (total 3 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Name 3 non-null object
1 Age 3 non-null int64
2 City 3 non-null object
dtypes: int64(1), object(2)
memory usage: 96.0+ bytes
describe() to get summary statistics for numerical columns.print(df.describe())
Output:
Age
count 3.000000
mean 30.000000
std 5.000000
min 25.000000
25% 27.500000
50% 30.000000
75% 32.500000
max 35.000000
You can access specific rows, columns, or subsets of the DataFrame.
. notation.print(df['Name']) # or df.Name
Output:
a Alice
b Bob
c Charlie
Name: Name, dtype: object
print(df[['Name', 'City']])
Output:
Name City
a Alice New York
b Bob Los Angeles
c Charlie Chicago
loc (label-based) or iloc (integer-based).print(df.loc['a']) # Access row with index 'a'
Output:
Name Alice
Age 25
City New York
Name: a, dtype: object
print(df.iloc[0]) # Access the first row
Output:
Name Alice
Age 25
City New York
Name: a, dtype: object
loc or iloc to access specific elements.print(df.loc['a', 'Name']) # Access the 'Name' of row 'a'
Output:
Alice
df['Salary'] = [50000, 60000, 70000]
print(df)
Output:
Name Age City Salary
a Alice 25 New York 50000
b Bob 30 Los Angeles 60000
c Charlie 35 Chicago 70000
df['Age'] = df['Age'] + 1
print(df)
Output:
Name Age City Salary
a Alice 26 New York 50000
b Bob 31 Los Angeles 60000
c Charlie 36 Chicago 70000
loc to add a row with a new index.df.loc['d'] = ['David', 40, 'Houston', 80000]
print(df)
Output:
Name Age City Salary
a Alice 26 New York 50000
b Bob 31 Los Angeles 60000
c Charlie 36 Chicago 70000
d David 40 Houston 80000
drop() with axis=1.df = df.drop('Salary', axis=1)
print(df)
Output:
Name Age City
a Alice 26 New York
b Bob 31 Los Angeles
c Charlie 36 Chicago
d David 40 Houston
drop() with axis=0.df = df.drop('d', axis=0)
print(df)
Output:
Name Age City
a Alice 26 New York
b Bob 31 Los Angeles
c Charlie 36 Chicago
You can filter rows based on conditions using boolean indexing.
filtered_df = df[df['Age'] > 30]
print(filtered_df)
Output:
Name Age City
b Bob 31 Los Angeles
c Charlie 36 Chicago
& (and) or | (or).filtered_df = df[(df['Age'] > 30) & (df['City'] == 'Chicago')]
print(filtered_df)
Output:
Name Age City
c Charlie 36 Chicago
sort_values().sorted_df = df.sort_values(by='Age', ascending=False)
print(sorted_df)
Output:
Name Age City
c Charlie 36 Chicago
b Bob 31 Los Angeles
a Alice 26 New York
sorted_df = df.sort_values(by=['Age', 'Name'], ascending=[False, True])
print(sorted_df)
Output:
Name Age City
c Charlie 36 Chicago
b Bob 31 Los Angeles
a Alice 26 New York
Missing data is common in real-world datasets. Pandas provides tools to handle it.
Missing data is represented as NaN (Not a Number) in Pandas.
import numpy as np
data = {
'Name': ['Alice', 'Bob', np.nan, 'David'],
'Age': [25, np.nan, 35, 40],
'City': ['New York', 'Los Angeles', 'Chicago', np.nan]
}
df = pd.DataFrame(data)
print(df)
Output:
Name Age City
0 Alice 25.0 New York
1 Bob NaN Los Angeles
2 NaN 35.0 Chicago
3 David 40.0 NaN
isna() or isnull().print(df.isna())
Output:
Name Age City
0 False False False
1 False True False
2 True False False
3 False False True
dropna().df_cleaned = df.dropna()
print(df_cleaned)
Output:
Name Age City
0 Alice 25.0 New York
fillna().df_filled = df.fillna({'Name': 'Unknown', 'Age': 0, 'City': 'Unknown'})
print(df_filled)
Output:
Name Age City
0 Alice 25.0 New York
1 Bob 0.0 Los Angeles
2 Unknown 35.0 Chicago
3 David 40.0 Unknown
Pandas allows you to group data and perform aggregate operations (e.g., sum, mean, count).
data = {
'Name': ['Alice', 'Bob', 'Charlie', 'David'],
'Age': [25, 30, 35, 40],
'City': ['New York', 'Los Angeles', 'New York', 'Los Angeles'],
'Salary': [50000, 60000, 70000, 80000]
}
df = pd.DataFrame(data)
# Group by 'City' and calculate the mean of numerical columns
grouped = df.groupby('City').mean()
print(grouped)
Output:
Age Salary
City
Los Angeles 35.000000 70000.0
New York 30.000000 60000.0
You can apply custom aggregation functions using agg().
grouped = df.groupby('City').agg({'Age': 'mean', 'Salary': ['sum', 'count']})
print(grouped)
Output:
Age Salary
mean sum count
City
Los Angeles 35.000000 140000 2
New York 30.000000 120000 2
Pandas provides SQL-like operations to merge and join DataFrames.
df1 = pd.DataFrame({
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35]
})
df2 = pd.DataFrame({
'Name': ['Alice', 'Bob', 'David'],
'Salary': [50000, 60000, 80000]
})
# Merge on 'Name' column
merged_df = pd.merge(df1, df2, on='Name', how='inner')
print(merged_df)
Output:
Name Age Salary
0 Alice 25 50000
1 Bob 30 60000
how parameter specifies the type of merge:
inner: Only keep rows present in both DataFrames.outer: Keep all rows, filling missing values with NaN.left: Keep all rows from the left DataFrame.right: Keep all rows from the right DataFrame.Pandas can read and write data from/to various file formats, such as CSV, Excel, JSON, and SQL.
df = pd.read_csv('data.csv')
print(df)
df = pd.read_excel('data.xlsx')
print(df)
df.to_csv('output.csv', index=False)
df.to_excel('output.xlsx', index=False)
You can apply custom functions to DataFrame columns or rows using apply().
# Add 10% to each salary
df['Salary'] = df['Salary'].apply(lambda x: x * 1.1)
print(df)
Output:
Name Age City Salary
0 Alice 25 New York 55000.0
1 Bob 30 Los Angeles 66000.0
2 Charlie 35 Chicago 77000.0
3 David 40 Houston 88000.0
Pandas supports pivot tables for summarizing data.
pivot = pd.pivot_table(df, values='Salary', index='City', columns='Age', aggfunc='mean')
print(pivot)
Pandas is excellent for handling time series data. You can work with dates, resample data, and more.
# Create a DataFrame with dates
dates = pd.date_range(start='2023-01-01', periods=4, freq='D')
df = pd.DataFrame({'Date': dates, 'Value': [10, 20, 30, 40]})
df.set_index('Date', inplace=True)
print(df)
Output:
Value
Date
2023-01-01 10
2023-01-02 20
2023-01-03 30
2023-01-04 40
df['Age'] + 1) instead of loops for better performance.inplace=True for operations like drop() or fillna() to modify the DataFrame in place.dask or modin for parallel processing.pd.read_csv() with usecols and dtype to optimize memory usage when reading large files.Here’s a small exercise to test your understanding:
Product, Price, Quantity['Laptop', 1000, 5], ['Phone', 500, 10], ['Tablet', 300, 15]Total that multiplies Price by Quantity.Total > 2000.Price in descending order.products.csv.Try solving this on your own, and then check the solution below:
import pandas as pd
# Step 1: Create the DataFrame
data = {
'Product': ['Laptop', 'Phone', 'Tablet'],
'Price': [1000, 500, 300],
'Quantity': [5, 10, 15]
}
df = pd.DataFrame(data)
# Step 2: Add the 'Total' column
df['Total'] = df['Price'] * df['Quantity']
# Step 3: Filter rows where Total > 2000
filtered_df = df[df['Total'] > 2000]
# Step 4: Sort by Price in descending order
sorted_df = filtered_df.sort_values(by='Price', ascending=False)
# Step 5: Save to CSV
sorted_df.to_csv('products.csv', index=False)
print(sorted_df)
Output:
Product Price Quantity Total
0 Laptop 1000 5 5000
1 Phone 500 10 5000
To deepen your understanding of Pandas, explore the following topics:
df.plot()).You can also refer to the official Pandas documentation: https://pandas.pydata.org/docs/
I hope this tutorial helps you get started with Pandas DataFrames! If you have any questions or need further clarification, feel free to ask.