1 回答
TA贡献1890条经验 获得超9个赞
这是我将坚持的当前解决方案,以便它可能对其他人有用:
fig, ax = plt.subplots()
# set up df
inputData = pd.DataFrame(np.random.randint(100, size=(100, 5)), columns=['timestamp','var2','var3','var4','var5'])
inputData['timestamp'][:]=pd.date_range('2020-may-01','2020-aug-08')
inputData['var2']=np.arange(0,100,1)
inputData['var2'][0:3]=49
inputData['var4']=np.arange(0,200,2)
inputData['var2'][0:3]=np.nan
# set constants and settings
dispFactor=20
timeseries_plots=['var2','var4']
resetDates=['2020-05-05','2020-05-20', '2020-08-04']
offsetFactor = dispFactor
#begin
fig, ax=plt.subplots()
for ii,var in enumerate(timeseries_plots):
offsetRef = np.zeros(inputData[var].size)
for tt,ttdate in enumerate(resetDates):
if tt==0:
if inputData[var].loc[inputData['timestamp']==ttdate].isna().bool(): #if date is nan
print('a',inputData[var].loc[~inputData[var].isnull()].iloc[0],inputData[var].bfill().loc[inputData['timestamp']==ttdate])
offsetRef[(inputData['timestamp']<ttdate)]= inputData[var].loc[~inputData[var].isnull()].iloc[0]
offsetRef[(inputData['timestamp']>=ttdate)]=inputData[var].bfill().loc[inputData['timestamp']==ttdate]
else:
print('b',inputData[var].loc[~inputData[var].isnull()].iloc[0],inputData[var].loc[inputData['timestamp']==ttdate])
offsetRef[(inputData['timestamp']<ttdate)]= inputData[var].loc[~inputData[var].isnull()].iloc[0]
offsetRef[(inputData['timestamp']>=ttdate)]= inputData[var].loc[inputData['timestamp']==ttdate]
else:
if inputData[var].loc[inputData['timestamp']==ttdate].isna().bool(): #if date is nan
print('c')
offsetRef[ inputData['timestamp'] >=resetDates[tt]] = inputData[var].bfill().loc[inputData['timestamp']==ttdate]
else:
print('d',inputData[var].loc[inputData['timestamp']==ttdate])
offsetRef[ inputData['timestamp'] >=resetDates[tt]] = inputData[var].loc[inputData['timestamp']==ttdate]
print(offsetRef)
ax.plot(inputData['timestamp'], offsetFactor*(len(timeseries_plots)-ii-1)+inputData[var]-offsetRef)
plt.show()
这会将所选位置的偏移量“重置”为 20,resetDates以生成下图:
在任何一种情况下,我可能都不需要 nan 数据的 if 逻辑捕获(并且只依赖.bfill()
)来工作 - 但这让我觉得它更安全。我将在改进解决方案时进行编辑。
添加回答
举报