Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Confirm if column in a pandas dataframe is in a sequential order starting by one

Imagine I have the following column on a dataframe:

df['Col1'] = [1, 2, 3, 4, 6, 5]

What would be the best way to confirm if this column is in a sequential order having their lowest value starting with 1? In the example above, I would expect it to return "True".

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If need first sorting values and test sequential by difference is equal 1 for all values and then test if first value is 1:

df = pd.DataFrame({'Col1':[1, 2, 3, 4, 6, 5]})

out = (np.diff(df['Col1'].sort_values()) == 1).all() and (df['Col1'].iat[0] == 1)
print (out)
True

If need test first sorted value:

s = df['Col1'].sort_values()
out = (np.diff(s) == 1).all() and (s.iat[0] == 1)
print (out)
True

If difference of ordered values should be positive:

df = pd.DataFrame({'Col1':[1, 2, 3, 4, 8, 5]})

out = (np.diff(df['Col1'].sort_values()) > 0).all() and (df['Col1'].iat[0] == 1)
print (out)
True
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading