+4 votes
in Programming Languages by (9.6k points)
I have a list of random numbers. I want to check whether those numbers are monotonically increasing or decreasing. Is there any Python function for it?

1 Answer

+1 vote
by (42.1k points)

You can use the is_monotonic_increasing or is_monotonic_decreasing attribute of pandas's Series to check if the list of numbers is monotonically increasing or decreasing, respectively.

First, you need to convert your list to pandas Series to apply these attributes.

Here is an example to show how to convert a list to a Series and apply these attributes:

>>> import pandas as pd
>>> v
[2828978234.6720667, 2523723428.4042473, 2493970473.7634807, 2478117503.102314, 2453217115.4810367, 2446309458.763538, 2439580319.7837763, 2376784754.3911676, 2362926245.68204, 2354647422.048292, 2343058355.8204017, 2338062923.4045787, 2335978334.3602896, 2327838580.2337847, 2324959353.4350915, 2307427379.9857135, 2305581479.4816375, 2299412512.127759, 2298692239.1688786, 2295844865.3728147, 2294971760.7162547, 2292083426.77864, 2289618975.0881863, 2279046140.6888947]
>>> ds = pd.Series(v)  # convert list to Series
>>> ds
0     2.828978e+09
1     2.523723e+09
2     2.493970e+09
3     2.478118e+09
4     2.453217e+09
5     2.446309e+09
6     2.439580e+09
7     2.376785e+09
8     2.362926e+09
9     2.354647e+09
10    2.343058e+09
11    2.338063e+09
12    2.335978e+09
13    2.327839e+09
14    2.324959e+09
15    2.307427e+09
16    2.305581e+09
17    2.299413e+09
18    2.298692e+09
19    2.295845e+09
20    2.294972e+09
21    2.292083e+09
22    2.289619e+09
23    2.279046e+09
dtype: float64
>>> ds.is_monotonic_decreasing
True
>>> ds.is_monotonic_increasing
False

...