Thursday, July 4, 2024
HomeLanguagesPythonPython | Pandas dataframe.at_time()

Python | Pandas dataframe.at_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.
Pandasdataframe.at_time() function is used to select all the values in a row corresponding to the input time of the day. If the input time is not present in the dataframe then an empty dataframe is returned.
 

Syntax: DataFrame.at_time(time, asof=False)
Parameters: 
time : datetime.time or string
Returns: values_at_time : type of caller
 

Note: at_time() function raises exception when the index of the dataframe is not a DatetimeIndex
Example #1: Create a datetime indexed dataframe and retrieve the values at any specific time 
 

Python3




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


Now find out the values at time “12:00”
 

Python3




df.at_time('12:00')


Output : 
 

 
Example #2: Set the frequency of date_time index for 30 minute duration and query for both valid and invalid time (Not present in the dataframe) .
 

Python3




# importing pandas as pd
import pandas as pd
 
# Creating row index values for our data frame
# We have taken time frequency to be of 30 minutes interval
# We are 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)
 
# Printing the dataframe
df


Now let’s query for time “02:00”
 

Python3




# Find the row values at time "02:00"
df.at_time('02:00')


Output : 
 

 

Nango Kalahttps://www.kala.co.za
Experienced Support Engineer with a demonstrated history of working in the information technology and services industry. Skilled in Microsoft Excel, Customer Service, Microsoft Word, Technical Support, and Microsoft Office. Strong information technology professional with a Microsoft Certificate Solutions Expert (Privet Cloud) focused in Information Technology from Broadband Collage Of Technology.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments