Pandas DataFrame take() method with examples

Spread the love

The take() method in pandas helps us select rows and columns based on their position in the dataframe. We provide an array of ints indicating which positions to take.

syntax –

DataFrame.take(indices, axis=0)

indices – An array of ints indicating which positions to take.

axis – The axis on which to select elements. 0 means that we are selecting rows, 1 means that we are selecting columns.

Examples –

Let’s create a dataframe to work with.

import pandas as pd

data = {'Apple':[89, 89, 90, 110, 125, 84, 131, 123, 123, 140, 145, 145],
       'Orange': [46, 46, 50, 65, 63, 48, 110, 120, 60, 42, 47, 62],
       'Banana': [26, 30, 30, 25, 38, 22, 22, 36, 20, 27, 23, 34 ],
       'Mango': [80, 80, 90, 125, 130, 150, 140, 140, 135, 135, 80, 90]}

index = ['Jan','Feb','Mar','Apr','May','June','Jul','Aug','Sep','Oct','Nov','Dec']
df = pd.DataFrame(data, index=index)
df

1 . Select Rows Based on Row Position –

Let’s say that we want to select the 1st row, 5th row and the 10th row. Remember that indexing in python starts with 0.

# select 1st, 5th and 10th row
df.take([0, 4, 9])

By default the axis is set to axis=0 or index i.e. it will select rows. If you want you can explicitly set this like shown below.

# select 1st, 5th and 10th row
df.take([0, 4, 9], axis='index')

2 . Select Columns based on Column Position –

We can also select columns based on column position. Let’s say that we want to select the 1st and the 3rd columns i.e. Apple and Banana.

# select 1st and 3rd column
df.take([0, 2], axis='columns')

Rating: 1 out of 5.

Leave a Reply