首页 > 编程语言 >Python根据主播直播时间段判定订单销售额归属

Python根据主播直播时间段判定订单销售额归属

时间:2024-04-13 12:00:11浏览次数:12  
标签:Python Time datetime 直播 time data anchor 主播

写在前面:最近在群里看到一个这样的直播电商的场景觉得还是挺有趣的,于是就想用Python来实现。

需求描述:根据主播直播时间段结合销售订单的付款时间判断所属销售的归属

生成主播在线直播时间段数据

from datetime import datetime, timedelta
import random
import pandas as pd

def generate_live_data(start_time, live_duration, anchors, num_repeats=4):
    """
    生成直播数据。

    参数:
    start_time (datetime): 直播开始时间。
    live_duration (timedelta): 直播时长。
    anchors (list): 主播列表。
    num_repeats (int): 每个主播重复直播的次数,默认为 4。

    返回:
    DataFrame: 包含生成的直播数据的 DataFrame,每行包括开始时间、结束时间和主播。
    """
    live_data = []
    current_time = start_time
    for anchor in anchors:
        for _ in range(num_repeats):  # 每人直播指定次数
            end_time = current_time + live_duration  # 计算直播结束时间
            live_data.append((current_time, end_time, anchor))
            current_time = end_time

    # 将列表转换为 DataFrame
    df = pd.DataFrame(live_data, columns=["Start Time", "End Time", "Anchor"])
    return df

# 定义开始时间
start_time = datetime(2024, 4, 11, 0, 0)  # 2024年4月11日凌晨

# 定义直播时长
live_duration = timedelta(hours=3)  # 每人直播三小时

# 定义主播列表
anchors = ["Anchor 1", "Anchor 2", "Anchor 3", "Anchor 4"]

# 生成直播数据
live_data_df = generate_live_data(start_time, live_duration, anchors)

# 将数据写出到 Excel 文件
excel_file_path = "live_data.xlsx"
live_data_df.to_excel(excel_file_path, index=False)

主播数据展示

生成销售订单数据

import pandas as pd
from datetime import datetime, timedelta
import random

def generate_purchase_data(start_time, end_time, time_interval, customers, products):
    """
    生成模拟购买数据,并导出到 Excel 文件。

    参数:
    start_time (datetime): 数据开始时间。
    end_time (datetime): 数据结束时间。
    time_interval (timedelta): 时间间隔。
    customers (list): 模拟客户姓名列表。
    products (list): 模拟商品列表。

    返回:
    str: 导出的 Excel 文件路径。
    """
    # 生成时间列表
    time_list = []
    current_time = start_time
    while current_time < end_time:
        time_list.append(current_time)
        current_time += time_interval

    # 生成模拟购买数据
    purchase_data = []
    for time in time_list:
        for customer in customers:
            product = random.choice(products)  # 随机选择一个商品
            quantity = random.randint(1, 5)  # 随机生成购买数量
            purchase_data.append((time, customer, product, quantity))

    # 将购买数据转换为 DataFrame
    df = pd.DataFrame(purchase_data, columns=["Time", "Customer", "Product", "Quantity"])

    # 导出到 Excel 文件
    excel_file = "purchase_data.xlsx"
    df.to_excel(excel_file, index=False)

    return excel_file

# 定义开始时间和结束时间
start_time = datetime(2024, 4, 11, 0, 0)  # 2024年4月11日凌晨
end_time = datetime(2024, 4, 13, 0, 0)    # 2024年4月12日凌晨

# 定义时间间隔
time_interval = timedelta(minutes=30)  # 每隔半小时

# 定义模拟的客户姓名列表和商品列表
customers = ["Alice", "Bob", "Charlie", "David", "Emma"]
products = ["Product A", "Product B", "Product C", "Product D", "Product E"]

# 生成购买数据并导出到 Excel 文件
excel_file_path = generate_purchase_data(start_time, end_time, time_interval, customers, products)

print("数据已成功导出到 Excel 文件:", excel_file_path)

销售订单数据展示

根据销售数据匹配主播直播时间段并保存到Excel文件

有时候我们需要根据销售数据来匹配主播的直播时间段,以便进行更深入的分析。

1. 导入必要的模块

import pandas as pd
from datetime import datetime

2. 从Excel文件中读取销售数据和主播直播时间数据

# 从Excel文件中读取销售数据
sales_data = pd.read_excel("C:\\Users\\Administrator\\Desktop\\purchase_data.xlsx")

# 将时间列转换为datetime类型
sales_data['Time'] = pd.to_datetime(sales_data['Time'])

# 从Excel文件中读取主播直播时间数据
anchor_time_data = pd.read_excel("C:\\Users\\Administrator\\Desktop\\live_data.xlsx")

# 将时间列转换为datetime类型
anchor_time_data['Start Time'] = pd.to_datetime(anchor_time_data['Start Time'])
anchor_time_data['End Time'] = pd.to_datetime(anchor_time_data['End Time'])

3. 初始化结果列表并遍历销售数据

# 初始化一个空列表,用于存储结果
result = []

# 遍历销售数据,判断每笔销售属于哪个主播的直播时间段
for index, row in sales_data.iterrows():
    sale_time = row['Time']
    customer = row['Customer']
    product = row['Product']
    quantity = row['Quantity']

    # 判断销售时间在哪个主播的直播时间段内
    for _, anchor_row in anchor_time_data.iterrows():
        start_time = anchor_row['Start Time']
        end_time = anchor_row['End Time']
        anchor = anchor_row['Anchor']

        if start_time <= sale_time <= end_time:
            result.append((start_time, end_time, anchor,sale_time, customer, product, quantity))
            break

4. 将结果转换为DataFrame并保存到Excel文件

