Lesson 1 of 6 · about 15 minutes
Creating, reading and writing
What pandas is
pandas is the Python library for working with tables of data: spreadsheets, CSV files, survey results, sales records. It is the tool most data analysts reach for first.
You bring it in with one line. Everyone shortens the name to pd, so you will see pd. in front of almost every pandas command:
import pandas as pd
print(pd.__version__)pandas has two main building blocks: the DataFrame (a whole table) and the Series (one column of it). This lesson shows how to make both, how to load a table from a file, and how to save one.
DataFrames
A DataFrame is a table. It has rows, columns, and a value in every cell. The quickest way to make one is from a dictionary: each key becomes a column name, and each list becomes that column's values.
import pandas as pd
df = pd.DataFrame({
"name": ["Ava", "Ben", "Cleo"],
"age": [12, 13, 12],
"points": [88, 92, 79],
})
print(df)The output:
name age points
0 Ava 12 88
1 Ben 13 92
2 Cleo 12 79The numbers down the left side (0, 1, 2) are the index: a label for every row. pandas numbers the rows for you unless you say otherwise. You can give your own labels with index=:
import pandas as pd
df = pd.DataFrame(
{"apples": [30, 41], "bananas": [21, 34]},
index=["Monday", "Tuesday"],
)
print(df)The output:
apples bananas
Monday 30 21
Tuesday 41 34Series
A Series is a single column: a list of values with an index. Every column you take out of a DataFrame is a Series, and you can also make one directly:
import pandas as pd
prices = pd.Series([1.5, 0.75, 2.0], index=["apple", "banana", "cherry"], name="price")
print(prices)The output:
apple 1.50
banana 0.75
cherry 2.00
Name: price, dtype: float64The name is the column name the Series would have inside a DataFrame. The last line also shows the dtype, the kind of values it holds: float64 means decimal numbers.
Quick check
What is a Series?
Reading a CSV file
Real data usually comes from a file. The most common format is CSV (comma-separated values). A CSV file is plain text: open one in any text editor and it looks like this file, called pets.csv:
name,animal,age
Rex,dog,4
Mittens,cat,2
Bubbles,fish,1
Luna,cat,6The first line is the header: the column names. Every other line is one row, with a comma between each value. A spreadsheet app shows the same file as a table:
| name | animal | age |
|---|---|---|
| Rex | dog | 4 |
| Mittens | cat | 2 |
| Bubbles | fish | 1 |
| Luna | cat | 6 |
pd.read_csv() reads a CSV file into a DataFrame. The example below first creates pets.csv (with exactly the text above) so there is a file to read, then reads it:
import pandas as pd
# Create pets.csv so there is a file to read
csv_text = """name,animal,age
Rex,dog,4
Mittens,cat,2
Bubbles,fish,1
Luna,cat,6
"""
with open("pets.csv", "w") as f:
f.write(csv_text)
pets = pd.read_csv("pets.csv")
print(pets)
print(pets.shape)The output:
name animal age
0 Rex dog 4
1 Mittens cat 2
2 Bubbles fish 1
3 Luna cat 6
(4, 3)pandas used the header line for the column names and added the row numbers itself. shape tells you the size of the table as (rows, columns): here 4 rows and 3 columns. For big files, pets.head() shows only the first five rows, which is the usual first look at any new dataset.
If the file already has a column you want to use as the row labels, pass index_col, for example pd.read_csv("pets.csv", index_col="name").
Quick check
A DataFrame has 120 rows and 5 columns. What is its shape?
Writing a CSV file
To save a DataFrame, use to_csv(). Pass index=False unless you want the row numbers saved as an extra column. Printing the file shows the CSV text that was written:
import pandas as pd
scores = pd.DataFrame({"team": ["Red", "Blue"], "goals": [3, 5]})
scores.to_csv("scores.csv", index=False)
print(open("scores.csv").read())The output:
team,goals
Red,3
Blue,5Reading the file back with pd.read_csv("scores.csv") gives you the same table again.
Exercise 1: Make a table
Create a DataFrame called scores with two columns: name with the values Ava, Ben and Cleo, and points with 12, 7 and 9. Then print it.
Exercise 2: A Series of prices
Create a Series called prices with the values 1.5, 0.75 and 2.0, the index apple, banana and cherry, and the name price. Print it.
Exercise 3: Save it and read it back
The team DataFrame is ready. Save it to a file called team.csv without the index, then read the file back into a DataFrame called loaded and print loaded.shape.
Lesson 1 complete
You finished creating, reading and writing and passed every exercise.
What you learned
import pandas as pdloads pandas.pd.DataFrame({...})makes a table from a dictionary of columns;index=sets the row labels.pd.Series([...], index=..., name=...)makes a single column.pd.read_csv("file.csv")reads a table from a file, anddf.shapegives (rows, columns).df.to_csv("file.csv", index=False)saves a table.