Python Pandas dataframe.asfreq()

Python Pandas dataframe.asfreq()

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

Pandas dataframe.asfreq()函数用于将时间序列转换为指定频率。这个函数可以选择提供填充方法来填充/回填缺失的值。它返回符合指定频率的新索引的原始数据。如果需要进行总结等操作来表示新频率下的数据,那么resample就更合适。

语法 : DataFrame.asfreq(freq, method=None, how=None, normalize=False, fill_value=None)

参数 :
freq : DateOffset对象,或字符串
method:用于填补重新索引系列的漏洞的方法
how: 仅对于PeriodIndex,见PeriodIndex.asfreq
normalize : 是否将输出指数重置为午夜时分
fill_value :用于缺失值的值,在上升采样过程中应用(注意这并不填补已经存在的NaN)。

返回:转换:调用者的类型

例子#1:将时间序列数据从周频改为日频进行取样

# importing pandas as pd
import pandas as pd
  
# Creating a date_time form index 
index_values = (pd.date_range('1/1/2000',
                   periods=3,freq='W'))
  
# Creating a series using 'index_values'
# Notice, one of the series value is nan value
series = (pd.Series([0.0,None,2.0],
              index=index_values))
  
# Creating dataframe using the series
df=pd.DataFrame({"Col_1":series})
  
# Print the Dataframe
df

Python Pandas dataframe.asfreq()

现在把这个每周采样的数据取消采样,变成每日采样的数据。默认情况下,新创建的bin会有nan值。因此,使用fill_value参数将所有新创建的bins填上一个提供的值。

# unsampling and providing a fill value = 9.0
df.asfreq(freq ='D', fill_value = 9.0)

输出 :
Python Pandas dataframe.asfreq()

注意:这不会填补采样前已经存在的NaN。

例子2:将一分钟的时间戳数据取消采样为30s bins.首先创建一个有5个一分钟时间戳的系列。

# importing pandas as pd
import pandas as pd
  
# Creating a date_time form index 
index_values = (pd.date_range('1/1/2000',
                     periods=5,freq='T'))
  
# Creating a series using 'index_values'
# Notice, one of the series value is nan value
series = (pd.Series([0.0,1.0,None,3.0,4.0],
                      index=index_values))
  
# Creating dataframe using the series
df=pd.DataFrame({"Col_1":series})
  
# Print the Dataframe
df

Python Pandas dataframe.asfreq()

现在,取消对30秒的采样,并提供一个100.0的填充值。

# unsampling and providing a fill value of 100.0
df.asfreq(freq ='30S', fill_value = 100.0)

输出 :

Python Pandas dataframe.asfreq()

注意:取消采样前存在的Nan值将不会被填补。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程