Tuesday, November 19, 2024
Google search engine
HomeLanguagesPython | Pandas DatetimeIndex.snap()

Python | Pandas DatetimeIndex.snap()

Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.

Pandas DatetimeIndex.snap() function is used to snap time stamps to nearest occurring frequency. The function takes a single parameter which is the frequency that we want to be applied while snapping the timestamp values of the DatetimeIndex object.

Syntax: DatetimeIndex.snap(freq)

Parameters :
freq : frequency

Return : DatetimeIndex

Example #1: Use DatetimeIndex.snap() function to convert the given DatetimeIndex object to the nearest occurring frequency based on the input frequency.




# importing pandas as pd
import pandas as pd
  
# Create the DatetimeIndex
# Here 'Q' represents quarter end frequency 
didx = pd.DatetimeIndex(start ='2000-01-15 08:00', freq ='Q',
                          periods = 4, tz ='Asia/Calcutta')
  
# Print the DatetimeIndex
print(didx)


Output :

Now we want to convert the given DatetimeIndex object timestamp values to the nearest frequency based on the input.




# snap the timestamp to the nearest frequency 
didx.snap('MS')


Output :

As we can see in the output, the function has snapped each timestamp value in the given DatetimeIndex object.
 
Example #2: Use DatetimeIndex.snap() function to convert the given DatetimeIndex object to the nearest occurring frequency based on the input frequency.




# importing pandas as pd
import pandas as pd
  
# Create the DatetimeIndex
# Here 'MS' represents month start frequency 
didx = pd.date_range(pd.Timestamp("2000-01-15 08:00"), 
                              periods = 5, freq ='MS')
  
# Print the DatetimeIndex
print(didx)


Output :

Now we want to convert the given DatetimeIndex object timestamp values to the nearest frequency based on the input.




# snap the timestamp to the nearest frequency 
didx.snap('Q')


Output :

As we can see in the output, the function has snapped each timestamp value in the given DatetimeIndex object.

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments