我有下表:
df = pd.DataFrame(({'code':['A121','A121','A121','H812','H812','H812','Z198','Z198','Z198','S222','S222','S222'],
'mode':['stk','sup','cons','stk','sup','cons','stk','sup','cons','stk','sup','cons'],
datetime.date(year=2021,month=5,day=1):[4,2,np.nan,2,2,np.nan,6,np.nan,np.nan,np.nan,2,np.nan],
datetime.date(year=2021,month=5,day=2):[1,np.nan,np.nan,3,np.nan,np.nan,2,np.nan,np.nan,np.nan,np.nan,np.nan],
datetime.date(year=2021,month=5,day=3):[12,5,np.nan,13,5,np.nan,12,np.nan,np.nan,np.nan,5,np.nan],
datetime.date(year=2021,month=5,day=4):[np.nan,1,np.nan,np.nan,4,np.nan,np.nan,np.nan,np.nan,np.nan,7,np.nan]}))
df = df.set_index('mode')
我希望实现以下目标,我希望根据一些算术计算设置cons
所在的行:
cons
对应的日期和代码需要设置为以下计算prev_date stk - current_date stk + sup
我尝试了以下代码:
dates = list(df.columns)
dates.remove('code')
for date in dates:
prev_date = date - datetime.timedelta(days=1)
if(df.loc["stk"].get(prev_date,None) is not None):
opn_stk = df.loc["stk",prev_date].reset_index(drop=True)
cls_stk = df.loc["stk",date].reset_index(drop=True)
sup = df.loc["sup",date].fillna(0).reset_index(drop=True)
cons = opn_stk - cls_stk + sup
df.loc["cons",date] = cons
我没有收到任何错误,但是cons
值根本没有改变
我怀疑这可能是因为df.loc["cons",date]
是一个索引序列,而计算opn_stk - cls_stk + sup
是一个未索引序列。
你知道怎么解决这个问题吗
另外,我正在使用循环来计算这个,有没有其他更有效的向量化方法
预期产量
让我们试试groupby应用程序:
*假设列按日期按1天的间隔排序
尽管@Henry Ecker的回答非常优雅,但与我所做的相比,它的速度非常慢(慢了10倍多),因此我希望继续修复我的实现
我的实现按照Henry Ecker的建议进行了修复
df.loc["cons",date] = cons.to_numpy()
作为旁注: 我的实现运行在
0:00:00.053309 seconds
中的完整数据上(不是这个,我创建这个作为玩具示例),Henry Ecker的实现运行在0:00:00.568888 seconds
中,因此速度要慢10倍以上这可能是因为他在迭代代码,而我在迭代日期。在任何给定的时间点,我最多会有30个日期,但可能会有超过500个代码
相关问题 更多 >
编程相关推荐