Python:基于一列中日期值之间的差异创建新行
我正试图根据第一条记录和第二条记录之间的差异,以及从第二条记录到第三条记录、每个Id等创建新记录。 pandas.diff()和pandas.shift()除了告诉我第一张和第二张唱片之间的总天数差异等之外,没有做到这一点 因为我的数据集中没有结束日期,所以在这里发布的解决方案不起作用 假设以下数据集:Python:基于一列中日期值之间的差异创建新行,python,pandas,date,datetime,Python,Pandas,Date,Datetime,我正试图根据第一条记录和第二条记录之间的差异,以及从第二条记录到第三条记录、每个Id等创建新记录。 pandas.diff()和pandas.shift()除了告诉我第一张和第二张唱片之间的总天数差异等之外,没有做到这一点 因为我的数据集中没有结束日期,所以在这里发布的解决方案不起作用 假设以下数据集: df1=pd.DataFrame(columns=['Id','Code','Date']) Ids=[1,1,1,2,2,2,2,3,3] Codes=[8,9,11,5,6,7,8,7,8]
df1=pd.DataFrame(columns=['Id','Code','Date'])
Ids=[1,1,1,2,2,2,2,3,3]
Codes=[8,9,11,5,6,7,8,7,8]
Dates=['2020-07-02','2020-06-16','2020-04-07',
'2020-02-19','2020-03-18','2020-05-02','2020-07-02',
'2020-05-19','2020-03-24']
df1.Id=Ids
df1.Code=Codes
df1.Date=Dates
我希望达到的结果是:
Id Code Date
1 8 2020-07-02
1 9 2020-06-16
1 11 2020-05-01
1 11 2020-04-07
2 5 2020-02-19
2 6 2020-03-18
2 7 2020-04-01
2 7 2020-05-02
2 8 2020-06-01
2 8 2020-07-02
3 7 2020-05-19
3 8 2020-04-01
3 11 2020-03-24
正如您所看到的,对于日期和代码之间的每个缺失日期,都会生成一个新记录,指定两个记录之间的月份,并且在这个新记录中,代码的副本是从其以前的记录中生成的。我怀疑下面的方法是否最佳,但它是有效的
df = pd.DataFrame(columns=['Id','Code','Date'])
for _, df_temp in df1.groupby(by=['Id'], axis=0):
df_temp = df_temp.sort_values(by=['Date']).reset_index(drop=True)
# impute values
dates = df_temp['Date']
for i in range(df_temp.shape[0] - 1):
date_range = [d.strftime('%Y-%m-%d') for d in pd.date_range(dates.loc[i], dates.loc[i+1], freq='M')]
new_rows = pd.DataFrame(columns=['Id','Code','Date'])
new_rows['Date'] = date_range
new_rows['Id'] = df_temp.loc[i, 'Id']
new_rows['Code'] = df_temp.loc[i, 'Code']
df = pd.concat([df, new_rows])
# take care of the last entry
df.loc[df.shape[0]] = df_temp.loc[df_temp.shape[0] - 1]
df = pd.DataFrame(columns=['Id','Code','Date'])
for _, df_temp in df1.groupby(by=['Id'], axis=0):
df_temp = df_temp.sort_values(by=['Date']).reset_index(drop=True)
# impute values
dates = df_temp['Date']
for i in range(df_temp.shape[0] - 1):
date_range = [d.strftime('%Y-%m-%d') for d in pd.date_range(dates.loc[i], dates.loc[i+1], freq='M')]
new_rows = pd.DataFrame(columns=['Id','Code','Date'])
new_rows['Date'] = date_range
new_rows['Id'] = df_temp.loc[i, 'Id']
new_rows['Code'] = df_temp.loc[i, 'Code']
df = pd.concat([df, new_rows])
# take care of the last entry
df.loc[df.shape[0]] = df_temp.loc[df_temp.shape[0] - 1]