Friday, November 22, 2024
Google search engine
HomeLanguagesPython | 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 : 
 

 

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