You are on page 1of 1

Do not worry about the syntax, it is quite terse and concise

This DataFrame is being used to explain how to add, remove and insert rows and columns into a DataFrame.

In [ ]: d = np.arange(16).reshape(4,4)

ndx = ['a', 'b', 'c', 'd']

cols = ['one','two','three','four']

df = pd.DataFrame(data=d, index=ndx, columns=cols)

df

Accessing Rows and Columns


A few ways to achieve this, depends on your needs, your style, preferences, data at hand etc.

loc gets rows or columns with particular labels from the index.
iloc gets rows or columns at particular positions in the index (so it only takes integers).
loc and iloc take 2 arguments - row, column
the column argument defaults to all columns

In [ ]: # Accessing a row with index label 'c'

df.loc['c']

# Accessing the 3rd row (index starts at 0)

df.iloc[2]

# Using loc and ioc to access columns

# Need to be a little more specific

# Accessing all rows of a column called 'three'

df.loc[:, 'three']

# Accessing all rows of the 3rd column (index starts at 0)

df.iloc[:, 2]

# Addressing individual cells

df.loc['c','three']

df.iloc[2,2]

# Accessing columns is usually achieved by specifying the column name

df['one']

# or the names of columns by using a list

df[['two','three']]

df[['three','two']]

Removing Rows and Columns


Three choices

drop (rows and columns)


del (columns only)
pop (columns only)

In [ ]: # Removing a row

df.drop('b')

# Note that dropping returns a new DataFrame, the original is still unchanged

You might also like