Ben Chuanlong Du's Blog

It is never too late to learn.

Drop Rows or Columns from a pandas DataFrame

Drop Rows

In [1]:
import pandas as pd

data = {
    "name": ["Jason", "Molly", "Tina", "Jake", "Amy"],
    "year": [2012, 2012, 2013, 2014, 2014],
    "reports": [4, 24, 31, 2, 3],
}
df = pd.DataFrame(data, index=["Cochice", "Pima", "Santa Cruz", "Maricopa", "Yuma"])
df
Out[1]:
name year reports
Cochice Jason 2012 4
Pima Molly 2012 24
Santa Cruz Tina 2013 31
Maricopa Jake 2014 2
Yuma Amy 2014 3
In [2]:
df.drop(["Cochice", "Pima"])
Out[2]:
name year reports
Santa Cruz Tina 2013 31
Maricopa Jake 2014 2
Yuma Amy 2014 3

Drop Columns

In [3]:
import pandas as pd

data = {
    "name": ["Jason", "Molly", "Tina", "Jake", "Amy"],
    "year": [2012, 2012, 2013, 2014, 2014],
    "reports": [4, 24, 31, 2, 3],
}
df = pd.DataFrame(data, index=["Cochice", "Pima", "Santa Cruz", "Maricopa", "Yuma"])
df
Out[3]:
name year reports
Cochice Jason 2012 4
Pima Molly 2012 24
Santa Cruz Tina 2013 31
Maricopa Jake 2014 2
Yuma Amy 2014 3
In [4]:
df.drop("reports", axis=1, inplace=False)
Out[4]:
name year
Cochice Jason 2012
Pima Molly 2012
Santa Cruz Tina 2013
Maricopa Jake 2014
Yuma Amy 2014
In [5]:
df.drop(df.columns[[0, 1]], axis=1)
Out[5]:
reports
Cochice 4
Pima 24
Santa Cruz 31
Maricopa 2
Yuma 3
In [ ]:
 

Comments