Python Pandas DatetimeIndex.to_period()

Python Pandas DatetimeIndex.to_period()

Python是一种进行数据分析的伟大语言,主要是因为以数据为中心的Python包的奇妙生态系统。Pandas就是这些包中的一个,它使导入和分析数据变得更加容易。

Pandas DatetimeIndex.to_period()函数用于将给定的DatetimeIndex按特定频率转换为PeriodIndex。该函数基本上将DatetimeIndex转换为PeriodimeIndex。

语法: DatetimeIndex.to_period(freq=None)

参数 :
freq : pandas偏移量字符串之一或一个偏移量对象。默认情况下会被推断出来

返回 : PeriodIndex

示例#1:使用DatetimeIndex.to_period()函数将DatetimeIndex对象的数据转换为PeriodIndex。

# 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)
Python

输出 :
Python Pandas DatetimeIndex.to_period()

现在我们要把DatetimeIndex对象转换为PeriodIndex对象。

# cast to PeriodIndex
# 'T' represents minute based frequency
didx.to_period('T')
Python

输出 :
Python Pandas DatetimeIndex.to_period()
正如我们在输出中看到的,该函数已经将DatetimeIndex对象转换为PeriodIndex对象。

示例#2:使用DatetimeIndex.to_period()函数将DatetimeIndex对象的数据转换为PeriodIndex。

# importing pandas as pd
import pandas as pd
  
# Create the DatetimeIndex
# Here 'T' represents minutely frequency 
didx = pd.DatetimeIndex(start ='2015-03-02 01:15:12', freq ='T', periods = 5)
  
# Print the DatetimeIndex
print(didx)
Python

输出 :
Python Pandas DatetimeIndex.to_period()

现在我们要把DatetimeIndex对象转换为PeriodIndex对象。

# cast to PeriodIndex
# 'H' represents hourly frequency
didx.to_period('H')
Python

输出 :
Python Pandas DatetimeIndex.to_period()
正如我们在输出中看到的,该函数已经将DatetimeIndex对象转换为PeriodIndex对象。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

Pandas 日期时间