Lesson 2 of 6 · about 20 minutes
Indexing, selecting and assigning
Selecting columns
Most of working with data is picking out the part you need. Every example in this lesson uses this small table of students:
import pandas as pd
df = pd.DataFrame({
"name": ["Ava", "Ben", "Cleo", "Dan", "Eli"],
"city": ["Leeds", "York", "Leeds", "Bath", "York"],
"age": [12, 13, 12, 14, 13],
"score": [88, 92, 79, 65, 95],
})
print(df)The output:
name city age score
0 Ava Leeds 12 88
1 Ben York 13 92
2 Cleo Leeds 12 79
3 Dan Bath 14 65
4 Eli York 13 95To get one column, put its name in square brackets. The result is a Series:
import pandas as pd
df = pd.DataFrame({
"name": ["Ava", "Ben", "Cleo", "Dan", "Eli"],
"score": [88, 92, 79, 65, 95],
})
print(df["score"])The output:
0 88
1 92
2 79
3 65
4 95
Name: score, dtype: int64df.score works too, as long as the column name has no spaces and does not clash with a pandas method name. Square brackets always work, so they are the safer habit.
To get several columns, pass a list of names. Note the double brackets: the outer pair selects, the inner pair is the list. The result is a smaller DataFrame:
import pandas as pd
df = pd.DataFrame({
"name": ["Ava", "Ben", "Cleo"],
"city": ["Leeds", "York", "Leeds"],
"score": [88, 92, 79],
})
print(df[["name", "score"]])The output:
name score
0 Ava 88
1 Ben 92
2 Cleo 79Rows by position: iloc
iloc selects by position, counting from 0 like a Python list. The first part picks rows, the optional second part picks columns:
import pandas as pd
df = pd.DataFrame({
"name": ["Ava", "Ben", "Cleo", "Dan", "Eli"],
"score": [88, 92, 79, 65, 95],
})
print(df.iloc[0])
print()
print(df.iloc[1:3])
print()
print(df.iloc[-1, 0])The output:
name Ava
score 88
Name: 0, dtype: object
name score
1 Ben 92
2 Cleo 79
Elidf.iloc[0] is the first row, df.iloc[1:3] is rows 1 and 2 (the end is not included, as with lists), and df.iloc[-1, 0] is the cell in the last row and first column.
Quick check
How many rows does df.iloc[2:5] return (if df has 10 rows)?
Rows by label: loc
loc selects by label: the index values and the column names. This is usually what you want, because it reads like the question you are asking:
import pandas as pd
df = pd.DataFrame(
{"city": ["Leeds", "York", "Leeds", "Bath"], "score": [88, 92, 79, 65]},
index=["Ava", "Ben", "Cleo", "Dan"],
)
print(df.loc["Cleo"])
print()
print(df.loc["Ben", "score"])
print()
print(df.loc["Ava":"Cleo", ["score"]])The output:
city Leeds
score 79
Name: Cleo, dtype: object
92
score
Ava 88
Ben 92
Cleo 79One difference to remember: with loc, a slice like "Ava":"Cleo" includes the end label. With iloc, the end position is left out.
Selecting with conditions
The most useful trick of all: compare a column with a value, and you get True or False for every row. Put that inside df[...] or df.loc[...] to keep only the True rows:
import pandas as pd
df = pd.DataFrame({
"name": ["Ava", "Ben", "Cleo", "Dan", "Eli"],
"city": ["Leeds", "York", "Leeds", "Bath", "York"],
"score": [88, 92, 79, 65, 95],
})
print(df.loc[df["score"] > 85])
print()
print(df.loc[(df["city"] == "York") & (df["score"] > 92)])
print()
print(df.loc[df["city"].isin(["Bath", "Leeds"])])The output:
name city score
0 Ava Leeds 88
1 Ben York 92
4 Eli York 95
name city score
4 Eli York 95
name city score
0 Ava Leeds 88
2 Cleo Leeds 79
3 Dan Bath 65Combine conditions with & (and) and | (or), and put each condition in its own brackets. isin([...]) keeps rows whose value is in a list.
Quick check
Which line keeps rows where age is over 12 AND city is York?
Assigning values
You can add a new column, or change an existing one, by assigning to it. A single value fills the whole column; a calculation works row by row:
import pandas as pd
df = pd.DataFrame({"name": ["Ava", "Ben", "Cleo"], "score": [88, 92, 79]})
df["school"] = "Hill Park"
df["bonus"] = df["score"] + 5
df.loc[df["score"] < 80, "bonus"] = 90
print(df)The output:
name score school bonus
0 Ava 88 Hill Park 93
1 Ben 92 Hill Park 97
2 Cleo 79 Hill Park 90The last line uses loc with a condition and a column name to change only some cells: everyone who scored under 80 gets a bonus score of 90.
Exercise 1: Two columns
From the df table, make a DataFrame called small that has only the name and score columns, in that order. Print it.
Exercise 2: Top scorers
Make a DataFrame called top with only the rows where score is 85 or more. Print it.
Exercise 3: Add a total
Add a column called total to df that holds maths plus science for each student. Then print the value of total for Cleo using loc (the index is the student names).
Lesson 2 complete
You finished indexing, selecting and assigning and passed every exercise.
What you learned
df["col"]gives one column (a Series);df[["a", "b"]]gives several (a DataFrame).df.iloc[...]selects by position, counting from 0; slices leave out the end.df.loc[...]selects by label; slices include the end.df.loc[condition]keeps the rows where the condition is True. Use&,|andisin().df["new"] = ...adds or replaces a column.