Sunday, December 29, 2024
Google search engine
HomeLanguagesPython | Pandas dataframe.between_time()

Python | Pandas dataframe.between_time()

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 dataframe.between_time() is used to select values between particular times of the day (e.g. 9:00-9:30 AM). Unlike dataframe.at_time() function, this function extracts values in a range of time. This function is only used with time-series data. The index of the Dataframe must be DatetimeIndex in order to be able to use this function.

Syntax: DataFrame.between_time(start_time, end_time, include_start=True, include_end=True)

Parameters:
start_time : datetime.time or string
end_time : datetime.time or string
include_start : boolean, default True
include_end : boolean, default True

Returns: values_between_time : type of caller

Note: between_time() function raises exception when the index of the dataframe is not a DatetimeIndex

Example #1: Use between_time() function to find the values between a given time interval.




# importing pandas as pd
import pandas as pd
  
# Creating row index values for dataframe
# Taken time frequency to be of 30 minutes interval
# Generating eight index value using "period = 8" parameter
ind = pd.date_range('01/01/2000', periods = 8, freq ='30T')
  
# Creating a dataframe with 2 columns
# using "ind" as the index for dataframe
  
df = pd.DataFrame({"A":[1, 2, 3, 4, 5, 6, 7, 8],
                   "B":[10, 20, 30, 40, 50, 60, 70, 80]},
                                             index = ind)
  
# Printing the dataframe
df


Now let’s query for time between “02:00” to “03:30”




# Find the row values between time "02:00" to "03:30"
df.between_time('02:00', '03:30')


Output :

 
Example #2: Use between_time() function to find the values between a given time interval while excluding the start and end times.




# importing pandas as pd
import pandas as pd
  
# Creating row index values for our data frame
# Taken time frequency to be of 30 minutes interval
# Generating eight index value using "period = 8" parameter
ind = pd.date_range('01/01/2000', periods = 8, freq ='30T')
  
# Creating a dataframe with 2 columns
# using "ind" as the index for our dataframe
  
df = pd.DataFrame({"A":[1, 2, 3, 4, 5, 6, 7, 8],
                   "B":[10, 20, 30, 40, 50, 60, 70, 80]},
                                             index = ind)
  
# query for time between "02:00" to "03:30" with
# both the start and end time values being excluded
df.between_time('02:00', '03:30', include_start = False,
                                    include_end = False)


Output :

Notice the values corresponding to start time and end time is not included in the dataframe returned by the between_time() function.

RELATED ARTICLES

Most Popular

Recent Comments