如何将Shift与Apply函数一起使用来遍历行?

问题描述

对于以日期为索引的股价数据帧,当我使用shift()获取先前值并使用apply()创建存储先前值的列时,会出现以下错误:

AttributeError: 'numpy.float64' object has no attribute 'shift'

以下是生成此错误的代码:

df.head(10)
             Open   High    Low  Close    Volume
Date                                            
2004-01-01  66.60  71.55  66.70  71.55  664600.0
2004-01-02  71.55  76.85  73.55  74.50  608500.0
2004-01-05  74.50  77.00  73.50  73.50  249400.0
2004-01-06  73.50  74.45  72.30  73.30  248600.0
2004-01-07  73.30  74.75  72.95  73.50   98600.0
2004-01-08  73.50  74.25  72.00  72.60   97000.0
2004-01-09  72.60  73.50  72.05  72.80   66900.0
2004-01-12  72.80  74.10  72.65  72.65   75100.0
2004-01-13  72.65  73.50  71.55  72.50   80500.0
2004-01-14  72.50  72.75  68.90  68.90  176100.0
  1. 我们创建一个函数,然后使用apply创建列:
def momentum(df):

    df['Pre_Close'] = df['Close'].shift(-1)

df['Pre_Close']= df.apply( lambda df: momentum(df),axis=1)

问题:请帮助解决此错误。 (注意):为了使功能简单,我跳过了很多代码)

AttributeError: 'numpy.float64' object has no attribute 'shift'

解决方法

以下代码段起作用的原因是,将单列括在额外的方括号内,返回DataFrame

df['Pre_Close'] = df[['Close']].shift(-1) 

df[['Column Name']] -----> returns a DataFrame
df['Column Name'] -----> returns a Series

关于从列shift中提取先前值的目的,也是最简单的使用方法,并且达到了目的

其他更程序化的方法如下

由于每个列的值本质上都是list/numpy array

以下功能非常简单,仅在一维输入中起作用

def shift_vector(inp,shift):

    if isinstance(inp,list):
       n = len(inp)
       first_half = [0] * shift
       return return first_half + inp[shift:]
    elif isinstance(inp,numpy.ndarray):
       n = len(inp)
       first_half = np.zeros(1,shift)
       return numpy.concatenate([first_half,inp[shift:])

该想法是在一个非常简单的级别上演示如何使用索引来实现移位

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...