Selecting Elements In A 1D Array

Goal

This post aims to select elements in a 1d array in python using following modules:

  • Numpy
  • Pandas

Referring to Chris Albon's blog, I only look at his title of the post but wrote my own contents without looking at the contents to deepen my understanding about the topic.

Numpy

Library

In [1]:
import numpy as np

1-d array

In [3]:
arr = np.array([1, 2, 3, 4, 5, 6])
arr
Out[3]:
array([1, 2, 3, 4, 5, 6])

Select elements

the first one

In [4]:
arr[0]
Out[4]:
1

the last one

In [5]:
arr[-1]
Out[5]:
6

the second last one

In [8]:
arr[-2]
Out[8]:
5

by range

In [7]:
arr[2:4]
Out[7]:
array([3, 4])

by condition (even number)

In [16]:
np.mod(arr, 2)
Out[16]:
array([1, 0, 1, 0, 1, 0])
In [15]:
arr[np.mod(arr, 2) == 0]
Out[15]:
array([2, 4, 6])

Pandas

Library

In [18]:
import pandas as pd

1-d array (or series)

In [19]:
s = pd.Series([1, 3, 5, 7, 9, 11])
s
Out[19]:
0     1
1     3
2     5
3     7
4     9
5    11
dtype: int64

Select elements

the first one

In [24]:
s.iloc[0]
Out[24]:
1

the last one

In [25]:
s.iloc[-1]
Out[25]:
11

the second last one

In [26]:
s.iloc[-2]
Out[26]:
9

by range

In [27]:
s.iloc[3:5]
Out[27]:
3    7
4    9
dtype: int64

by condition

In [30]:
np.mod(s, 3)
Out[30]:
0    1
1    0
2    2
3    1
4    0
5    2
dtype: int64
In [31]:
s[np.mod(s, 3) == 0]
Out[31]:
1    3
4    9
dtype: int64

Comments

Comments powered by Disqus