Python Pandas 批量处理会员商品筛选 - 基于地理位置和限额
import pandas as pd
import math
for i in range(1, 32):
# 加载商品信息表和会员信息表
product_info = pd.read_excel('D:\pythonProject3\商品信息\商品打包.xlsx')
member_info = pd.read_excel('D:\pythonProject3\打包问题\会员信息.xlsx', sheet_name=f'会员信息{i}')
# 对商品信息表按照经纬度排序
product_info.sort_values(by=['新商品GPS经度', '新商品GPS纬度'], inplace=True)
# 初始化会员挑选到商品的数量
member_info['挑选商品数量'] = 0
# 遍历每个会员
for i in range(len(member_info)):
member = member_info.iloc[i]
# 获取会员的GPS经纬度
member_latitude = member['会员GPS纬度']
member_longitude = member['会员GPS经度']
# 获取会员的预订商品限额
limit = member['预订商品限额']
# 初始化商品数量和总距离
selected_quantity = 0
total_distance = 0
# 遍历每个商品
for j in range(len(product_info)):
product = product_info.iloc[j]
# 获取商品的GPS经纬度和打包数量
product_latitude = product['新商品GPS纬度']
product_longitude = product['新商品GPS经度']
quantity = product['打包数量']
# 计算商品与会员之间的距离
distance = math.sqrt(
(member_latitude - product_latitude) ** 2 + (member_longitude - product_longitude) ** 2)
# 判断商品与会员之间的距离是否满足要求
if distance <= 1:
# 判断挑选该商品是否会超过预订商品限额
if selected_quantity + quantity <= limit:
# 更新商品数量和总距离
selected_quantity += quantity
total_distance += distance
else:
break
# 更新会员挑选到商品的数量
member_info.at[i, '挑选商品数量'] = selected_quantity
# 输出每个会员挑选到商品的数量
print(member_info['挑选商品数量'])
# member_info.to_excel('D:\pythonProject3\打包问题\会员信息 - 副本.xlsx', index=False, columns=['会员编号', '会员GPS纬度', '会员GPS经度', '信誉值', '预订商品比例', '挑选商品数量'])
outfile = r'D:\pythonProject3\打包问题\会员信息 - 副本.xlsx'
with pd.ExcelWriter(outfile, mode='a', engine='openpyxl') as writer:
member_info.to_excel(writer, columns=['会员编号', '会员GPS纬度', '会员GPS经度', '信誉值', '预订商品比例',
'挑选商品数量'], sheet_name=f'会员信息{i}', index=False)
该代码使用 Python Pandas 库,根据会员的 GPS 坐标、商品的 GPS 坐标、预订商品限额,以及距离限制,自动筛选每个会员可以挑选的商品数量,并将结果写入 Excel 文件。
代码功能:
- 读取商品信息和会员信息文件。
- 对商品信息表按照经纬度排序。
- 遍历每个会员,根据其 GPS 坐标和预订商品限额,筛选符合条件的商品。
- 计算每个会员可以挑选的商品数量,并更新到会员信息表中。
- 将最终的会员信息写入 Excel 文件。
适用场景:
- 电商平台根据会员位置和商品位置,进行商品推荐和筛选。
- 物流配送系统根据用户地址和配送点位置,优化配送路线。
- 社交平台根据用户位置和兴趣点,推荐附近的朋友和活动。
代码说明:
product_info:商品信息表,包含商品的 GPS 经纬度和打包数量。member_info:会员信息表,包含会员的 GPS 经纬度、预订商品限额等信息。distance:商品与会员之间的距离,使用勾股定理计算。selected_quantity:当前会员已选商品的数量。limit:会员的预订商品限额。
优化建议:
- 使用
geopy库进行更加准确的地理距离计算。 - 添加错误处理机制,例如文件读取失败、数据格式错误等。
- 使用
multiprocessing或threading库提高代码执行效率。 - 可以使用
matplotlib库对数据进行可视化分析。
原文地址: https://www.cveoy.top/t/topic/fAvp 著作权归作者所有。请勿转载和采集!