Python | Панды DatetimeIndex.to_frame ()

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

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

Pandas DatetimeIndex.to_frame() function create a DataFrame with a column containing the Index. By default the labels of the DatetimeIndex object is used as an index for the newly constructed Dataframe.

Syntax: DatetimeIndex.to_frame(index=True)

Parameters :
index : Set the index of the returned DataFrame as the original Index

Return : DataFrame containing the original Index data.

Example #1: Use DatetimeIndex.to_frame() function to create a DataFrame object from the given DatetimeIndex object. Also set the index value to False

# importing pandas as pd
import pandas as pd
  
# Create the DatetimeIndex
# Here "S" represents secondly frequency 
didx = pd.DatetimeIndex(start ="2018-11-15 09:45:10", freq ="S", periods = 5)
  
# Print the DatetimeIndex
print(didx)

Выход :

Now we want to construct a DataFrame out of the DatetimeIndex object.

# construct the DataFrame
didx.to_frame(index = False)

Output :

As we can see in the output, the function has returned a DataFrame object constructed from the didx DatetimeIndex object.
 
Example #2: Use DatetimeIndex.to_frame() function to create a DataFrame object from the given DatetimeIndex object.

# importing pandas as pd
import pandas as pd
  
# Create the DatetimeIndex
# Here "M" represents monthly frequency 
didx = pd.DatetimeIndex(start ="2015-03-02", freq ="M", periods = 5)
  
# Print the DatetimeIndex
print(didx)

Выход :

Now we want to construct a DataFrame out of the DatetimeIndex object.

# construct the DataFrame
didx.to_frame(index = True)

Выход :

Как мы видим в выходных данных, функция вернула объект DataFrame, созданный из объекта didx DatetimeIndex.

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

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