在选择 pandas 中的一部分数据时出现问题 [英] Problem in the selection of a part of data in pandas
本文介绍了在选择 pandas 中的一部分数据时出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下数据库是从csv文件中用熊猫提取的:
I have the following database that are extracted with pandas from csv files :
df1=pd.read_csv(path,parse_dates=True)
df1的打印结果为:
The print of df1 gives :
control Avg_return
2019-09-07 True 0
2019-06-06 True 0
2019-02-19 True 0
2019-01-17 True 0
2018-12-20 True 0
2018-11-27 True 0
2018-10-12 True 0
... ... ...
加载2个csv文件后
df2=pd.read_csv(path,parse_dates=True)
df2的打印结果为:
The print of df2 gives :
return
2010-01-01 NaN
2010-04-01 0.010920
2010-05-01 -0.004404
2010-06-01 -0.025209
2010-07-01 -0.023280
... ...
我的代码的目标是:
- 从df1开始约会
- 从第1点算起的日期减去6天.
- 从第1点算起的日期减去244天.
- 在df2中获取这两个日期以来的所有回报
- 计算这些收益的平均值并将其存储在Avg_return中
我这样做了:
for i in range(0,df1_row):
#I go through my data df1
if (control.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.loc[i,"Average_return"] = df2[[date_1:date_2],["return"]].mean()
# I want to make the mean of the return between my date-6 days and my date-244 days
不幸的是,它给了我这个错误:
Unfortunately it gives me this error :
df1.loc[i,"Average_return"] = df2[[date1:date2],["return"]].mean()
^
SyntaxError: invalid syntax
有人可以帮助我吗? :)
Is someone able to help me? :)
推荐答案
这是不遍历所有行的另一种方法:
This is a different approach without looping over all rows:
# make sure your index is a datetime index
df1.index = pd.to_datetime(df1.index)
df1['date_1'] = df1.index - pd.to_timedelta(6, unit='d')
df1['date_2'] = df1.index - pd.to_timedelta(244, unit='d')
df1['Average_return'] = df1.apply(lambda r: df2.loc[r['date_1']: r['date_2'], 'return'].mean(), axis=1)
这篇关于在选择 pandas 中的一部分数据时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文