Python是進行數據分析的一種出色語言,主要是因為以數據為中心的python軟件包具有奇妙的生態係統。 Pandas是其中的一種,使導入和分析數據更加容易。
Pandas dataframe.shift()
函數根據需要的周期數移動索引,並帶有可選的時間頻率。該函數采用稱為周期的標量參數,該參數表示要在所需軸上進行的平移次數。處理時間序列數據時,此函數非常有用。
用法:DataFrame.shift(periods=1, freq=None, axis=0)
參數:
periods: Number of periods to move, can be positive or negative
freq: DateOffset, timedelta, or time rule string, optional Increment to use from the tseries module or time rule (e.g. ‘EOM’). See Notes
axis: {0 or ‘index’, 1 or ‘columns’}
返回:shifted:DataFrame
範例1:采用shift()
在時間序列數據中將索引軸移動2個周期的函數
# importing pandas as pd
import pandas as pd
# Creating row index values for our data frame
# We have taken time frequency to be of 12 hours interval
# We are 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.shift()
使索引軸向正方向移動2個周期的函數
# shift index axis by two periods in positive direction
# axis = 0 is set by default
df.shift(2, axis = 0)
讓索引軸在負方向上移動一段時間
# shift index axis by two periods in negative direction
# axis = 0 is set by default
df.shift(-2, axis = 0)
輸出:
範例2:采用shift()
用於在時間序列數據中將列軸移動2個周期
# importing pandas as pd
import pandas as pd
# Creating row index values for our data frame
# We have taken time frequency to be of 12 hours interval
# We are 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.shift()
沿正方向將列軸移動2個周期的函數
# shift column axis by two periods in positive direction
df.shift(2, axis = 1)
讓列軸在負方向上移動一段時間
# shift column axis by two periods in negative direction
df.shift(-2, axis = 0)
輸出:
相關用法
- Python pandas.map()用法及代碼示例
- Python Pandas Series.str.len()用法及代碼示例
- Python Pandas.factorize()用法及代碼示例
- Python Pandas TimedeltaIndex.name用法及代碼示例
- Python Pandas dataframe.ne()用法及代碼示例
- Python Pandas Series.between()用法及代碼示例
- Python Pandas DataFrame.where()用法及代碼示例
- Python Pandas Series.add()用法及代碼示例
- Python Pandas.pivot_table()用法及代碼示例
- Python Pandas Series.mod()用法及代碼示例
- Python Pandas Dataframe.at[ ]用法及代碼示例
- Python Pandas Dataframe.iat[ ]用法及代碼示例
- Python Pandas.pivot()用法及代碼示例
- Python Pandas dataframe.mul()用法及代碼示例
- Python Pandas.melt()用法及代碼示例
注:本文由純淨天空篩選整理自Shubham__Ranjan大神的英文原創作品 Python | Pandas dataframe.shift()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。