Home > Software design >  How to verify whether string value is in correct range in Data Frame in Python Pandas?
How to verify whether string value is in correct range in Data Frame in Python Pandas?

Time:07-12

I have DataFrame in Python pandas like below ("col1" is data type string):

col1
-------
14212614414
05261265140
82044114467
...
  • Fifth and sixth values mean day of born.

How to check whether day are from the correct range, so fifth and sixth values should be from range 1 to 31.

col1        | col2
------------|-------
14212614414 | True
05261265140 | True
82044114467 | False
...

How can Ido that in Python Pandas?

CodePudding user response:

You can use the series.str accessor and slice the string, then treat it as an int with astype and check if it's between the numbers

df['col2']=df['col1'].str[4:6].astype(int).between(1,31)


col1    col2
0   14212614414 True
1   5261265140  True
2   82044114467 False
  • Related