■ pivot_table 함수에서 values/index/columns/aggfunc 인자를 사용해 피벗 테이블의 데이터를 만드는 방법을 보여준다.
▶ main.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 |
import pandas as pd import numpy as np dataFrame1 = pd.DataFrame( { "x" : np.random.uniform(1.0, 168.0, 12), "y" : np.random.uniform(7.0, 334.0, 12), "z" : np.random.uniform(1.7, 20.7, 12), "month" : [5, 6, 7] * 4, "week" : [1, 2] * 6, } ) print(dataFrame1) print() """ x y z month week 0 51.147907 186.453553 18.048592 5 1 1 17.414609 134.206940 18.168186 6 2 2 125.479678 275.452230 4.875730 7 1 3 163.957947 230.605326 4.792094 5 2 4 82.406862 264.809601 11.619394 6 1 5 72.015022 216.739788 8.978817 7 2 6 130.329259 178.444185 16.741323 5 1 7 48.271124 92.696412 17.645448 6 2 8 76.477016 120.586115 10.668580 7 1 9 114.988345 18.068705 12.941800 5 2 10 42.186119 124.941915 20.037603 6 1 11 17.708408 331.049473 19.871238 7 2 """ dataFrame2 = pd.melt(dataFrame1, id_vars = ["month", "week"]) print(dataFrame2) """ month week variable value 0 5 1 x 51.147907 1 6 2 x 17.414609 2 7 1 x 125.479678 3 5 2 x 163.957947 4 6 1 x 82.406862 5 7 2 x 72.015022 6 5 1 x 130.329259 7 6 2 x 48.271124 8 7 1 x 76.477016 9 5 2 x 114.988345 10 6 1 x 42.186119 11 7 2 x 17.708408 12 5 1 y 186.453553 13 6 2 y 134.206940 14 7 1 y 275.452230 15 5 2 y 230.605326 16 6 1 y 264.809601 17 7 2 y 216.739788 18 5 1 y 178.444185 19 6 2 y 92.696412 20 7 1 y 120.586115 21 5 2 y 18.068705 22 6 1 y 124.941915 23 7 2 y 331.049473 24 5 1 z 18.048592 25 6 2 z 18.168186 26 7 1 z 4.875730 27 5 2 z 4.792094 28 6 1 z 11.619394 29 7 2 z 8.978817 30 5 1 z 16.741323 31 6 2 z 17.645448 32 7 1 z 10.668580 33 5 2 z 12.941800 34 6 1 z 20.037603 35 7 2 z 19.871238 """ print() dataFrame3 = pd.pivot_table( dataFrame2, values = "value", index = ["variable", "week"], columns = ["month"], aggfunc = "mean", ) print(dataFrame3) """ month 5 6 7 variable week x 1 90.738583 62.296490 100.978347 2 139.473146 32.842867 44.861715 y 1 182.448869 194.875758 198.019173 2 124.337015 113.451676 273.894630 z 1 17.394958 15.828498 7.772155 2 8.866947 17.906817 14.425027 """ |
▶ requirements.txt
1 2 3 4 5 6 7 8 |
numpy==2.1.2 pandas==2.2.3 python-dateutil==2.9.0.post0 pytz==2024.2 six==1.16.0 tzdata==2024.2 |
※ pip install pandas 명령을 실행했다.