forked from AllenDowney/ThinkStats2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcumulative.py
More file actions
234 lines (174 loc) · 6.11 KB
/
cumulative.py
File metadata and controls
234 lines (174 loc) · 6.11 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
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
"""This file contains code used in "Think Stats",
by Allen B. Downey, available from greenteapress.com
Copyright 2010 Allen B. Downey
License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html
"""
from __future__ import print_function, division
import numpy as np
import nsfg
import first
import thinkstats2
import thinkplot
def PercentileRank(scores, your_score):
"""Computes the percentile rank relative to a sample of scores."""
count = 0
for score in scores:
if score <= your_score:
count += 1
percentile_rank = 100.0 * count / len(scores)
return percentile_rank
scores = [55, 66, 77, 88, 99]
your_score = 88
print('score, percentile rank')
for score in scores:
print(score, PercentileRank(scores, score))
print()
def Percentile(scores, percentile_rank):
"""Computes the value that corresponds to a given percentile rank. """
scores.sort()
for score in scores:
if PercentileRank(scores, score) >= percentile_rank:
return score
def Percentile2(scores, percentile_rank):
"""Computes the value that corresponds to a given percentile rank.
Slightly more efficient.
"""
scores.sort()
index = percentile_rank * (len(scores)-1) // 100
return scores[index]
print('prank, score, score')
for percentile_rank in [0, 20, 25, 40, 50, 60, 75, 80, 100]:
print(percentile_rank,
Percentile(scores, percentile_rank),
Percentile2(scores, percentile_rank))
def EvalCdf(sample, x):
"""Computes CDF(x) in a sample.
sample: sequence
x: value
returns: cumulative probability
"""
count = 0.0
for value in sample:
if value <= x:
count += 1.0
prob = count / len(sample)
return prob
sample = [1, 2, 2, 3, 5]
print('x', 'CDF(x)')
for x in range(0, 7):
print(x, EvalCdf(sample, x))
def PositionToPercentile(position, field_size):
"""Converts from position in the field to percentile.
position: int
field_size: int
"""
beat = field_size - position + 1
percentile = 100.0 * beat / field_size
return percentile
def PercentileToPosition(percentile, field_size):
"""Converts from percentile to hypothetical position in the field.
percentile: 0-100
field_size: int
"""
beat = percentile * field_size / 100.0
position = field_size - beat + 1
return position
# my time 42:44
print('Percentile rank in field', PositionToPercentile(97, 1633))
print('Percentile rank in age group', PositionToPercentile(26, 256))
percentile = PositionToPercentile(26, 256)
print('Equivalent position in M50-59', PercentileToPosition(percentile, 171))
# 17th place = 46:05
print('Equivalent position in F20-29', PercentileToPosition(percentile, 448))
# 48:28
def MakeExample():
"""Makes a simple example CDF."""
t = [2, 1, 3, 2, 5]
cdf = thinkstats2.Cdf(t)
thinkplot.Clf()
thinkplot.Cdf(cdf)
thinkplot.Save(root='cumulative_example_cdf',
xlabel='x',
ylabel='CDF',
axis=[0, 6, 0, 1],
legend=False)
def MakeFigures(live, firsts, others):
"""Creates several figures for the book.
live: DataFrame
firsts: DataFrame
others: DataFrame
"""
first_wgt = firsts.totalwgt_lb
first_wgt_dropna = first_wgt.dropna()
print('Firsts', len(first_wgt), len(first_wgt_dropna))
#assert len(first_wgt_dropna) == 4381
other_wgt = others.totalwgt_lb
other_wgt_dropna = other_wgt.dropna()
print('Others', len(other_wgt), len(other_wgt_dropna))
#assert len(other_wgt_dropna) == 4706
first_pmf = thinkstats2.Pmf(first_wgt_dropna, label='first')
other_pmf = thinkstats2.Pmf(other_wgt_dropna, label='other')
width = 0.4 / 16
# plot PMFs of birth weights for first babies and others
thinkplot.PrePlot(2)
thinkplot.Hist(first_pmf, align='right', width=width)
thinkplot.Hist(other_pmf, align='left', width=width)
thinkplot.Save(root='cumulative_birthwgt_pmf',
title='Birth weight',
xlabel='weight (pounds)',
ylabel='PMF')
# plot CDFs of birth weights for first babies and others
first_cdf = thinkstats2.Cdf(firsts.totalwgt_lb, label='first')
other_cdf = thinkstats2.Cdf(others.totalwgt_lb, label='other')
thinkplot.PrePlot(2)
thinkplot.Cdfs([first_cdf, other_cdf])
thinkplot.Save(root='cumulative_birthwgt_cdf',
title='Birth weight',
xlabel='weight (pounds)',
ylabel='CDF',
axis=[0, 12.5, 0, 1]
)
def MakeCdf(live):
"""Plot the CDF of pregnancy lengths for live births.
live: DataFrame for live births
"""
cdf = thinkstats2.Cdf(live.prglngth, label='prglngth')
thinkplot.Cdf(cdf)
thinkplot.Save('cumulative_prglngth_cdf',
title='Pregnancy length',
xlabel='weeks',
ylabel='CDF')
def RandomFigure(live):
weights = live.totalwgt_lb
cdf = thinkstats2.Cdf(weights, label='totalwgt_lb')
sample = np.random.choice(weights, 100, replace=True)
ranks = [cdf.PercentileRank(x) for x in sample]
rank_cdf = thinkstats2.Cdf(ranks, label='percentile ranks')
thinkplot.Cdf(rank_cdf)
thinkplot.Save(root='cumulative_random',
xlabel='percentile rank',
ylabel='CDF')
def TestSample(live):
"""Plots the distribution of weights against a random sample.
live: DataFrame for live births
"""
weights = live.totalwgt_lb
cdf = thinkstats2.Cdf(weights, label='totalwgt_lb')
sample = cdf.Sample(1000)
sample_cdf = thinkstats2.Cdf(sample, label='sample')
thinkplot.PrePlot(2)
thinkplot.Cdfs([cdf, sample_cdf])
thinkplot.Save(root='cumulative_sample',
xlabel='weight (pounds)',
ylabel='CDF')
def main(name, data_dir=''):
thinkstats2.RandomSeed(17)
MakeExample()
live, firsts, others = first.MakeFrames()
RandomFigure(live)
TestSample(live)
MakeCdf(live)
MakeFigures(live, firsts, others)
if __name__ == '__main__':
import sys
main(*sys.argv)