Pandas处理CSV数据实现每小时洗衣机、烘干机分类使用量统计
实现方案
核心修改分为两处:一是在分组聚合逻辑中新增洗衣机、烘干机的分类统计,二是调整数据库插入语句适配新增字段,修改后完整可运行代码如下:
for i in range(1): # 可自行替换为 len(csvList) 处理全量文件 df = wr.s3.read_csv(path=[f's3://{csvList[i].bucket_name}/{csvList[i].key}']) df['Timestamp'] = pd.to_datetime(df['Timestamp']) # 分组聚合新增分类统计字段 df = df.groupby(df['Timestamp'].dt.floor('h')).agg( machines_used_per_hour=('Machine Name', 'count'), revenue_per_hour=('Total Revenue', 'sum'), # 统计洗衣机数量:匹配前缀为Washer的记录数 washers_per_hour=('Machine Name', lambda x: x.str.startswith('Washer').sum()), # 统计烘干机数量:匹配前缀为Dryer的记录数 dryers_per_hour=('Machine Name', lambda x: x.str.startswith('Dryer').sum()) ).reset_index() for j in df.iterrows(): # 插入语句新增两个统计字段 dbInsert = """INSERT INTO `store-machine-use`(store_id, timestamp, machines_used_per_hour, revenue_per_hour, washers_per_hour, dryers_per_hour, notes) VALUES (%s, %s, %s, %s, %s, %s, %s)""" values = ( int(storeNumberList[i]), str(j[1]['Timestamp']), int(j[1]['machines_used_per_hour']), int(j[1]['revenue_per_hour']), int(j[1]['washers_per_hour']), int(j[1]['dryers_per_hour']), '' ) cursor.execute(dbInsert, values) cnx.commit()
补充说明
- 统计逻辑使用
startswith匹配前缀,完全适配你给出的Dryer #数字/Washer #数字命名规则,比模糊匹配准确率更高 - 原有的总机器使用量、总营收统计逻辑完全保留,和新增的分类统计数据口径一致
- 若存在不符合命名规则的异常
Machine Name值,可在lambda中新增过滤逻辑避免统计错误
内容的提问来源于stack exchange,提问作者Kozer H
相关产品推荐
相关产品推荐

