Python | Pandas dataframe.at_time ()

Опубликовано: 29 Марта, 2022

Python - отличный язык для анализа данных, в первую очередь из-за фантастической экосистемы пакетов Python, ориентированных на данные. Pandas - один из таких пакетов, который значительно упрощает импорт и анализ данных.

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

# 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”

df.at_time("12:00")

Выход :

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 datframe) .

# 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”

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

Выход :

Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.

Для начала подготовьтесь к собеседованию. Расширьте свои концепции структур данных с помощью курса Python DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение - базовый уровень.