【对比python】分组子集运算 | 润乾 -pg游戏官网登录入口

任务:计算出指定时间段内各种货物每天的库存状态

python

1 import pandas as pd
2 import numpy as np
3 starttime = '2015-01-01'
4 endtime = '2015-12-31'
5 stock_data = pd.read_csv('e:\\txt\\stocklog.csv',sep='\t')
6 stock_data['date']=pd.to_datetime(stock_data['date'])
7 stock_data = stock_data[(stock_data['date']>=starttime)&(stock_data['date']<=endtime)]
8 stock_data['enter']=stock_data['quantity'][stock_data['indicator']!='issue']
9 stock_data['issue']=stock_data['quantity'][stock_data['indicator']=='issue']
10 stock_g = stock_data[['stockid','date','enter','issue']].groupby(by=['stockid','date'],as_index=false).sum()
11 stock_gr = stock_g.groupby(by='stockid',as_index = false)
12 date_df = pd.dataframe(pd.date_range(starttime,endtime),columns=['date'])
13 stock_status_list = []
14 for index,group in stock_gr:
15
16     date_df['stockid']=group['stockid'].values[0]
17     stock_status = pd.merge(date_df,group,on=['stockid','date'],how='left')
18     stock_status = stock_status.sort_values(['stockid','date'])
19     stock_status['open']=0
20     stock_status['close']=0
21     stock_status['total']=0
22     stock_status = stock_status.fillna(0)
23     stock_value = stock_status[['stockid','date','open','enter','total','issue','close']].values
24     open = 0
25     for value in stock_value:
26         value[2] = open
27         value[4] = value[2] value[3]
28         value[6] = value[4] - value[5]
29         open = value[6]
30     stock = pd.dataframe(stock_value,columns = ['stockid','date','open','enter','total','issue','close'])
31     stock_status_list.append(stock)
32 stock_status = pd.concat(stock_status_list,ignore_index=true)
  print(stock_status)

集算器

  a b
1 =file("e:\\txt\\stocklog.csv").import@t()  
2 =a1.select(date>=date("2015-01-01") && date<=date("2015-12-31"))  
3 =a2.groups(stockid,date;
sum(if(indicator=="issue",quantity,0)):issue,
sum(if(indicator!="issue",quantity,0)):enter)
 
4 =periods(start,end)  
5 for a3.group(stockid) =a5.align(a4,date)
6   >b=c=0
7   =b5.new(a5.stockid:stockid,a4(#):date,c:open,enter,
(b=c enter):total,issue,
(c=b-issue):close)
8   >b7.run(enter=ifn(enter,0),issue=ifn(issue,0))
9   =@|b7

集算器9行代码完成python32行代码完成的任务,而且再阅读代码时,集算器也更好理解。

网站地图