-
-
Save yulkang/c2b330db2af5f7ce82a38d0c32f3a7c7 to your computer and use it in GitHub Desktop.
Bootstrapped two-sample t-test in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from __future__ import division | |
import numpy as np | |
import pandas as pd | |
import random | |
def sample(data): | |
sample = [random.choice(data) for _ in xrange(len(data))] | |
return sample | |
def bootstrap_t_test(treatment, control, nboot = 1000, direction = "less"): | |
ones = np.vstack((np.ones(len(treatment)),treatment)) | |
treatment = ones.conj().transpose() | |
zeros = np.vstack((np.zeros(len(control)), control)) | |
control = zeros.conj().transpose() | |
Z = np.vstack((treatment, control)) | |
tstat = np.mean(treatment[:,1])-np.mean(control[:,1]) | |
tboot = np.zeros(nboot) | |
for i in xrange(nboot): | |
sboot = sample(Z) | |
sboot = pd.DataFrame(np.array(sboot), columns=['treat', 'vals']) | |
tboot[i] = np.mean(sboot['vals'][sboot['treat'] == 1]) - np.mean(sboot['vals'][sboot['treat'] == 0]) - tstat | |
if direction == "greater": | |
pvalue = np.sum(tboot>=tstat-0)/nboot | |
elif direction == "less": | |
pvalue = np.sum(tboot<=tstat-0)/nboot | |
else: | |
print 'Enter a valid arg for direction' | |
print 'The p-value is %f' % (pvalue) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment