如何使此函数在具有datetime.index的python数据帧中工作



我为自己编写了以下代码。问题是它在一个单独的新文档中工作,但当我试图将它应用于以日期时间为索引的数据帧时,它不起作用。出现错误。知道如何修改它以便在datetime.index df上使用吗?提前谢谢!

我得到的错误,指向下面代码的最后一行,是:

TypeError:不再支持对带有时间戳的整数和整数数组进行加法/减法运算。使用`n*而不是加减n

import pandas as pd 
import numpy as np
Z30 = [1,1.2,0.85,0.50,-0.50,-1.20,-1.85,0.75,1.5,2]
df = pd.DataFrame(Z30)
df.columns = ['Z30']
df['Z30DELTA'] = 0
def condition(df,i):
if  df.loc[i, 'Z30'] > 1 or  df.loc[i, 'Z30'] < -1:
return 1
else:
return 0
for i in range(1, len(df)):

df.loc[i, 'Z30DELTA'] = df.loc[i-1, 'Z30DELTA'] + df.loc[i, 'Z30']* condition(df,i)

df.loc[]是基于标签的索引。如果您的索引是datetime,则不能使用df.loc[i ,'col](其中i是整数(来访问值,因为datetime索引中没有标签i。您可以改用df.loc[df.index[i] ,'col]

def condition(df,i):
if  df.loc[i, 'Z30'] > 1 or  df.loc[i, 'Z30'] < -1:
return 1
else:
return 0
for i in range(1, len(df)):
df.loc[df.index[i], 'Z30DELTA'] = df.loc[df.index[i-1], 'Z30DELTA'] + df.loc[df.index[i], 'Z30']* condition(df, df.index[i])

你可以试试这个:

import pandas as pd 
import numpy as np
Z30 = [1,1.2,0.85,0.50,-0.50,-1.20,-1.85,0.75,1.5,2]
df = pd.DataFrame({'Z30': Z30})
df = df.set_index(pd.date_range(start='1/1/2018', periods=10))
df['Z30DELTA'] = 0

def condition(df,i):
if  df.loc[i, 'Z30'] > 1 or  df.loc[i, 'Z30'] < -1:
return 1
else:
return 0
for i, values in df.iterrows():
loc = df.index.get_loc(i)
print(loc)
df.loc[i, 'Z30DELTA'] = df['Z30DELTA'].iloc[loc-1]  + df.loc[i, 'Z30']* condition(df,i)
print(df)

它提供所需的输出。

最新更新