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

python dataframe datetime frequency extract 5 from '5S'

I am using pd.inter_freq(df.index) to know the data frequency. My question is, how to extract the digits from the string.
Code:

xdf = pd.DataFrame({'data':range(0,6)},index=pd.date_range('2022-06-03 00:00:00', '2022-06-03 00:00:25', freq='5s'))
print(pd.infer_freq(xdf.index))
# time frequency
tf = int(pd.infer_freq(xdf.index))

Expected output

tf = 5

Present output:

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

ValueError: invalid literal for int() with base 10: '5S'

>Solution :

Instead of parsing the output of pd.infer_freq(), read the number from the DatetimeIndex.freq directly:

>>> pd.infer_freq(xdf.index)
'5S'

>>> xdf.index.freq
<5 * Seconds>

>>> xdf.index.freq.n
5

>>> xdf.index.freq.name
'S'
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