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個周期。