Основной DataFrame, используемый в приведенном ниже коде
df
Date State Type Value
2010-01-01 AK NUC 10
2010-02-01 AK NUC 10
2010-03-01 AK NUC 10
2010-01-01 CO NUC 2
2010-02-01 CO NUC 2
2010-01-01 AK WND 20
2010-02-01 AK WND 21
Изменения, которые вы хотите добавить в основную, обратите внимание, что я заменил пробел на _
delta
Operating_Date Retirement_Date Type State Value
2010-02-01 2010-04-01 NUC AK 1
2011-02-01 2014-02-01 NUC AK 2
2011-03-01 2016-03-01 NUC AK 10
План атаки заключается вИспользуйте один столбец даты, чтобы сделать это, нам нужно объединить дату выхода на пенсию и дату операции в один столбец, мы присвоим значению отрицательное число, когда будем использовать дату выхода на пенсию, и оставим положительное значение для даты операции
#We first make a copy of the delta, we will call these cancellations and use the
#Retirement_Date and the value in negative
cx = delta.copy()
cx['Date']=cx['Retirement_Date']
cx.drop(['Operating_Date','Retirement_Date'],axis=1,inplace=True)
cx['Value'] *=-1
#In the original delta we assign operating date as the date value
delta['Date'] = delta['Operating_Date']
delta.drop(['Operating_Date','Retirement_Date'],axis=1,inplace=True)
#We then append the cancellations to the main delta frame and rename the values
#column to delta
delta = delta.append(cx)
delta.rename(columns={'Value':'Delta'},inplace=True)
Теперь у нас есть фрейм данных с одним столбцом даты, содержащим все положительные и отрицательные изменения, которые мы хотим отслеживать за дату
delta
Type State Delta Date
NUC AK 1 2010-02-01
NUC AK 2 2011-02-01
NUC AK 10 2011-03-01
NUC AK -1 2010-04-01
NUC AK -2 2014-02-01
NUC AK -10 2016-03-01
Теперь все, что нам нужно сделать, это добавить совокупное значение изменений восновной фрейм данных
#we start by merging the data frames, as the column names are the same and we want to merge on all of them we just specify that it's an outer join
df = df.merge(delta,how='outer')
#if there are any new dates in the delta that aren't in the main dataframe we want to bring forth our cumulative sum
#but first we need to make sure we sort by date so the cumulative sum works
df.sort_values(['Type','State','Date'],inplace=True)
df['Value'] = df.groupby(['State','Type'])['Value'].ffill()
#for the dates where we have no changes we fill with zeros
df['Delta'].fillna(0,inplace=True)
#we can now add the cumilative sum of the delta to the values column
df['Value'] +=df.groupby(['State','Type'])['Delta'].cumsum().astype(int)
#and lastly we can remove the delta column again and we're done
del df['Delta']
последний фрейм данных, который, как мы надеемся, является тем, к чему вы стремитесь
df
Date State Type Value
2010-01-01 AK NUC 10
2010-02-01 AK NUC 11
2010-03-01 AK NUC 11
2010-04-01 AK NUC 10
2011-02-01 AK NUC 12
2011-03-01 AK NUC 22
2014-02-01 AK NUC 20
2016-03-01 AK NUC 10
2010-01-01 CO NUC 2
2010-02-01 CO NUC 2
2010-01-01 AK WND 20
2010-02-01 AK WND 21