-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstats_by_group.py
More file actions
38 lines (29 loc) · 1.23 KB
/
stats_by_group.py
File metadata and controls
38 lines (29 loc) · 1.23 KB
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
# We'll group by a given column and calculate statistics for
# each group
#
# Reference:
# https://datascienceparichay.com/article/pandas-groupby-median/
import pandas as pd
if __name__ == "__main__":
df = pd.DataFrame({
'Address': ['123 Main Street', '456 Centerline Road', '323 Arden Way', '5000 Smith Lane', '200 Darling Way', '1920 Cesna Blvd'],
'ZipCode': ['95431', '95630', '95630', '95431', '95630', '95431'],
'SalePrice': [425000, 376000, 571432, 498321, 387499, 430060]
})
print('\nHere is the data frame we are using')
print(df)
print('\nA data frame can be grouped by one or more columns')
df_groups = df.groupby('ZipCode')
print('Then aggregate functions can be run on a column for each group')
median_by_zip = df_groups ['SalePrice'].median()
average_by_zip = df_groups ['SalePrice'].mean()
min_by_zip = df_groups ['SalePrice'].min()
max_by_zip = df_groups ['SalePrice'].max()
print('\nHere is the median of each zip code')
print(median_by_zip)
print('\nHere is the average of each zip code')
print(average_by_zip)
print('\nHere is the min of each zip code')
print(min_by_zip)
print('\nHere is the max of each zip code')
print(max_by_zip)