w3resource

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

 

Python 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]

Python 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 Python skills with w3resource's quiz



Python: Tips of the Day

Python: Membership Testing in a Collection

>>> a = ('one', 'two', 'three', 'four', 'five')
>>> if 'one' in a:
...     print('The tuple contains one.')
... 
The tuple contains one.
>>> b = {0: 'zero', 1: 'one', 2: 'two', 3: 'three'}
>>> if 2 in b.keys():
...     print('The dict has the key of 2.')
... 
The dict has the key of 2.