Python 官方文档:入门教程 => 点击学习
目录语法示例在python数据分析中,可以使用shift()方法对DataFrame对象的数据进行位置的前滞、后滞移动。 语法 DataFrame.shift(periods=1,
在python数据分析中,可以使用shift()方法对DataFrame对象的数据进行位置的前滞、后滞移动。
DataFrame.shift(periods=1, freq=None, axis=0)
移动滞后没有对应值的默认为NaN。
period为正,无freq
import pandas as pd
pd.set_option('display.unicode.east_asian_width', True)
data = [51.0, 52.33, 51.21, 54.23, 56.78]
index = ['2022-2-28', '2022-3-1', '2022-3-2', '2022-3-3', '2022-3-4']
df = pd.DataFrame(data=data, index=index, columns=['close'])
df.index.name = 'date'
print(df)
print("=========================================")
df['昨收'] = df['close'].shift()
df['change'] = df['close'] - df['close'].shift()
print(df)
period为负,无freq
import pandas as pd
pd.set_option('display.unicode.east_asian_width', True)
data = [51.0, 52.33, 51.21, 54.23, 56.78]
index = ['2022-2-28', '2022-3-1', '2022-3-2', '2022-3-3', '2022-3-4']
index = pd.to_datetime(index)
index.name = 'date'
df = pd.DataFrame(data=data, index=index, columns=['昨收'])
print(df)
print("=========================================")
df['close'] = df['昨收'].shift(-1)
df['change'] = df['昨收'].shift(-1) - df['close']
print(df)
period为正,freq为正
import pandas as pd
import datetime
pd.set_option('display.unicode.east_asian_width', True)
data = [51.0, 52.33, 51.21, 54.23, 56.78]
index = ['2022-2-28', '2022-3-1', '2022-3-2', '2022-3-3', '2022-3-4']
index = pd.to_datetime(index)
index.name = 'date'
df = pd.DataFrame(data=data, index=index, columns=['close'])
print(df)
print("=========================================")
print(df.shift(periods=2, freq=datetime.timedelta(3)))
如图,索引列的时间序列数据滞后了6天。(二乘以三)
period为正,freq为负
import pandas as pd
import datetime
pd.set_option('display.unicode.east_asian_width', True)
data = [51.0, 52.33, 51.21, 54.23, 56.78]
index = ['2022-2-28', '2022-3-1', '2022-3-2', '2022-3-3', '2022-3-4']
index = pd.to_datetime(index)
index.name = 'date'
df = pd.DataFrame(data=data, index=index, columns=['close'])
print(df)
print("=========================================")
print(df.shift(periods=3, freq=datetime.timedelta(-3)))
如图,索引列的时间序列数据前滞了9天(三乘以负三)
period为负,freq为负
import pandas as pd
import datetime
pd.set_option('display.unicode.east_asian_width', True)
data = [51.0, 52.33, 51.21, 54.23, 56.78]
index = ['2022-2-28', '2022-3-1', '2022-3-2', '2022-3-3', '2022-3-4']
index = pd.to_datetime(index)
index.name = 'date'
df = pd.DataFrame(data=data, index=index, columns=['close'])
print(df)
print("=========================================")
print(df.shift(periods=-3, freq=datetime.timedelta(-3)))
如图,索引列的时间序列数据滞后了9天(负三乘以负三)
到此这篇关于Python DataFrame的shift()方法的使用的文章就介绍到这了,更多相关python DataFrame shift() 内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
--结束END--
本文标题: python DataFrame的shift()方法的使用
本文链接: https://www.lsjlt.com/news/141964.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0