更新DataFrame后,我的for循环无法正常运行(我不是程序员。我使用的是python 2.7.15)。我的代码效率不高,但是仍然可以正常工作,因此请不要更改我的循环,仅告诉我如何更改DataFrame。
从AlphaVantage下载的DataFrame如下所示:
Open High ... 8. split coefficient datetime
0 31.1100 31.3500 ... 1.0000 2018-07-23
1 31.2900 31.3100 ... 1.0000 2018-07-20
2 28.4800 29.1200 ... 1.0000 2018-07-26
3 28.8200 29.3350 ... 1.0000 2018-07-27
4 30.4500 30.9400 ... 1.0000 2018-07-24
当我更新到DataFrame时,如下所示:
Open High Low Close AdjClose Volume
datetime
2018-07-23 31.1100 31.3500 30.6000 30.8200 30.8200 6023310
2018-07-20 31.2900 31.3100 30.8450 31.1100 31.1100 5022452
2018-07-26 28.4800 29.1200 27.5500 28.9800 28.9800 10582061
2018-07-27 28.8200 29.3350 27.7050 28.1300 28.1300 8101362
2018-07-24 30.4500 30.9400 29.9650 30.1400 30.1400 5706941
一旦用我的循环运行程序,我就会收到此错误:
TypeError: cannot insert DatetimeIndex with incompatible label
该代码的相关部分是:
import requests
import pandas as pd
import numpy as np
import json
import datetime as dt
import matplotlib as plt
.
.
.
df['datetime'] = pd.to_datetime(df['datetime'])
df.set_index('datetime', inplace=True)
df.sort_index(inplace=False)
# extract the default columns
df = df[columns]
return df
df = df_from_response(data)
df.sort_index(ascending=True, inplace=False) # Current day on top data frame
A=pd.DataFrame(df)
print (A.head(5)) #3
Len=len(A)
print (Len)
# Upward and Downward movement calculation
for Rw in range(Len-1):
def adj(A):
adj_N=float(A.iloc[Rw,4])
adj_O=float(A.iloc[Rw+1,4])
#print (adj_N,adj_O)
if adj_N>adj_O:
x1=adj_N-adj_O
x2=0
如您所见,索引“ datetime”消失了,但是我想要两个新列。因此,如何在新列中看到索引“ datetime”?同样,请保持我的“ for循环不变”。
相关分类