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

質問編集履歴

1

追加で試したコードです。エラーがでてしまいました。

2021/09/28 00:16

投稿

Shin_go
Shin_go

スコア20

title CHANGED
File without changes
body CHANGED
@@ -40,4 +40,40 @@
40
40
  person_cost
41
41
  ```
42
42
 
43
- ![イメージ説明](bb1107fc2c281bdbc86eb26cc9690501.png)
43
+ ![イメージ説明](bb1107fc2c281bdbc86eb26cc9690501.png)
44
+
45
+
46
+
47
+ ```python
48
+ #医療費データをユーザーごとに集計
49
+ person_cost1 = pd.pivot_table( cost1,index="person_number",values='cost',columns='nendo',aggfunc='sum').reset_index().fillna(0)
50
+ person_cost2 = pd.pivot_table( cost2,index="person_number",values='cost',columns='nendo',aggfunc='sum').reset_index().fillna(0)
51
+ person_cost3 = pd.pivot_table( cost3,index="person_number",values='cost',columns='nendo',aggfunc='sum').reset_index().fillna(0)
52
+ person_cost4 = pd.pivot_table( cost4,index="person_number",values='cost',columns='nendo',aggfunc='sum').reset_index().fillna(0)
53
+ person_cost5 = pd.pivot_table( cost5,index="person_number",values='cost',columns='nendo',aggfunc='sum').reset_index().fillna(0)
54
+
55
+ person_cost=pd.merge(person_cost1,person_cost2,left_on='person_number',right_on='person_number',how='inner')
56
+ person_cost=pd.merge(person_cost,person_cost3,left_on='person_number',right_on='person_number',how='inner')
57
+ person_cost=pd.merge(person_cost,person_cost4,left_on='person_number',right_on='person_number',how='inner')
58
+ person_cost=pd.merge(person_cost,person_cost5,left_on='person_number',right_on='person_number',how='inner')
59
+
60
+
61
+ person_cost.loc['Column_total']= person_cost.sum(numeric_only=True, axis=0)
62
+ # person_cost.loc[:,'total'] = person_cost.sum(numeric_only=True, axis=1)
63
+
64
+ #個人ごとの合計を算出・列を追加
65
+ person_cost["total"]=cost1["cost"]+cost2["cost"]+cost3["cost"]+cost4["cost"]+cost5["cost"]
66
+
67
+ #個人ごとの平均を算出・列を追加
68
+ person_cost["mean"]=person_cost["total"]/5
69
+
70
+ #個人ごとの前年増減率を算出・列を追加
71
+ person_cost["YonY_1"]=round((cost2["cost"]-cost1["cost"])/cost1["cost"]*100,1)
72
+ person_cost["YonY_2"]=round((cost3["cost"]-cost2["cost"])/cost2["cost"]*100,1)
73
+ person_cost["YonY_3"]=round((cost4["cost"]-cost3["cost"])/cost3["cost"]*100,1)
74
+ person_cost["YonY_4"]=round((cost5["cost"]-cost4["cost"])/cost4["cost"]*100,1)
75
+
76
+ person_cost[[1, 2, 3, 4, 5, 'total']] = person_cost[[1, 2, 3, 4, 5, 'total']].astype(np.int64)
77
+
78
+ person_cost
79
+ ```