简体   繁体   中英

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:

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

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

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM