Python | Pandas dataframe.at_time()
Last Updated :
06 Aug, 2021
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
import pandas as pd
ind = pd.date_range( '01/ 01/2000' , periods = 5 , freq = '12H' )
df = pd.DataFrame({ "A" :[ 1 , 2 , 3 , 4 , 5 ],
"B" :[ 10 , 20 , 30 , 40 , 50 ]},
index = ind)
df
|
Now find out the values 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
import pandas as pd
ind = pd.date_range( '01/01/2000' , periods = 8 , freq = '30T' )
df = pd.DataFrame({ "A" :[ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 ],
"B" :[ 10 , 20 , 30 , 40 , 50 , 60 , 70 , 80 ]},
index = ind)
df
|
Now let’s query for time “02:00”
Output :
Share your thoughts in the comments
Please Login to comment...