Python Pandas DataFrame.tshift

Python Pandas DataFrame.tshift

Pandas DataFrame是一个二维的大小可变的,可能是异质的表格数据结构,有标记的axis(行和列)。算术操作在行和列的标签上对齐。它可以被认为是一个类似于Dict的系列对象的容器。这是Pandas的主要数据结构。

Pandas DataFrame.tshift()函数用于移动时间索引,如果在给定的数据框架中可用,则使用索引的频率。

语法: DataFrame.tshift(periods=1, freq=None, axis=0)

参数:
periods:移动的周期数,可以是正数或负数
freq : 使用tseries模块或时间规则的增量(例如,’EOM’)。
axis:对应于包含索引的axis。

返回 : shifted : NDFrame

示例#1:使用DataFrame.tshift()函数将给定数据框架的基于Datetime的索引移动5小时。

# importing pandas as pd
import pandas as pd
  
# Creating the DataFrame
df = pd.DataFrame({'Weight':[45, 88, 56, 15, 71],
                   'Name':['Sam', 'Andrea', 'Alex', 'Robin', 'Kia'],
                   'Age':[14, 25, 55, 8, 21]})
  
# Create the index
index_ = pd.date_range('2010-10-09 08:45', periods = 5, freq ='H')
  
# Set the index
df.index = index_
  
# Print the DataFrame
print(df)
Python

输出 :

Python Pandas DataFrame.tshift

现在我们将使用DataFrame.tshift()函数将给定数据框架的基于日期时间的索引移动5小时。我们将把’5H’作为频率值传递给该函数。

# Shift by 5 hours
result = df.tshift(freq = '5H')
  
# Print the result
print(result)
Python

输出 :

Python Pandas DataFrame.tshift

正如我们在输出中看到的,DataFrame.tshift()函数已经成功地将给定数据框架的基于Datetime的索引按指定频率进行了转移。

示例#2 :使用DataFrame.tshift()函数将给定数据框架的基于Datetime的索引移动-30个周期。

# importing pandas as pd
import pandas as pd
  
# Creating the DataFrame
df = pd.DataFrame({'Weight':[45, 88, 56, 15, 71],
                   'Name':['Sam', 'Andrea', 'Alex', 'Robin', 'Kia'],
                   'Age':[14, 25, 55, 8, 21]})
  
# Create the index
index_ = pd.date_range('2010-10-09 08:45', periods = 5, freq ='H')
  
# Set the index
df.index = index_
  
# Print the DataFrame
print(df)
Python

输出 :

Python Pandas DataFrame.tshift

现在我们将使用DataFrame.tshift()函数将给定数据框架的基于日期时间的指数转移到-30期。这将使同一频率的指数在过去的30个时期内移动。

# Shift by -30 periods
result = df.tshift(periods = -30)
  
# Print the result
print(result)
Python

输出 :

Python Pandas DataFrame.tshift

正如我们在输出中看到的,DataFrame.tshift()函数已经成功地将给定数据框架的基于Datetime的索引转移到了指定的时期。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册