Removing columns from a pandas DataFrame
Removing Columns

This introduction to pandas is derived from Data School's pandas Q&A with my own notes and code.

Removing columns from a pandas DataFrame

In [1]:
import pandas as pd
In [2]:
# Creating pandas DataFrame
url = 'http://bit.ly/uforeports'
ufo = pd.read_csv(url)
In [3]:
ufo.head()
Out[3]:
City Colors Reported Shape Reported State Time
0 Ithaca NaN TRIANGLE NY 6/1/1930 22:00
1 Willingboro NaN OTHER NJ 6/30/1930 20:00
2 Holyoke NaN OVAL CO 2/15/1931 14:00
3 Abilene NaN DISK KS 6/1/1931 13:00
4 New York Worlds Fair NaN LIGHT NY 4/18/1933 19:00
In [4]:
ufo.shape
Out[4]:
(18241, 5)
In [5]:
# Removing column
# axis=0 row axis
# axis=1 column axis
# inplace=True to effect change
ufo.drop('Colors Reported', axis=1, inplace=True)
In [6]:
ufo.head()
Out[6]:
City Shape Reported State Time
0 Ithaca TRIANGLE NY 6/1/1930 22:00
1 Willingboro OTHER NJ 6/30/1930 20:00
2 Holyoke OVAL CO 2/15/1931 14:00
3 Abilene DISK KS 6/1/1931 13:00
4 New York Worlds Fair LIGHT NY 4/18/1933 19:00
In [7]:
# Removing column
list_drop = ['City', 'State']
ufo.drop(list_drop, axis=1, inplace=True)
In [9]:
ufo.head()
Out[9]:
Shape Reported Time
0 TRIANGLE 6/1/1930 22:00
1 OTHER 6/30/1930 20:00
2 OVAL 2/15/1931 14:00
3 DISK 6/1/1931 13:00
4 LIGHT 4/18/1933 19:00
In [10]:
# Removing rows 0 and 1
# axis=0 is the default, so technically, you can leave this out
rows = [0, 1]
ufo.drop(rows, axis=0, inplace=True)
In [12]:
ufo.head()
Out[12]:
Shape Reported Time
2 OVAL 2/15/1931 14:00
3 DISK 6/1/1931 13:00
4 LIGHT 4/18/1933 19:00
5 DISK 9/15/1934 15:30
6 CIRCLE 6/15/1935 0:00
Tags: pandas