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]:
Select elements¶
the first one¶
In [4]:
arr[0]
Out[4]:
the last one¶
In [5]:
arr[-1]
Out[5]:
the second last one¶
In [8]:
arr[-2]
Out[8]:
by range¶
In [7]:
arr[2:4]
Out[7]:
by condition (even number)¶
In [16]:
np.mod(arr, 2)
Out[16]:
In [15]:
arr[np.mod(arr, 2) == 0]
Out[15]:
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]:
Select elements¶
the first one¶
In [24]:
s.iloc[0]
Out[24]:
the last one¶
In [25]:
s.iloc[-1]
Out[25]:
the second last one¶
In [26]:
s.iloc[-2]
Out[26]:
by range¶
In [27]:
s.iloc[3:5]
Out[27]:
by condition¶
In [30]:
np.mod(s, 3)
Out[30]:
In [31]:
s[np.mod(s, 3) == 0]
Out[31]:
Comments
Comments powered by Disqus