Home > other >  python dataframe datetime frequency extract 5 from '5S'
python dataframe datetime frequency extract 5 from '5S'

Time:06-04

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:

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

CodePudding user response:

You want to access the n property of freq.

>>> xdf.index.freq.n
5

To find the most frequent frequency, use mode:

>>> xdf.index.to_series().diff().dt.seconds.mode()
5

CodePudding user response:

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'
  • Related