Python dataframe.mean()和切片错误的问题
我有两个数据库: df1: df2: 我的目标是,如果Python dataframe.mean()和切片错误的问题,python,pandas,datetime,mean,Python,Pandas,Datetime,Mean,我有两个数据库: df1: df2: 我的目标是,如果control_1为True,则计算从df2开始的两个日期之间的平均值 for i in range(0,df1.row): #I go through my data df1 if (control_1.iloc[i]==True): #I check if control_1 is true date_1=df1.in
control_1
为True
,则计算从df2
开始的两个日期之间的平均值
for i in range(0,df1.row): #I go through my data df1
if (control_1.iloc[i]==True): #I check if control_1 is true
date_1=df1.index[i]-pd.to_timedelta(6, unit='d') # I remove 6 days from my date
date_2=df1.index[i]-pd.to_timedelta(244, unit='d') # I remove 244 days from my date
df1.["Average_return"].iloc[i]=df2["return"].iloc[date_1:date_2].mean()
# I want to make the mean of the return between my date-6 days and my date-244 days
不幸的是,它给了我这个错误:
TypeError: cannot do slice indexing on <class 'pandas.core.indexes.base.Index'> with these indexers [2019-05-31] of <class 'datetime.date'>
TypeError:无法使用的这些索引器[2019-05-31]对进行切片索引
有人能帮我吗:)
来自df1的csv文件是:(control_1.iloc[i]=True)检查此项;)它应该是
control\u 1.iloc[i]==True吗?是打字错误还是你的代码是这样运行的?谢谢你们,我复制代码时是个错误。:)不幸的是,问题仍然存在。您能否提供输入文件的复制部分+用于读入的代码行,或者您也尝试过的示例数据帧,而不是df1和df2的打印输出?我理解。我将删除我的问题,并将其改写得更清楚
for i in range(0,df1.row): #I go through my data df1
if (control_1.iloc[i]==True): #I check if control_1 is true
date_1=df1.index[i]-pd.to_timedelta(6, unit='d') # I remove 6 days from my date
date_2=df1.index[i]-pd.to_timedelta(244, unit='d') # I remove 244 days from my date
df1.["Average_return"].iloc[i]=df2["return"].iloc[date_1:date_2].mean()
# I want to make the mean of the return between my date-6 days and my date-244 days
TypeError: cannot do slice indexing on <class 'pandas.core.indexes.base.Index'> with these indexers [2019-05-31] of <class 'datetime.date'>