def MODE(df, n, price='Close'):
"""
Mode (most common value) of discrete data
"""
mode_list = []
i = 0
while i < len(df[price]):
if i + 1 < n:
mode = float('NaN')
else:
start = i + 1 - n
end = i + 1
mode = statistics.mode(df[price][start:end])
mode_list.append(mode)
i += 1
return mode_list
python类mode()的实例源码
def listen_for_end(self, keypress):
""" Listen for 'q', left, or right keys to end game.
"""
if keypress != 255:
print(keypress)
if keypress == ord('q'): # 'q' pressed to quit
print("Escape key entered")
return "END"
elif self.curr_level == 0:
# Select mode
self.curr_level = 1
self.tickcount = 0
if keypress == 81 or keypress == 2: # left
self.easy_mode = True
elif keypress == 83 or keypress == 3: # right
self.easy_mode = False
elif self.curr_level == 2:
print("Resetting")
self.reset()
Exercises4.py 文件源码
项目:Python-Programming-A-Concise-Introduction
作者: abdullahaalam
项目源码
文件源码
阅读 28
收藏 0
点赞 0
评论 0
def temp_stat(temps):
""" computes the average, median, std dev, and variance of temps """
import statistics
print(temps)
print("Mean: ", statistics.mean(temps))
print("Median: ", statistics.median(temps))
print("Standard deviation: ", statistics.stdev(temps))
print("Variance: ", statistics.variance(temps))
try:
print("Mode: ", statistics.mode(temps))
except statistics.StatisticsError as e:
print("Mode error: ", e)
#%%
def test():
"""Tests the statistical functions.
Raises:
AssertionError if a test fails.
"""
testlist0 = [1, 2, 3, 4, 5]
testlist1 = [1, 2, 3, 4, 5, 6]
testlist2 = [2, 2, 3, 4, 4, 6]
testlist3 = [2, 2, 3, 4, 5, 6, 7]
assert mean(testlist0) - 5 <= 1e-6, mean(testlist0)
assert mean(testlist1) - 3.5 <= 1e-6, mean(testlist1)
assert mean(testlist2) - 21 / 6 <= 1e-6, mean(testlist2)
assert mean(testlist3) - 29 / 7 <= 1e-6, mean(testlist3)
assert median(testlist0) == 3, median(testlist0)
assert median(testlist1) - 3.5 <= 1e-6, median(testlist1)
assert median(testlist2) - 3.5 <= 1e-6, median(testlist2)
assert median(testlist3) == 4, median(testlist3)
assert mode(testlist3) == 2, mode(testlist3)
def get_stats(self, metrics, lang=UNSPECIFIED_TRANSLATION, limit=100):
stats = super(NumField, self).get_stats(metrics, lang, limit)
stats.update({
'median': '*',
'mean': '*',
'mode': '*',
'stdev': '*'
})
try:
# require a non empty dataset
stats['mean'] = statistics.mean(self.flatten_dataset(metrics))
stats['median'] = statistics.median(self.flatten_dataset(metrics))
# requires at least 2 values in the dataset
stats['stdev'] = statistics.stdev(self.flatten_dataset(metrics),
xbar=stats['mean'])
# requires a non empty dataset and a unique mode
stats['mode'] = statistics.mode(self.flatten_dataset(metrics))
except statistics.StatisticsError:
pass
return stats
def average(numbers, type='mean'):
import statistics
type = type.lower()
try:
statistics.mean(numbers)
except:
raise RuntimeError('An Error Has Occured: List Not Specified (0018)')
if type == 'mean':
return statistics.mean(numbers)
elif type == 'mode':
return statistics.mode(numbers)
elif type == 'median':
return statistics.median(numbers)
elif type == 'min':
return min(numbers)
elif type == 'max':
return max(numbers)
elif type == 'range':
return max(numbers) - min(numbers)
else:
raise RuntimeError('An Error Has Occured: You Entered An Invalid Operation (0003)')
# Throw A Runtime Error
def mode(self):
return statistics.mode(self.price)
# ???
# ??
def get_mode_trade_size(self, side: OrderSide, order_type: OrderType, seconds_ago: int,
group_by_period: Optional[int] = None) -> Optional[float]:
order_quantities = self.get_trade_quantities(side, order_type, seconds_ago, group_by_period)
if len(order_quantities) == 0:
return None
try:
return mode(order_quantities)
except StatisticsError:
return None
def classify(self, features):
if not self.votes:
self.get_votes(features)
return mode(self.votes)
def confidence(self, features):
if not self.votes:
self.get_votes(features)
choice_votes = self.votes.count(mode(self.votes))
conf = choice_votes / len(self.votes)
return conf
def classify(self, features):
votes = []
for c in self._classifiers:
v = c.classify(features)
votes.append(v)
return mode(votes)
def confidence(self, features):
votes = []
for c in self._classifiers:
v = c.classify(features)
votes.append(v)
choice_votes = votes.count(mode(votes))
conf = choice_votes / len(votes)
return conf
def classify(self, features):
votes = []
for c in self._classifiers:
v = c.classify(features)
votes.append(v)
return mode(votes)
def confidence(self, features):
votes = []
for c in self._classifiers:
v = c.classify(features)
votes.append(v)
choice_votes = votes.count(mode(votes))
conf = choice_votes / len(votes)
return conf
Train_Classifiers.py 文件源码
项目:NLP-Sentiment-Analysis-Twitter
作者: aalind0
项目源码
文件源码
阅读 27
收藏 0
点赞 0
评论 0
def __init__(self, *classifiers):
self._classifiers = classifiers
#Creating our own classify method.
#After iterating we return mode(votes), which just returns the most popular vote.
Train_Classifiers.py 文件源码
项目:NLP-Sentiment-Analysis-Twitter
作者: aalind0
项目源码
文件源码
阅读 26
收藏 0
点赞 0
评论 0
def classify(self, features):
votes = []
for c in self._classifiers:
v = c.classify(features)
votes.append(v)
return mode(votes)
#Defining another parameter, confidence.
#Since we have algorithms voting, we can tally the votes for and against the winning vote, and call this "confidence.
Train_Classifiers.py 文件源码
项目:NLP-Sentiment-Analysis-Twitter
作者: aalind0
项目源码
文件源码
阅读 24
收藏 0
点赞 0
评论 0
def confidence(self, features):
votes = []
for c in self._classifiers:
v = c.classify(features)
votes.append(v)
choice_votes = votes.count(mode(votes))
conf = choice_votes / len(votes)
return conf
# Defining and Accessing the corporas.
# In total, approx 10,000 feeds to be trained and tested on.
def classify(self, features):
votes = []
for c in self._classifiers:
v = c.classify(features)
votes.append(v)
return mode(votes)
def classify(self, features):
votes = []
for c in self._classifiers:
v = c.classify(features)
votes.append(v)
return mode(votes)
def confidence(self, features):
votes = []
for c in self._classifiers:
v = c.classify(features)
votes.append(v)
choice_votes = votes.count(mode(votes))
conf = choice_votes / len(votes)
return conf
def __init__(self, *classifiers):
self._classifiers = classifiers
# this classifies the vote and returns the mode
# of the result.
# must be handed:
# *featured words
def clify(self, features):
self.votes = []
for self.i in self._classifiers:
self.j = self.i.clify(features)
self.votes.append(self.j)
return mode(self.votes)
# find the confidents of results
# must be handed:
# *featured words
def conf(self, features):
self.votes = []
for self.i in self._classifiers:
self.j = self.i.clify(features)
self.votes.append(self.j)
self.choice_votes = self.votes.count(mode(self.votes))
self.conf = self.choice_votes / len(self.votes)
return self.conf
# find the features of document
# must be handed:
# *document to find feature of
# *word features
def __init__(self, *classifiers):
self._classifiers = classifiers
# this classifies the vote and returns the mode
# of the result.
# must be handed:
# *featured words
def classify(self, features):
self.votes = []
for self.i in self._classifiers:
self.j = self.i.classify(features)
self.votes.append(self.j)
return mode(self.votes)
# find the confidents of results
# must be handed:
# *featured words
def main():
print(stats.mean(range(6)))
print(stats.median(range(6)))
print(stats.median_low(range(6)))
print(stats.median_high(range(6)))
print(stats.median_grouped(range(6)))
try:
print(stats.mode(range(6)))
except Exception as e:
print(e)
print(stats.mode(list(range(6)) + [3]))
print(stats.pstdev(list(range(6)) + [3]))
print(stats.stdev(list(range(6)) + [3]))
print(stats.pvariance(list(range(6)) + [3]))
print(stats.variance(list(range(6)) + [3]))
def prepare_data(self):
"""Overload method from UnivariateCommonMixin."""
# Make sure test data has exactly one mode.
return [1, 1, 1, 1, 3, 4, 7, 9, 0, 8, 2]
def test_nominal_data(self):
# Test mode with nominal data.
data = 'abcbdb'
self.assertEqual(self.func(data), 'b')
data = 'fe fi fo fum fi fi'.split()
self.assertEqual(self.func(data), 'fi')
def test_discrete_data(self):
# Test mode with discrete numeric data.
data = list(range(10))
for i in range(10):
d = data + [i]
random.shuffle(d)
self.assertEqual(self.func(d), i)
def test_bimodal_data(self):
# Test mode with bimodal data.
data = [1, 1, 2, 2, 2, 2, 3, 4, 5, 6, 6, 6, 6, 7, 8, 9, 9]
assert data.count(2) == data.count(6) == 4
# Check for an exception.
self.assertRaises(statistics.StatisticsError, self.func, data)