python中shift(1)_Python Pandas dataframe.slice_shift()用法及代码示例

Python是进行数据分析的一种出色语言,主要是因为以数据为中心的python软件包具有奇妙的生态系统。 Pandas是其中的一种,使导入和分析数据更加容易。

Pandas dataframe.slice_shift()功能相当于在不复制数据的情况下进行移位。移位的数据将不包括丢失的周期,并且移位的轴将小于原始数据。该功能只是沿指定方向在给定轴上放置指定的周期数。

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

参数:

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

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

范例1:采用slice_shift()在时间序列数据中将索引轴移动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

让我们使用dataframe.slice_shift()使索引轴向正方向移动2个周期的功能

# shift index axis by two

# periods in positive direction

# axis = 0 is set by default

df.slice_shift(2, axis = 0)

输出:

注意索引标签,前两个标签已删除,但数据已沿正方向移动了两个周期。

我们还可以将索引轴沿负方向移动一些时间

# shift index axis by two

# periods in negative direction

# axis = 0 is set by default

df.slice_shift(-2, axis = 0)

输出:

请注意,在输出中,数据点已沿负方向(即向上)移动了2个周期,并且最后两个索引标签已被删除。

范例2:采用slice_shift()用于在时间序列数据中将列轴移动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)

输出:

在输出中,我们可以看到删除了前两个列标签,并且沿列轴的数据点已在正方向上移动了2个周期。

我们还可以将列轴沿负方向移动一些时间

# shift column axis by two periods in negative direction

df.slice_shift(-2, axis = 0)

输出:

在输出中,我们可以看到删除了最后两个列标签,并且沿列轴的数据点已沿负方向(即向左)移动了2个周期。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值