大家好,我是皮皮。
一、前言
前几天在Python最强王者交流群【Chloe】问了一道Pandas
处理的问题,如下图所示。
原始数据如下:
代码语言:javascript复制df = pd.DataFrame({
'ord_no':[70001,70009,70002,70004,70007,70005,70008,70010,70003,70012,70011,70013],
'purch_amt':[150.5, 270.65, 65.26, 110.5, 948.5, 2400.6, 5760, 1983.43, 2480.4, 250.45, 75.29, 3045.6],
'ord_date': ['05-10-2012','09-10-2012','05-10-2012','08-17-2012','10-09-2012','07-27-2012','10-09-2012','10-10-2012','10-10-2012','06-17-2012','07-08-2012','04-25-2012'],
'customer_id':['C3001','C3001','D3005','D3001','C3005','D3001','C3005','D3001','D3005','C3001','D3005','D3005'],
'salesman_id': [5002,5005,5001,5003,5002,5001,5001,5006,5003,5002,5007,5001]})
def f(x):
return (x[0]=='C').sum()
df.groupby('salesman_id').agg({'customer_id':[('customer_id_C',f),('customer_id_list',lambda x:','.join(x)),('purc',lambda x:x.max()-x.min())]})
题目的要求是:
代码语言:javascript复制要求就是: calculate the number of customers starting with 'C',
# the list of all products and the difference of maximum purchase amount and minimum purchase amount.
预期的结果如下图所示:
二、实现过程
这个是聚类求和的问题,这里【月神】给出一个可行的代码,大家后面遇到了,可以对应的修改下,事半功倍,代码如下所示:
代码语言:javascript复制# 要求就是: calculate the number of customers starting with 'C',
# the list of all products and the difference of maximum purchase amount and minimum purchase amount.
import pandas as pd
df = pd.DataFrame({
'ord_no': [70001, 70009, 70002, 70004, 70007, 70005, 70008, 70010, 70003, 70012, 70011, 70013],
'purch_amt': [150.5, 270.65, 65.26, 110.5, 948.5, 2400.6, 5760, 1983.43, 2480.4, 250.45, 75.29, 3045.6],
'ord_date': ['05-10-2012', '09-10-2012', '05-10-2012', '08-17-2012', '10-09-2012', '07-27-2012', '10-09-2012',
'10-10-2012', '10-10-2012', '06-17-2012', '07-08-2012', '04-25-2012'],
'customer_id': ['C3001', 'C3001', 'D3005', 'D3001', 'C3005', 'D3001', 'C3005', 'D3001', 'D3005', 'C3001', 'D3005',
'D3005'],
'salesman_id': [5002, 5005, 5001, 5003, 5002, 5001, 5001, 5006, 5003, 5002, 5007, 5001]})
result = df.groupby('salesman_id').agg({'customer_id': [('customer_id_start_C', lambda x: (x.str[0] == 'C').sum()),
('customer_id_list', lambda x: ', '.join(x))],
'purch_amt': [('purchase_amt_app', lambda x: x.max() - x.min())]})
print(result)
运行之后,结果就是想要的了。
完美的解决了粉丝的问题!关于索引取值,还有其他的一个方法,如下所示。
三、总结
大家好,我是皮皮。这篇文章主要盘点了一道使用Pandas
处理数据的问题,文中针对该问题给出了具体的解析和代码实现,帮助粉丝顺利解决了问题。
最后感谢粉丝【Chloe】提问,感谢【月神】给出的思路和代码解析,感谢【dcpeng】、【冯诚】等人参与学习交流。