Python Pandas dataframe.slice_shift()

Python Pandas dataframe.slice_shift()

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

Pandas dataframe.slice_shift()函数等同于不复制数据的移位。移位后的数据将不包括删除的周期,移位后的axis将比原来的小。这个函数只是在给定的axis上按指定的方向丢掉指定数量的周期。

语法: DataFrame.slice_shift(periods=1, axis=0)

参数 :
periods:移动的周期数,可以是正数或负数

返回:移位:与调用者的类型相同

示例#1:使用slice_shift()函数将时间序列数据中的索引axis移动2个周期。

# importing pandas as pd
import pandas as pd
   
# Creating row index values for dataframe
# We have 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 4 columns
# using "ind" as the index for our dataframe
df = pd.DataFrame({"A":[1, 2, 3, 4, 5], 
                   "B":[10, 20, 30, 40, 50], 
                   "C":[11, 22, 33, 44, 55],
                   "D":[12, 24, 51, 36, 2]}, index = ind)
  
# Print the dataframe
df
Python

Python Pandas dataframe.slice_shift()

让我们使用dataframe.slice_shift()函数将索引axis向正方向移动2个周期。

# shift index axis by two
# periods in positive direction
# axis = 0 is set by default
df.slice_shift(2, axis = 0)
Python

输出 :
Python Pandas dataframe.slice_shift()
注意指数标签,前两个标签被放弃了,但数据已经在正方向上转移了两个时期。

我们也可以将指数axis向负方向移动一些时期

# shift index axis by two 
# periods in negative direction
# axis = 0 is set by default
df.slice_shift(-2, axis = 0)
Python

输出 :
Python Pandas dataframe.slice_shift()
注意在输出中,数据点已经在负方向(即向上)移动了2个周期,最后两个指数标签已经被删除。

例子2:使用slice_shift()函数将时间序列数据的列axis移动2个周期。

# importing pandas as pd
import pandas as pd
   
# Creating row index values for our data frame
# 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 4 columns
# using "ind" as the index for our dataframe
df = pd.DataFrame({"A":[1, 2, 3, 4, 5],
                   "B":[10, 20, 30, 40, 50],
                   "C":[11, 22, 33, 44, 55],
                   "D":[12, 24, 51, 36, 2]}, index = ind)
  
# shift column axis by two periods in positive direction
df.slice_shift(2, axis = 1)
Python

输出 :
Python Pandas dataframe.slice_shift()
在输出中,我们可以看到前两列标签被删除,数据点沿列axis向正方向移动了2个周期。

我们也可以将柱axis向负方向移动一些时期

# shift column axis by two periods in negative direction
df.slice_shift(-2, axis = 0)
Python

输出 :
Python Pandas dataframe.slice_shift()
在输出中,我们可以看到最后两列标签被删除了,数据点沿着列axis在负方向(即左边)被移动了2个周期。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册