w3resource

Pandas Data Series: Find the positions of the values neighboured by smaller values on both sides in a given series

 

Pandas: Data Series Exercise-32 with Solution

Write a Pandas program to find the positions of the values neighboured by smaller values on both sides in a given series.

Pictorial Presentation:

Pandas Data Series: Positions of the values surrounded by smaller values on both sides.

Sample Solution:

Python Code :

import pandas as pd
import numpy as np
nums = pd.Series([1, 8, 7, 5, 6, 5, 3, 4, 7, 1])
print("Original series:")
print(nums)
print("\nPositions of the values surrounded by smaller values on both sides:")
temp = np.diff(np.sign(np.diff(nums)))
result = np.where(temp == -2)[0] + 1
print(result)

Sample Output:

Original series:
0    1
1    8
2    7
3    5
4    6
5    5
6    3
7    4
8    7
9    1
dtype: int64

Positions of the values surrounded by smaller values on both sides:
[1 4 8]

Explanation:

nums = pd.Series([1, 8, 7, 5, 6, 5, 3, 4, 7, 1]): This code creates a Pandas Series object 'nums' containing ten integers.

temp = np.diff(np.sign(np.diff(nums))): This code first computes the second order difference of the 'nums' series using the np.diff() and np.sign() functions from the NumPy library. The diff() function computes the difference between consecutive elements in the 'nums' series, while the sign() function returns the sign of each element in the resulting difference series. The second order difference is obtained by computing the difference between consecutive elements of the resulting sign series.

result = np.where(temp == -2)[0] + 1: This code applies the np.where() function to find the positions in the second order difference series where the value is equal to -2. The where() function returns a tuple containing the indices where this condition is true, which are then added to 1 (since the diff() function reduces the length of the series by 1).

Python-Pandas Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Pandas program to compute the Euclidean distance between two given series.
Next: Write a Pandas program to replace missing white spaces in a given string with the least frequent character.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.