teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

1

コード追加

2020/06/22 04:02

投稿

jeanbiego
jeanbiego

スコア3966

answer CHANGED
@@ -20,4 +20,39 @@
20
20
  blc.append(record)
21
21
  df["balance"] = pd.DataFrame(blc)
22
22
  df
23
+ ```
24
+
25
+ user_id別ver.
26
+
27
+ ```python3
28
+ import pandas as pd
29
+ import copy
30
+ dfa = pd.DataFrame({
31
+ 'action_id':['1', '2', '3', '4', '5', '6', '7', '8'],
32
+ 'user_id':['a', 'a', 'a', 'a', 'a', 'a', 'a', 'a'],
33
+ 'date':['2020-06-05', '2020-06-06', '2020-06-08', '2020-06-10', '2020-06-11', '2020-06-12', '2020-06-15', '2020-06-20'],
34
+ 'actoin_type':['get', 'purchase', 'purchase', 'purchase', 'get', 'purchase', 'get', 'purchase'],
35
+ 'point_get':['500', '0', '0', '0', '300', '0', '200', '0'],
36
+ 'point_use':['0', '300', '0', '500','0', '250', '0', '150']
37
+ })
38
+ dfb = pd.DataFrame({
39
+ 'action_id':['1', '2', '3', '4', '5', '6', '7', '8'],
40
+ 'user_id':['b', 'b', 'b', 'b', 'b', 'b', 'b', 'b'],
41
+ 'date':['2020-06-05', '2020-06-06', '2020-06-08', '2020-06-10', '2020-06-11', '2020-06-12', '2020-06-15', '2020-06-20'],
42
+ 'actoin_type':['get', 'purchase', 'purchase', 'purchase', 'get', 'purchase', 'get', 'purchase'],
43
+ 'point_get':['300', '0', '100', '0', '300', '0', '200', '0'],
44
+ 'point_use':['0', '300', '0', '500','0', '250', '0', '150']
45
+ })
46
+ df=pd.concat([dfa,dfb])
47
+ df = df.reset_index(drop=True)
48
+ blc = []
49
+ for user_id, group in df.groupby("user_id"):
50
+ record = 0
51
+ for gt,us in zip(group["point_get"],group["point_use"]):
52
+ record += int(gt) -int(us)
53
+ if record < 0:
54
+ record = 0
55
+ blc.append(record)
56
+ df["balance"] = pd.DataFrame(blc)
57
+ df
23
58
  ```