今
日
鸡
汤
君歌杨叛儿,妾劝新丰酒。
大家好,我是Python进阶者。
一、前言
前几天在Python最强王者交流群【Chloe】问了一个Pandas实战需求问题。问题如下:
大佬们, 我有个需求: 公司希望了解哪些商家最受新客户欢迎。您需要了解每个商家的订单数量和首次订单数量。首次订单是从客户的角度来看的,是客户下的第一个订单。换句话说,有多少顾客是他们第一次向该商家订购的?注:近期系统新增餐厅注册;但是,由于他们可能尚未收到任何订单,因此您的答案应排除尚未收到任何订单的餐厅。您的输出应包含商家名称、订单总数以及首次订单的数量。
她自己提供了数据和写的代码如下:
不过代码得到的结果不是自己想要的。
二、实现过程
这里我使用【chatglm】给了一个思路:AI+Python助力需求问题,下面一起来看看吧。
可以看到我成功的把数据喂给了【chatglm】,它也顺利地收到了。接下来,我只需要把粉丝的需求提交给它,它就可以帮忙处理了。
可以看到【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, on='merchant_id')
# Merge with the merchant names
result = pd.merge(result, df[['id_y', 'name']].drop_duplicates(), left_on='merchant_id', right_on='id_y').drop('id_y', axis=1)
print(result.head())
下图是【chatglm】给的答案。
代码生成完之后,在本地也是可以跑通的,如下图所示。
顺利地解决了粉丝的问题。
通过这个粉丝需求问答,我们确切的感受到了AI助力Python实战需求的能力了,我最近也是一直在接触AIGC,从最开始的ChatGPT到最近火爆出圈的Sora,也建立了自己的AIGC分享群,目前也带动了500以上的AIGC爱好者一起学习,群里每周都会分享AIGC相关的内容,从认识AIGC,到使用AIGC,再到利用AIGC变现,我会带大家一起进军AIGC时代。大家可以在后台加我v,我拉你们进入AIGC学习群!
三、总结
大家好,我是Python进阶者。这篇文章主要盘点了一个Python库安装的问题,文中针对该问题,给出了具体的解析和代码实现,帮助粉丝顺利解决了问题。
领取专属 10元无门槛券
私享最新 技术干货