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
|
# Pivot
df = pd.DataFrame({
"Type": ['Breakfast', 'Lunch', 'Dinner', 'Breakfast', 'Lunch', 'Dinner', 'Breakfast', 'Lunch', 'Dinner'],
"Month": [1, 1, 1, 2, 2, 2, 3, 3, 3],
"Cost": [50, 60, 100, 30, 70, 90, 40, 40, 40]
})
pivot = df.pivot(index="Month", columns="Type", values="Cost")
'''
Type Breakfast Dinner Lunch
Month
1 50 100 60
2 30 90 70
3 40 40 40
'''
pivot.sum(axis=0)
'''
Type
Breakfast 120
Dinner 230
Lunch 170
dtype: int64
'''
# Pivot Table
df = pd.DataFrame({
"A": ["foo", "foo", "foo", "foo", "foo","bar", "bar", "bar", "bar"],
"B": ["one", "one", "one", "two", "two", "one", "one", "two", "two"],
"C": ["small", "large", "large", "small", "small", "large", "small", "small", "large"],
"D": [1, 2, 2, 3, 3, 4, 5, 6, 7],
"E": [2, 4, 5, 5, 6, 6, 8, 9, 9]
})
pTable = df.pivot_table(index=['A', 'B'], columns=['C'], values='D', aggfunc=np.sum, fill_value=-1)
'''
C large small
A B
bar one 4 5
two 7 6
foo one 2 1
two -1 3
'''
|