我有一些价格数据(比如来自yahoo finance)以每日粒度datetime变量作为索引,让我们称之为df,并将微软收盘价作为值变量。要获得月平均收盘价,我显然可以做以下两种操作之一:
import yfinance as yf
import pandas as pd
df = yf.download("CMG", start="2012-01-01",end="2020-01-01" )
dfm = df.resample("M").mean()
dfm2 = df.groupby(df.index.to_period("M")).mean()
对我来说,它们看起来非常相似,唯一不同的是,在重新采样时,新的日期时间索引是月底,groupby To_期间的索引是yyyy-mm
现在,我想在df中添加一个列,其粒度为每日收盘价与月平均值的偏差。因此,2020年1月1日-平均值(2020年1月20日),2020年1月2日-平均值(2020年1月20日),2020年2月1日-平均值(2020年2月20日)
因为dfm和df有不同的索引,我不能只做df-dfm
我唯一能想到的就是通过df循环,在dfm上放置一个计数器,并在循环中放置一个if语句,这是一种非常c类型的方法,但不是非常pythonic的。我猜它看起来会像这样(但这不起作用):
counter = 0
df["dailyminusmonthly"] =""
for i in df:
if i.index <= dfm[counter].index:
i.dailyminusmonthly = i.close - dfm.close[counter]
else:
counter = counter +1
i.dailyminusmonthly = i.close - dfm.close[counter]
您可以将
DatetimeIndex
转换为月周期,因此可以减去dfm2
,只有这样才有必要转换为numpy数组,因为减去的Series
的索引与原始df
的索引不同,以防止满NaN
列:另一个更简单的解决方案是使用^{} 与原始索引相同:
相关问题 更多 >
编程相关推荐