Search code examples
pythonpandasassert

how can i assert all values in a column have specific length in pandas?


I want to write assert statement for checking column 'client_id' has specific length = 12.

assert kcell[ kcell['client_id'].apply(lambda id: len(id) == 12 ]

or

assert (kcell[ kcell['client_id'].apply(lambda id: len(id) == 12])

Solution

  • If you want an actual assertion, run:

    assert kcell.client_id.apply(lambda n: len(str(n))).eq(12).all(), 'client_id length always 12'
    

    Note that kcell['client_id'].str.len() == 12 will fail if your column is of e.g. int type. My solution works for either int ot string column.