0
点赞
收藏
分享

微信扫一扫

# yyds干货盘点 # 盘点一个AI+Pandas实战业务需求

大家好,我是Python进阶者。

一、前言

前几天在Python最强王者交流群【Chloe】问了一个Pandas实战需求问题。问题如下:

大佬们, 我有个需求: 公司希望了解哪些商家最受新客户欢迎。您需要了解每个商家的订单数量和首次订单数量。首次订单是从客户的角度来看的,是客户下的第一个订单。换句话说,有多少顾客是他们第一次向该商家订购的?注:近期系统新增餐厅注册;但是,由于他们可能尚未收到任何订单,因此您的答案应排除尚未收到任何订单的餐厅。您的输出应包含商家名称、订单总数以及首次订单的数量。

她自己提供了数据和写的代码如下:

# yyds干货盘点 # 盘点一个AI+Pandas实战业务需求_AIGC

不过代码得到的结果不是自己想要的。

# yyds干货盘点 # 盘点一个AI+Pandas实战业务需求_AI+Python_02

二、实现过程

这里我使用【chatglm】给了一个思路:AI+Python助力需求问题,下面一起来看看吧。

# yyds干货盘点 # 盘点一个AI+Pandas实战业务需求_AI+Python_03

可以看到我成功的把数据喂给了【chatglm】,它也顺利地收到了。接下来,我只需要把粉丝的需求提交给它,它就可以帮忙处理了。

# yyds干货盘点 # 盘点一个AI+Pandas实战业务需求_AI应用_04

可以看到【chatglm】已经给我们处理了,并且生成了代码,这里贴出来给大家。

import pandas as pd

# Load the Excel file
df = pd.read_excel("./data.xlsx")

# Display the first few rows of the dataframe to understand its structure
# df.head()
# Sort the dataframe by customer_id and order_timestamp to get the first order for each customer
df_sorted = df.sort_values(by=['customer_id', 'order_timestamp'])

# Get the first order for each customer
df_first_orders = df_sorted.drop_duplicates(subset='customer_id', keep='first')

# Group by merchant_id and calculate the total orders and first orders for each merchant
merchant_stats = df.groupby('merchant_id').agg(
    total_orders=pd.NamedAgg(column='id_x', aggfunc='count'),
    total_customers=pd.NamedAgg(column='customer_id', aggfunc='nunique')
).reset_index()

# Group by merchant_id for first orders and calculate the number of first orders for each merchant
first_order_stats = df_first_orders.groupby('merchant_id').agg(
    first_orders=pd.NamedAgg(column='id_x', aggfunc='count')
).reset_index()

# Merge the two dataframes to get the final result
result = pd.merge(merchant_stats, first_order_stats, notallow='merchant_id')

# Merge with the merchant names
result = pd.merge(result, df[['id_y', 'name']].drop_duplicates(), left_notallow='merchant_id', right_notallow='id_y').drop('id_y', axis=1)

print(result.head())

下图是【chatglm】给的答案。

# yyds干货盘点 # 盘点一个AI+Pandas实战业务需求_AI+Python_05

代码生成完之后,在本地也是可以跑通的,如下图所示。

# yyds干货盘点 # 盘点一个AI+Pandas实战业务需求_Python_06

顺利地解决了粉丝的问题。

如果你也有类似这种Python相关的小问题,欢迎随时来交流群学习交流哦,有问必答!

通过这个粉丝需求问答,我们确切的感受到了AI助力Python实战需求的能力了,我最近也是一直在接触AIGC,从最开始的ChatGPT到最近火爆出圈的Sora,也建立了自己的AIGC分享群,目前也带动了500以上的AIGC爱好者一起学习,群里每周都会分享AIGC相关的内容,从认识AIGC,到使用AIGC,再到利用AIGC变现,我会带大家一起进军AIGC时代。大家可以在后台加我v,我拉你们进入AIGC学习群!

三、总结

大家好,我是Python进阶者。这篇文章主要盘点了一个AI+Python解决实战需求的问题,文中针对该问题,给出了具体的解析和代码实现,帮助粉丝顺利解决了问题。

最后感谢粉丝【Chloe】提出的问题,感谢【chatglm】给出的思路,感谢【莫生气】等人参与学习交流。

【提问补充】温馨提示,大家在群里提问的时候。可以注意下面几点:如果涉及到大文件数据,可以数据脱敏后,发点demo数据来(小文件的意思),然后贴点代码(可以复制的那种),记得发报错截图(截全)。代码不多的话,直接发代码文字即可,代码超过50行这样的话,发个.py文件就行。

# yyds干货盘点 # 盘点一个AI+Pandas实战业务需求_Python_07

举报

相关推荐

0 条评论