Module 3 · pandas · Lesson 16 of 66
DataFrames: columns and rows
Select, add and drop columns; pick rows with loc and iloc.
In this lesson · about 16 minutes
- Select one or several columns
- Add and drop columns and rows
- Select rows and cells with loc and iloc
A DataFrame is a table: several Series side by side that share one index. Columns have names; rows have index labels. Here's a small one with random numbers that we'll use in this lesson and the next.
Columns
df['W']gives one column, as a Series.df[['W', 'Z']](a list inside the brackets) gives a smaller DataFrame.df['new'] = df['W'] + df['Y']creates a column.df.drop('new', axis=1)removes a column.axis=1means columns;axis=0(the default) means rows.
Rows
df.loc['A']selects a row by its label.df.iloc[2]selects a row by its position (0, 1, 2…).df.loc['B', 'Y']is one cell: row label, then column name.df.loc[['A', 'B'], ['W', 'Y']]is a block of rows and columns.
Exercise
Two columns
Select columns X and Z as a DataFrame.
Code that runs before yours
import numpy as np import pandas as pd np.random.seed(101) df = pd.DataFrame(np.random.randn(5, 4), index='A B C D E'.split(), columns='W X Y Z'.split())
Exercise
Add a column
Add a column total that is W + X + Y + Z for each row. Then drop column W from df for good.
Code that runs before yours
import numpy as np import pandas as pd np.random.seed(101) df = pd.DataFrame(np.random.randn(5, 4), index='A B C D E'.split(), columns='W X Y Z'.split())
Exercise
A block of cells
Select rows C and E, columns X and Y.
Code that runs before yours
import numpy as np import pandas as pd np.random.seed(101) df = pd.DataFrame(np.random.randn(5, 4), index='A B C D E'.split(), columns='W X Y Z'.split())
Check your understanding0 of 2 correct
Quiz score: 0 of 2
Exercises solved: 0 of 3
Noviq Academy's Data Science course is free and for learning. Python runs in your browser with Pyodide, which downloads about 20 MB the first time, plus a few more for scikit-learn. Your code and progress stay on this device. The salaries data is a sample of San Francisco's public pay records; the purchases, customers, housing, advertising and classified data are made up. The Titanic, tips, flights and iris data sets come from Seaborn's examples; the maps use public 2011 to 2014 US and world figures. The 911 data is a 20,000-call sample of Montgomery County, Pennsylvania's public 911 records; the movie ratings are the MovieLens 100K data from GroupLens Research; the reviews are a 3,000-review sample from the Yelp Dataset Challenge; the loans are public LendingClub data; the colleges are the College data from An Introduction to Statistical Learning; the bank notes, kyphosis and breast cancer data come from the UCI Machine Learning Repository. Spark and TensorFlow can't run in a browser, so those lessons use stand-ins that run here, and show the code for the real tools.