# 将结果转换为DataFrame
result_df = pd.DataFrame(result, columns=['Start Time', 'End Time', 'Anchor','sale_time', 'Customer', 'Product', 'Quantity'])

# 将结果保存到Excel文件
excel_file_path = "live_data2.xlsx"
result_df.to_excel(excel_file_path, index=False)

 5.完整代码

import pandas as pd
from datetime import datetime

# 从Excel文件中读取销售数据
sales_data = pd.read_excel("C:\\Users\\Administrator\\Desktop\\purchase_data.xlsx")

# 将时间列转换为datetime类型
sales_data['Time'] = pd.to_datetime(sales_data['Time'])

# 从Excel文件中读取主播直播时间数据
anchor_time_data = pd.read_excel("C:\\Users\\Administrator\\Desktop\\live_data.xlsx")

# 将时间列转换为datetime类型
anchor_time_data['Start Time'] = pd.to_datetime(anchor_time_data['Start Time'])
anchor_time_data['End Time'] = pd.to_datetime(anchor_time_data['End Time'])

# 初始化一个空列表,用于存储结果
result = []

# 遍历销售数据,判断每笔销售属于哪个主播的直播时间段
for index, row in sales_data.iterrows():
    sale_time = row['Time']
    customer = row['Customer']
    product = row['Product']
    quantity = row['Quantity']

    # 判断销售时间在哪个主播的直播时间段内
    for _, anchor_row in anchor_time_data.iterrows():
        start_time = anchor_row['Start Time']
        end_time = anchor_row['End Time']
        anchor = anchor_row['Anchor']

        if start_time <= sale_time <= end_time:
            result.append((start_time, end_time, anchor,sale_time, customer, product, quantity))
            break

# 将结果转换为DataFrame
result_df = pd.DataFrame(result, columns=['Start Time', 'End Time', 'Anchor','sale_time', 'Customer', 'Product', 'Quantity'])

# 打印结果
print(result_df)

excel_file_path = "live_data2.xlsx"
result_df.to_excel(excel_file_path, index=False)

 

 

标签:Python,Time,datetime,直播,time,data,anchor,主播
From: https://www.cnblogs.com/lcl-cn/p/18132664

相关文章

  • /usr/bin/env: "python": 没有那个文件或目录
    我电脑里面是Python3的解释器,不是Python的解释器,因此作如下操作1.首先查看Python3解释器的路径1whichpython3 2.我们将创建一个指向/usr/bin/python3的软链接,名为python。1sudoln-s/usr/bin/python3/usr/bin/pythonPythonUbuntu/usr/bin/env:python:没有那......
  • 视频直播源码,不同业务场景需选择不同方案去缓存数据
    视频直播源码,不同业务场景需选择不同方案去缓存数据在开发视频直播源码时,针对不同业务场景,我们应该选择不同的方案去缓存数据。本文就针对最常见的存储方案和场景做一些分类和介绍一些在Vue/React中的高阶用法,助力前端开发体验和应用的稳定性。前端缓存方案确定不同场......
  • Python量化交易系统实战--计算交易指标
     作者:麦克煎蛋  出处:https://www.cnblogs.com/mazhiyong/转载请保留这段声明,谢谢! 本节主要包括以下内容:1、计算涨跌幅使用shift函数计算涨跌幅defcalculate_change_pct(data):"""涨跌幅=(当期收盘价-前期收盘价)/前期收盘价:paramdata:datafram......
  • 在线直播系统源码,前后端大文件上传代码分析
    在线直播系统源码,前后端大文件上传代码分析前端代码:<template><div><[email protected]="hanldeClick"class="upload_container"><inputname="请上传文件"type="file"ref="uploadRef"......
  • HX711压力传感器+树莓派python驱动程序
    #-*-coding:utf-8-*-importRPi.GPIOasGPIOimporttime#VCC接1号针脚,GND接6号针脚,SCK接11号针脚,DT接13号针脚classHx711():defsetup(self):self.SCK=11#物理引脚第11号,时钟self.DT=13#物理引脚第13号,数据self.flag=1......
  • Python循环语句
    循环while循环i=0whilei<10:print(i)#输出0-9i+=1#Python中不支持自增和自减random随机数importrandom#导入含有随机数的库randomnum=random.randint(1,100)#创建一个变量num,将1-100中的随机数赋值给num注:Python中导入库(包)可以在代......
  • Python+FastJson漏洞批量检测实战
    #-*-coding:utf-8-*-importosimportsubprocess#指定要读取文件的目录directory='D:/gongju02/anq/FastJson/JsonExp-1.4.0'defjson_exp(text_path):"""指定要检测的接口文件目录"""try:#改变当前工作目录os.chdir(di......
  • Python量化交易系统实战--获取股票数据
     我们首先需要获取股票数据。代码IDE选择:PyCharm计算机环境:MacOS  一、获取股票数据的三种方式 二、获取股票数据这里选定的是使用JoinQuant平台提供的免费接口(有时间范围限制),简单整理如下。使用前需要先申请权限并初始化授权:fromjqdatasdkimport*auth('','......
  • 在python中实现二叉树
    二叉树设计定义节点类classNode:#修改初始化方法definit(self,value):self.value=value#节点值self.left=None#左子树self.right=None#右子树定二叉树类classBinaryTree:#修改初始化方法definit(self,root=None):self.root=root#根节点#定......
  • Python程序员Visual Studio Code指南5调试
    5调试当运行程序时终端输出错误时,可以参考编辑器中的"问题"面板来解决遇到的问题。不过,并非所有错误都会导致错误。可能出现的情况是,程序执行成功,但输出结果与预期不同。出现这种情况时,下一步就是找出程序中的错误。这个过程被称为调试。您可以尝试通过注释代码行(从而禁止代码......