之前写一个获取股票特征的代码,需要用到嵌套循环,分别获取特征的名字和向前回溯的天数,代码如下:
i = 0
day = 3
d = {}
f = ''
fls = df2.columns.values.tolist()#获取原始dataframe的列名。
for f in fls:
while i < day:#day是向前回溯的天数。
d['last_{}_{}'.format(f,i+1)] = df2[f].iloc[len(df2)-(len(df2)-i):len(df2)-(day-i)]#将列名和天数加以组合,作为字典的键。
i += 1
feature = pd.DataFrame(d)
print (feature)
fls列表一共有[‘open’, ‘close’, ‘high’, ‘low’, ‘volume’]五个字符串,想象中运行后会出现5*3个列的dataframe,分别为:
‘last_open_1’,
‘last_open_2’,
‘last_open_3’,
‘last_close_1’,
‘last_close_2’,
‘last_close_3’,
‘last_high_1’,
‘last_high_2’,
‘last_high_3’,
‘last_low_1’,
‘last_low_2’,
‘last_low_3’,
‘last_volume_1’,
‘last_volume_2’,
‘last_volume_3’
然而运行结果如下:
last_open_1 last_open_2 l