pytest assert if a column is ascending or descending within another already sorted group

Viewed 284

I am running the following code:

import numpy as np
import pandas as pd

dfTestExample = pd.DataFrame(np.random.randint(0,100,size=(1000, 4)), columns=list('ABCD'))

dfTestExample = dfTestExample.sort_values(["A", "B"], ascending = [True, False])

dfTestExample.head(10)

which produces

    A   B   C   D
303 0   84  13  96
728 0   43  48  32
558 0   35  49  49
286 0   34  17  4
652 0   29  53  4
292 0   18  62  29
139 0   17  63  99
718 1   91  6   48
611 1   83  19  75
208 1   80  35  73
dfTestExample.A.is_monotonic
True
dfTestExample.B.is_monotonic
False

How do I check if the column B is also montonic for all values of A?

1 Answers

You can use groupby to split the dataframe into separate groups for each value of A:

monotonic = True
for group in df.groupby(['A']):
    b = group[1].B
    if not b.is_monotonic and not b.is_monotonic_decreasing:
        monotonic = False
print(monotonic)

groupby gives you a DataFrameGroupBy object. If you iterate over that object, you get tuples of index and DataFrame objects, and you can handle these separately. In your case the grouped DataFrame objects will look like:

    A   B   C   D
303 0   84  13  96
728 0   43  48  32
558 0   35  49  49
286 0   34  17  4
652 0   29  53  4
292 0   18  62  29
139 0   17  63  99

and:

    A   B   C   D
718 1   91  6   48
611 1   83  19  75
208 1   80  35  73

Note that if you want to know if a dataset is monotonically increasing or decreasing, you have to check both, as shown in the example.

Related