我想知道如何使用Pandas在excel中展开几行带有日期范围的数据。下面是我想每隔7天扩展的两个记录。你知道吗
下面是我期望看到的输出。如果没有足够的7天,那么我仍然想要一个显示剩余天数的行。你知道吗
下面是我起草的代码。对熊猫的使用还很陌生,所以我不确定我在这里使用的方法是否正确。如果有人能帮忙太好了!你知道吗
df = pd.read_excel(path_link + input_file_name)
time_series = pd.DataFrame({
'Product': df.Product,
'Date':pd.date_range(df.Start_Date, df.End_Date)
})
编辑
非常感谢下面的每个人的回应!我从你的回答中学到了很多。下面是答案。用datanoveler作为公认的答案。你知道吗
#Data Frame
data = [
['Apple', '3/1/2019', '4/1/2019'],
['Pear', '2/5/2019', '3/4/2019' ]
]
df = pd.DataFrame(data, columns=['Product', 'Start_Date', 'End_Date'])
#Change data type for dates
df['Start_Date'] = pd.to_datetime(df['Start_Date'])
df['End_Date'] = pd.to_datetime(df['End_Date'])
#Un-pivot table and expands product's calendar dates for the start date
df2 = pd.melt(df, id_vars='Product').set_index('value')\
.groupby('Product').resample('8D').sum().drop(['variable','Product'],axis=1)\
.reset_index()
#Creates end date column
df2['end_date'] = df2['value'] + pd.DateOffset(days=7)
#Returns the index of the last product's end date; row's 3 and 7
idx = df2.drop_duplicates(subset='Product',keep='last').index
#Replace df2's row's 3 and 7 with the end date found in the original df
df2.loc[idx,'end_date'] = df2['Product'].map(df.set_index('Product')['End_Date'])
print(df2)
IIUC,一个想法是
resample
使用melt
将开始和结束日期设为一列,并使用pd.DateOffset
分配天数,我们仍然需要处理每个产品的最大结束日期,我们可以通过使用.drop_duplicates
按组查找最后一个产品索引,通过简单的映射和.loc
分配来完成使用
df['your_date_col'] = pd.to_datetime(df['your_date_col'])
确保开始和结束日期都是正确的日期时间此答案还将处理每个产品的最大结束日期:
相关问题 更多 >
编程相关推荐