Python Pandas and Data AnalysisGet Certified
What Is Pandas?
Pandas is the most popular Python library for working with tables of data, such as spreadsheets, survey results, sales records, and CSV files. It gives you a table object called a DataFrame, in which every column has a name and a data type, and it can filter, sort, group, clean, and combine thousands or millions of rows with just a few lines of code. Doing the same work with plain lists and loops would take much longer and would be much harder to read. Data analysts, scientists, journalists, and business teams all use pandas as the first step in turning raw numbers into answers.
- DataFrame: a table with labeled columns and rows. A single column is called a Series.
- Selecting data: pick columns by name, rows with
locandiloc, and filter rows with conditions. - Statistics:
sum(),mean(),median(),max(), andmin()work on whole columns at once. - New columns and sorting: calculate a column from other columns and order the rows with
sort_values(). - Grouping and merging: summarize by category with
groupby()and join tables withmerge(). - Cleaning and loading: handle missing values and read data with
read_csv().
Creating a DataFrame
The easiest way to build a DataFrame is from a dictionary in which every key is a column name and every value is a list with the data of that column. All the lists must have the same length, because each position across the lists forms one row. Pandas adds a row label, called the index, that starts at 0, and it works out the data type of every column by itself. Useful first checks on a new table are shape, which gives the number of rows and columns, columns, which lists the names, and head(), which shows the first rows.
Try It: A Table of Big Cities
Click Test My Code. Add a sixth city to each of the three lists and check that the shape changes to six rows.
import pandas as pd
cities = pd.DataFrame({
"city": ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix"],
"state": ["NY", "CA", "IL", "TX", "AZ"],
"population": [8804190, 3898747, 2746388, 2304580, 1608139],
})
print(cities.shape)
print(list(cities.columns))
print(cities["population"].sum())
print(cities.head(2))pd, which is the standard habit in data analysis.pd.DataFrame() receives a dictionary. Each key becomes the name of a column.shape gives the number of rows and columns. The output is (5, 3).columns holds the column names, and list() turns them into a normal list. The output is ['city', 'state', 'population'].sum() adds up all its values. The output is 19362044.head(2) shows the first two rows as a small table, for New York and Los Angeles. The row labels 0 and 1 appear on the left.Selecting Columns, Rows, and Filtering
Choosing the part of a table that you need is the most common task in pandas. Square brackets with a column name select a column, loc selects rows and columns by their labels, and iloc selects them by their position, counting from zero. To keep only the rows that meet a condition, you put a comparison inside the square brackets, such as students["gpa"] >= 3.5, which produces a True or False value for every row. Several conditions are combined with & for “and” and | for “or”, and each condition must be wrapped in its own parentheses.
Try It: Finding Honor Roll Students
Click Test My Code. Change the GPA limit on line 11 to 3.8 and see who is left.
loc and iloc, keeps the rows of students with a GPA of at least 3.5, and then combines two conditions to find the juniors with a GPA above 3.0.import pandas as pd
students = pd.DataFrame({
"name": ["Olivia", "Liam", "Emma", "Noah", "Ava"],
"grade": [11, 10, 12, 11, 10],
"gpa": [3.8, 3.2, 3.9, 2.9, 3.5],
})
print(students["name"].tolist())
print(students.loc[2, "name"], students.iloc[0, 2])
honor = students[students["gpa"] >= 3.5]
print(honor["name"].tolist())
juniors = students[(students["grade"] == 11) & (students["gpa"] > 3.0)]
print(juniors["name"].tolist())pd.tolist() turns it into a normal list. The output is ['Olivia', 'Liam', 'Emma', 'Noah', 'Ava'].loc[2, "name"] uses the row label 2 and the column name, and iloc[0, 2] uses the positions row 0 and column 2. The output is Emma 3.8.['Olivia', 'Emma', 'Ava'].& means “and”. Each condition has its own parentheses. Only students in grade 11 with a GPA above 3.0 remain.['Olivia'].Summary Statistics
One of the great strengths of pandas is that a statistic can be calculated for a whole column in a single call, with no loop. The methods sum(), mean(), median(), min(), and max() work on a Series, and the method describe() gives a whole report at once. A related pair of methods, idxmax() and idxmin(), returns the row label of the largest or smallest value, so you can find out which row holds the best result. The mean is the average, while the median is the middle value, and the median is not pulled around by a few very large values.
Try It: Store Revenue Report
Click Test My Code. Change one revenue to 400 and see how much the mean moves compared with the median.
idxmax(), and the median.import pandas as pd
sales = pd.DataFrame({
"store": ["Dallas", "Denver", "Seattle", "Boston", "Atlanta"],
"revenue": [120, 95, 150, 110, 125],
})
print(sales["revenue"].sum())
print(sales["revenue"].mean())
print(sales["revenue"].max(), sales["revenue"].min())
best = sales.loc[sales["revenue"].idxmax(), "store"]
print(best)
print(sales["revenue"].median())pd.600.120.0.150 95.idxmax() returns the row label of the largest revenue, and loc uses that label to read the store name.Seattle.120.0.Adding Columns and Sorting
New columns are created by calculating with existing ones, and pandas applies the calculation to every row at once. This is called a vectorized operation, and it is both shorter and much faster than a loop over the rows. Writing orders["total"] = orders["price"] * orders["quantity"] adds a new column called total in one line. To put the rows in order, you use sort_values() with a column name, and the argument ascending=False puts the largest values first. Sorting returns a new table and leaves the original unchanged unless you assign the result back.
Try It: A Diner Order Sheet
Click Test My Code. Change the tax factor from 1.10 to 1.08 and compare the new totals.
total column and a with_tax column that adds ten percent and rounds to cents. It then sorts the rows by total, from largest to smallest, and prints the sorted item names, the sorted totals, and the totals with tax.import pandas as pd
orders = pd.DataFrame({
"item": ["Burger", "Fries", "Shake", "Salad"],
"price": [8.50, 3.00, 5.00, 7.50],
"quantity": [4, 10, 7, 2],
})
orders["total"] = orders["price"] * orders["quantity"]
orders["with_tax"] = (orders["total"] * 1.10).round(2)
ranked = orders.sort_values("total", ascending=False)
print(ranked["item"].tolist())
print(ranked["total"].tolist())
print(orders["with_tax"].tolist())pd.total.round(2) keeps two decimal places for the cents.sort_values() orders the rows by the total column. The argument ascending=False puts the largest first. The result is a new table.['Shake', 'Burger', 'Fries', 'Salad'].[35.0, 34.0, 30.0, 15.0].[37.4, 33.0, 38.5, 16.5].Grouping Data with groupby
Real questions about data are often about categories: the average salary in each city, the total sales for each month, or the number of students in each grade. The groupby() method answers them by splitting the table into groups that share a value in a column, applying a function to each group, and combining the results into a new table or Series. You choose the column to group by, then the column to summarize, and finally the function, such as mean(), sum(), or count(). With agg() you can calculate several statistics at the same time. This split, apply, and combine pattern is the heart of data analysis.
df.groupby("city")["salary"].mean()gives the average salary of each city..sum(),.count(),.min(), and.max()work in the same way..agg(["min", "max"])calculates several statistics in one step.- The groups appear in sorted order of the grouping values by default.
Try It: Salaries by City and Role
Click Test My Code. Change one salary on line 6 and see how the averages for that city change.
import pandas as pd
jobs = pd.DataFrame({
"city": ["Austin", "Austin", "Denver", "Denver", "Boston", "Boston"],
"role": ["Engineer", "Teacher", "Engineer", "Teacher", "Engineer", "Teacher"],
"salary": [110, 60, 105, 58, 120, 66],
})
by_city = jobs.groupby("city")["salary"].mean()
print(by_city.to_dict())
by_role = jobs.groupby("role")["salary"].agg(["min", "max"])
print(by_role.loc["Engineer"].tolist())
print(jobs.groupby("city")["salary"].sum().idxmax())pd.to_dict() turns the result into a dictionary. The cities appear in alphabetical order. The output is {'Austin': 85.0, 'Boston': 93.0, 'Denver': 81.5}.agg() calculates the minimum and the maximum salary of each group.loc["Engineer"] picks the row of the engineers. The output is [105, 120].idxmax() returns the city with the largest sum. The output is Boston.Handling Missing Data
Real data is rarely complete: a sensor fails, a survey question is skipped, or a cell in a spreadsheet is left empty. Pandas marks such a gap as NaN, which stands for “not a number”, and most statistics simply skip it. The method isna() shows where values are missing, fillna() replaces them with a value that you choose, such as the mean, and dropna() removes every row that has a gap. Which of the two to use depends on the data: filling keeps all the rows, while dropping avoids inventing numbers. A column that contains NaN is stored as floats, so whole numbers in it appear with a decimal point.
Try It: A Weather Table with a Gap
Click Test My Code. Replace the mean in fillna() with 0 and see what happens to the list of highs.
import pandas as pd
import numpy as np
weather = pd.DataFrame({
"city": ["Miami", "Phoenix", "Seattle", "Denver"],
"high": [88, np.nan, 62, 72],
})
print(weather["high"].isna().sum())
print(weather["high"].mean())
filled = weather["high"].fillna(weather["high"].mean())
print(filled.round(1).tolist())
cleaned = weather.dropna()
print(cleaned["city"].tolist())pd.np.nan, the value that marks a missing number.np.nan. The column becomes a float column.isna() gives True for each missing value, and sum() counts the True values. The output is 1.74.0.fillna() replaces every missing value with the mean of the known ones.[88.0, 74.0, 62.0, 72.0].dropna() returns a new table without the rows that contain a missing value.['Miami', 'Seattle', 'Denver'].Reading CSV Data
Most real datasets arrive as CSV files, which are plain text files in which every line is a row and the values are separated by commas. The function pd.read_csv() reads such a file straight into a DataFrame, takes the column names from the first line, and guesses the data type of every column. It accepts a file path, a web address, or any file-like object, and io.StringIO turns a piece of text into one, which is handy for examples and tests. After loading a file, it is a good habit to look at dtypes and len() to confirm that the columns have the types that you expect and that no rows are missing.
Try It: Annual Rainfall from CSV Text
Click Test My Code. Add a new line for another city inside the triple quotes and see the row count change.
read_csv(). It prints the data type of the rainfall column and the number of rows, keeps the cities with more than 40 inches, and finds the driest city by sorting.import io
import pandas as pd
csv_text = """city,state,rainfall
Seattle,WA,37.5
Miami,FL,61.9
Portland,OR,43.5
Phoenix,AZ,7.2
"""
rain = pd.read_csv(io.StringIO(csv_text))
print(rain.dtypes["rainfall"])
print(len(rain))
wet = rain[rain["rainfall"] > 40]
print(wet["city"].tolist())
print(rain.sort_values("rainfall").iloc[0]["city"])io module provides StringIO, which makes text behave like a file.pd.read_csv() turns the text into a DataFrame. io.StringIO() makes the string look like an open file.float64.4.['Miami', 'Portland'].iloc[0] takes the first row, and the city name is read from it. The output is Phoenix.Combining Tables with merge
Data is often spread over several tables, for example one table of employees and another table with the names of the departments, linked by a department number. The function pd.merge() joins two tables on a column that they share, which works just like a join in a database. By default it keeps only the rows whose key appears in both tables, and the argument how="left" keeps every row of the first table. After a merge you can use all the other pandas tools on the combined table, such as value_counts(), which counts how often each value occurs in a column.
Try It: Employees and Departments
Click Test My Code. Change Noah’s dept_id to 2 and see how the department counts change.
dept_id, prints the department of every employee and the shape of the result, and counts how many employees work in each department.import pandas as pd
employees = pd.DataFrame({
"name": ["Olivia", "Liam", "Emma", "Noah"],
"dept_id": [1, 2, 1, 3],
})
departments = pd.DataFrame({
"dept_id": [1, 2, 3],
"department": ["Sales", "Engineering", "Support"],
})
merged = pd.merge(employees, departments, on="dept_id")
print(merged["department"].tolist())
print(merged.shape)
counts = merged["department"].value_counts()
print(counts["Sales"], counts["Support"])pd.dept_id has the same name as in the first table, which makes the merge easy.pd.merge() joins the two tables on dept_id. Every employee gets the department name that belongs to their number.['Sales', 'Engineering', 'Sales', 'Support'].(4, 3).value_counts() counts how often each department name occurs.2 1.Tip: Avoid writing aforloop over the rows of a DataFrame when a column calculation, a filter, or agroupby()can do the job. The built-in operations are shorter, easier to read, and much faster. After you load or change a table, look atshape,dtypes, andhead()to make sure that the data looks the way you expect.
Using Pandas with User Input
Data analysis becomes interactive when the filter or the category comes from the user, as in a dashboard where someone picks a minimum population or chooses a team. The input arrives as text, so convert numbers with float() or int() before you compare them with a column, and check text choices for a match before you calculate anything. When a typed category does not exist, the filtered table is empty, and the property empty lets you detect this case and show a friendly message instead of a confusing result. These two examples show both patterns.
Try It: Big Cities by Minimum Population
The Program Input box is already filled with 2.5. Click Run Code straight away, then try 1.5 and 9.
import pandas as pd
cities = pd.DataFrame({
"city": ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix", "Philadelphia"],
"population_millions": [8.8, 3.9, 2.7, 2.3, 1.6, 1.6],
})
minimum = float(input("Minimum population in millions: "))
big = cities[cities["population_millions"] >= minimum]
print(f"{len(big)} cities have at least {minimum} million people")
print(big["city"].tolist())
print(round(big["population_millions"].mean(), 2))pd.2.5, is converted from text to the float 2.5.len(big) is the number of rows that remain. The output is 3 cities have at least 2.5 million people.['New York', 'Los Angeles', 'Chicago'].5.13.Try It: Team Scores
The Program Input box is filled with Sales. Click Run Code, then try Support, and finally a team that does not exist, such as Legal.
import pandas as pd
data = pd.DataFrame({
"name": ["Olivia", "Liam", "Emma", "Noah", "Ava", "Mason"],
"team": ["Sales", "Support", "Sales", "Support", "Sales", "Support"],
"score": [88, 72, 94, 65, 79, 81],
})
team = input("Which team (Sales or Support)? ")
group = data[data["team"] == team]
if group.empty:
print(f"No team named {team}")
else:
print(f"{team} average: {group['score'].mean():.1f}")
top = group.loc[group["score"].idxmax(), "name"]
print(f"Top scorer: {top}")pd.Sales, is stored as text.empty is True when no row matched, which happens when the team name does not exist.Legal, the output is No team named Legal.Sales average: 87.0.idxmax() returns the row label of the highest score in the group, and loc reads the name at that label.Top scorer: Emma.Common Mistakes with Pandas
Pandas looks simple at first, but a few habits from ordinary Python do not carry over, and they cause most of the confusing errors and warnings that beginners meet. Some mistakes stop the program with an error message, while others quietly produce a wrong table, which is worse. The list below covers the problems that appear most often, and it is worth a quick read whenever a filter returns nothing, a new column does not appear, or pandas prints a warning that you do not understand.
- Using
and/orin a filter: write&and|instead, and put each condition in parentheses. - Forgetting the parentheses:
df["a"] == 1 & df["b"] > 2is evaluated in the wrong order. Write(df["a"] == 1) & (df["b"] > 2). - Expecting a method to change the table:
sort_values(),dropna(), andfillna()return a new table. Assign the result to a variable. - Confusing
locandiloc:locuses labels, andilocuses positions. After a sort or a filter, the two can differ. - Looping over rows: a loop is slow and long. Use column calculations, filters, and
groupby(). - Chained indexing:
df[df["a"] > 1]["b"] = 0may change only a copy and triggers a warning. Usedf.loc[df["a"] > 1, "b"] = 0. - Not checking the data types: numbers read from a file can arrive as text. Look at
dtypesafterread_csv(). - Ignoring missing values: a gap can change the type of a column to float and affect averages. Check with
isna().sum()early.
Key Takeaways
Pandas turns tables of data into objects that you can filter, summarize, and combine with short and readable code, and it is the foundation of almost every data analysis project in Python. The ideas of this lesson, such as column calculations, boolean filters, groupby(), and merge(), appear again and again in real work. The points below summarize what you learned, and they prepare you for the next lesson on Matplotlib, where you will learn to turn your data into charts and graphs. Remember them whenever you open a new dataset.
- A DataFrame is a table with labeled columns, and one column is a Series. You can build one from a dictionary of lists.
- Select columns with
df["name"], rows by label withloc, and rows by position withiloc. - Filter rows with conditions, and combine them with
&and|in parentheses. - Calculate with whole columns at once, add new columns, and order rows with
sort_values(). groupby()splits the data by category, applies a function such asmean(), and combines the results.isna(),fillna(), anddropna()find and handle missing data, andread_csv()loads a CSV file.merge()joins two tables on a shared column, and most methods return a new table instead of changing the old one.
Frequently Asked Questions
These are the questions that students ask most often when they start to analyze data with pandas. The answers are brief and practical, and each idea appears in one of the examples above. If something is still unclear, try building a tiny DataFrame of your own with three columns and four rows, and then practice filtering it, adding a column, and grouping it, because working with a table that you can see completely is the fastest way to learn.
What is pandas in Python?
Pandas is a Python library for working with tabular data such as spreadsheets and CSV files. Its main object is the DataFrame, a table with labeled columns, and it provides fast tools to filter, sort, group, clean, and combine data. It is one of the most widely used libraries for data analysis.
What is a DataFrame in pandas?
A DataFrame is a two-dimensional table of data with named columns and labeled rows. Each column can have its own data type, such as numbers or text. You can create one from a dictionary of lists, from a CSV file with read_csv(), or from many other sources.
What is the difference between a Series and a DataFrame?
A Series is a single labeled column of data, and a DataFrame is a table made of several Series that share the same row labels. When you select one column of a DataFrame, such as df[“salary”], you get a Series. Selecting a list of columns gives you a smaller DataFrame.
How do I filter rows in pandas?
Put a condition inside square brackets, for example df[df[“gpa”] >= 3.5]. The condition produces True or False for every row, and only the True rows are kept. Combine several conditions with & for and, and | for or, and wrap each condition in parentheses.
What is the difference between loc and iloc?
The loc indexer selects rows and columns by their labels, such as the row label 2 and the column name “name”. The iloc indexer selects them by integer position, counting from zero. After sorting or filtering, the labels and the positions of the rows can be different, so choose the one that matches your intention.
How do I handle missing values in pandas?
Missing values appear as NaN. Use isna() to find them, fillna() to replace them with a value such as the mean, and dropna() to remove the rows that contain them. Filling keeps all the rows but invents values, while dropping avoids invented values but loses data, so choose according to your goal.
What does groupby do in pandas?
The groupby method splits a table into groups that share the same value in a column, applies a function such as mean(), sum(), or count() to each group, and combines the results. For example, df.groupby(“city”)[“salary”].mean() gives the average salary of every city.
How do I read a CSV file with pandas?
Call pd.read_csv() with the file path or web address, for example df = pd.read_csv(“data.csv”). Pandas uses the first line for the column names and guesses the data types. Afterwards, check df.head(), df.shape, and df.dtypes to confirm that the data was loaded the way you expected.