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

Question:

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".

Asked By: Paulo Cortez

||

Answers:

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
Answered By: jezrael

You can use sets operation:

>>> False if set(df['Col1']).difference(range(1, 7)) else True
True
Answered By: Corralien
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.