现有奶茶店数据,有下单时间,时间跨度为5个月,奶茶开始制作时间,奶茶制作完成时间,一单中的杯量,门店编号,需要填充每个门店当天的开始制作时间和制作完成时间的缺失值,用缺失值前方不为空的时间填充,写出Python循环代码
时间: 2024-03-27 21:40:48 浏览: 9
假设数据已经存在一个名为 `data` 的 DataFrame 中,门店编号存储在 `store_id` 列中,下单时间存储在 `order_time` 列中,开始制作时间存储在 `start_time` 列中,制作完成时间存储在 `finish_time` 列中,杯量存储在 `cup_num` 列中。可以按照以下方式编写循环代码:
```python
# 导入 pandas 库
import pandas as pd
# 将下单时间转换为日期格式
data['order_time'] = pd.to_datetime(data['order_time'])
# 按门店编号和下单时间排序
data = data.sort_values(['store_id', 'order_time'])
# 循环遍历每个门店编号
for store in data['store_id'].unique():
# 获取该门店的所有订单数据
store_data = data[data['store_id'] == store]
# 循环遍历每一天的数据
for date in store_data['order_time'].dt.date.unique():
# 获取该门店该天的数据
day_data = store_data[store_data['order_time'].dt.date == date]
# 填充开始制作时间的缺失值
day_data['start_time'] = day_data['start_time'].fillna(method='ffill')
# 填充制作完成时间的缺失值
day_data['finish_time'] = day_data['finish_time'].fillna(method='ffill')
# 将填充后的数据保存回原来的 DataFrame 中
data.loc[day_data.index, ['start_time', 'finish_time']] = day_data[['start_time', 'finish_time']]
```
该代码会循环遍历每个门店,然后循环遍历该门店每一天的数据。对于每一天的数据,将开始制作时间和制作完成时间的缺失值填充为前方不为空的时间。最后,将填充后的数据保存回原来的 DataFrame 中。