Data Science Fundamentals for Python and MongoDB 1st Edition David Paper instant download
Data Science Fundamentals for Python and MongoDB 1st Edition David Paper instant download
https://textbookfull.com/product/data-science-fundamentals-for-
python-and-mongodb-1st-edition-david-paper/
https://textbookfull.com/product/hands-on-scikit-learn-for-
machine-learning-applications-data-science-fundamentals-with-
python-david-paper/
https://textbookfull.com/product/introduction-to-python-for-
science-and-engineering-1st-edition-david-j-pine/
https://textbookfull.com/product/python-for-data-science-2nd-
edition-john-paul-mueller/
https://textbookfull.com/product/data-science-with-python-1st-
edition-coll/
Python Data Science Handbook Essential Tools for
Working with Data 1st Edition Jake Vanderplas
https://textbookfull.com/product/python-data-science-handbook-
essential-tools-for-working-with-data-1st-edition-jake-
vanderplas/
https://textbookfull.com/product/python-data-science-handbook-
essential-tools-for-working-with-data-1st-edition-jake-
vanderplas-2/
https://textbookfull.com/product/data-science-and-analytics-with-
python-1st-edition-jesus-rogel-salazar/
https://textbookfull.com/product/fundamentals-of-python-data-
structures-2nd-edition-kenneth-a-lambert/
https://textbookfull.com/product/introducing-data-science-big-
data-machine-learning-and-more-using-python-tools-1st-edition-
davy-cielen/
David Paper
Trademarked names, logos, and images may appear in this book. Rather
than use a trademark symbol with every occurrence of a trademarked
name, logo, or image, we use the names, logos, and images only in an
editorial fashion and to the benefit of the trademark owner, with no
intention of infringement of the trademark. The use in this publication
of trade names, trademarks, service marks, and similar terms, even if
they are not identified as such, is not to be taken as an expression of
opinion as to whether or not they are subject to proprietary rights.
While the advice and information in this book are believed to be true
and accurate at the date of publication, neither the authors nor the
editors nor the publisher can accept any legal responsibility for any
errors or omissions that may be made. The publisher makes no
warranty, express or implied, with respect to the material contained
herein.
1. Introduction
David Paper1
(1) Apt 3, Logan, Utah, USA
Python Fundamentals
Python has several features that make it well suited for learning and
doing data science. It’s free, relatively simple to code, easy to
understand, and has many useful libraries to facilitate data science
problem solving. It also allows quick prototyping of virtually any data
science scenario and demonstration of data science concepts in a clear,
easy to understand manner.
The goal of this chapter is not to teach Python as a whole, but present,
explain, and clarify fundamental features of the language (such as logic,
data structures, and libraries) that help prototype, apply, and/or solve
data science problems.
Python fundamentals are covered with a wide spectrum of activities
with associated coding examples as follows:
1. functions and strings
4. list comprehension
5. generators
6. data randomization
8. visualization
def str_to_int(s):
return int(s)
def str_to_float(f):
return float(f)
if __name__ == "__main__":
# hash symbol allows single-line comments
'''
triple quotes allow multi-line comments
'''
float_num = 999.01
int_num = 87
float_str = '23.09'
int_str = '19'
string = 'how now brown cow'
s_float = num_to_str(float_num)
s_int = num_to_str(int_num)
i_str = str_to_int(int_str)
f_str = str_to_float(float_str)
print (s_float, 'is', type(s_float))
print (s_int, 'is', type(s_int))
print (f_str, 'is', type(f_str))
print (i_str, 'is', type(i_str))
print ('\nstring', '"' + string + '" has',
len(string), 'characters')
str_ls = string.split()
print ('split string:', str_ls)
print ('joined list:', ' '.join(str_ls))
Output:
A popular coding style is to present library importation and functions
first, followed by the main block of code. The code example begins with
three custom functions that convert numbers to strings, strings to
numbers, and strings to float respectively. Each custom function returns
a built-in function to let Python do the conversion. The main block
begins with comments. Single-line comments are denoted with the #
(hash) symbol. Multiline comments are denoted with three consecutive
single quotes. The next five lines assign values to variables. The
following four lines convert each variable type to another type. For
instance, function num_to_str() converts variable float_num to string
type. The next five lines print variables with their associated Python
data type. Built-in function type() returns type of given object. The
remaining four lines print and manipulate a string variable.
import numpy as np
if __name__ == "__main__":
ls = ['orange', 'banana', 10, 'leaf', 77.009,
'tree', 'cat']
print ('list length:', len(ls), 'items')
print ('cat count:', ls.count('cat'), ',',
'cat index:', ls.index('cat'))
print ('\nmanipulate list:')
cat = ls.pop(6)
print ('cat:', cat, ', list:', ls)
ls.insert(0, 'cat')
ls.append(99)
print (ls)
ls[7] = '11'
print (ls)
ls.pop(1)
print (ls)
ls.pop()
print (ls)
print ('\nslice list:')
print ('1st 3 elements:', ls[:3])
print ('last 3 elements:', ls[3:])
print ('start at 2nd to index 5:', ls[1:5])
print ('start 3 from end to end of list:',
ls[-3:])
print ('start from 2nd to next to end of
list:', ls[1:-1])
print ('\ncreate new list from another list:')
print ('list:', ls)
fruit = ['orange']
more_fruit = ['apple', 'kiwi', 'pear']
fruit.append(more_fruit)
print ('appended:', fruit)
fruit.pop(1)
fruit.extend(more_fruit)
print ('extended:', fruit)
a, b = fruit[2], fruit[1]
print ('slices:', a, b)
print ('\ncreate matrix from two lists:')
matrix = np.array([ls, fruit])
print (matrix)
print ('1st row:', matrix[0])
print ('2nd row:', matrix[1])
Output:
import numpy as np
if __name__ == "__main__":
tup = ('orange', 'banana', 'grape', 'apple',
'grape')
print ('tuple length:', len(tup))
print ('grape count:', tup.count('grape'))
print ('\nslice tuple:')
print ('1st 3 elements:', tup[:3])
print ('last 3 elements', tup[3:])
print ('start at 2nd to index 5', tup[1:5])
print ('start 3 from end to end of tuple:',
tup[-3:])
print ('start from 2nd to next to end of
tuple:', tup[1:-1])
print ('\ncreate list and create matrix from
it and tuple:')
fruit = ['pear', 'grapefruit', 'cantaloupe',
'kiwi', 'plum']
matrix = np.array([tup, fruit])
print (matrix)
Output:
if __name__ == "__main__":
audio = {'amp':'Linn', 'preamp':'Luxman',
'speakers':'Energy',
'ic':'Crystal Ultra', 'pc':'JPS',
'power':'Equi-Tech',
'sp':'Crystal Ultra', 'cdp':'Nagra',
'up':'Esoteric'}
del audio['up']
print ('dict "deleted" element;')
print (audio, '\n')
print ('dict "added" element;')
audio['up'] = 'Oppo'
print (audio, '\n')
print ('universal player:', audio['up'], '\n')
dict_ls = [audio]
video = {'tv':'LG 65C7 OLED', 'stp':'DISH',
'HDMI':'DH Labs',
'cable' : 'coax'}
print ('list of dict elements;')
dict_ls.append(video)
for i, row in enumerate(dict_ls):
print ('row', i, ':')
print (row)
Output:
The main block begins by creating dictionary audio with several
elements. It continues by deleting an element with key up and value
Esoteric, and displaying. Next, a new element with key up and element
Oppo is added back and displayed. The next part creates a list with
dictionary audio, creates dictionary video, and adds the new dictionary
to the list. The final part uses a for loop to traverse the dictionary list
and display the two dictionaries. A very useful function that can be used
with a loop statement is enumerate(). It adds a counter to an iterable.
An iterable is an object that can be iterated. Function enumerate() is
very useful because a counter is automatically created and
incremented, which means less code .
import csv
def read_txt(f):
with open(f, 'r') as f:
d = f.readlines()
return [x.strip() for x in d]
def read_csv(f):
contents = ''
with open(f, 'r') as f:
reader = csv.reader(f)
return list(reader)
def od_to_d(od):
return dict(od)
if __name__ == "__main__":
f = 'data/names.txt'
data = read_txt(f)
print ('text file data sample:')
for i, row in enumerate(data):
if i < 3:
print (row)
csv_f = 'data/names.csv'
conv_csv(f, csv_f)
r_csv = read_csv(csv_f)
print ('\ntext to csv sample:')
for i, row in enumerate(r_csv):
if i < 3:
print (row)
headers = ['first', 'last']
r_dict = read_dict(csv_f, headers)
dict_ls = []
print ('\ncsv to ordered dict sample:')
for i, row in enumerate(r_dict):
r = od_to_d(row)
dict_ls.append(r)
if i < 3:
print (row)
print ('\nlist of dictionary elements
sample:')
for i, row in enumerate(dict_ls):
if i < 3:
print (row)
Output:
The code begins by importing the csv library, which implements classes
to read and write tabular data in CSV format. It continues with five
functions. Function read_txt() reads a text (.txt) file and strips
(removes) extraneous characters with list comprehension, which is an
elegant way to define and create a list in Python. List comprehension is
covered later in the next section. Function conv_csv() converts a text to
a CSV file and saves it to disk. Function read_csv() reads a CSV file and
returns it as a list. Function read_dict() reads a CSV file and returns a
list of OrderedDict elements. An OrderedDict is a dictionary subclass
that remembers the order in which its contents are added, whereas a
regular dictionary doesn’t track insertion order. Finally, function
od_to_d() converts an OrderedDict element to a regular dictionary
element. Working with a regular dictionary element is much more
intuitive in my opinion. The main block begins by reading a text file and
cleaning it for processing. However, no processing is done with this
cleansed file in the code. It is only included in case you want to know
how to accomplish this task. The code continues by converting a text
file to CSV, which is saved to disk. The CSV file is then read from disk
and a few records are displayed. Next, a headers list is created to store
keys for a dictionary yet to be created. List dict_ls is created to hold
dictionary elements. The code continues by creating an OrderedDict list
r_dict. The OrderedDict list is then iterated so that each element can be
converted to a regular dictionary element and appended to dict_ls. A
few records are displayed during iteration. Finally, dict_ls is iterated
and a few records are displayed. I highly recommend that you take
some time to familiarize yourself with these data structures, as they are
used extensively in data science application.
List Comprehension
List comprehension provides a concise way to create lists. Its logic is
enclosed in square brackets that contain an expression followed by a
for clause and can be augmented by more for or if clauses.
The read_txt() function in the previous section included the following
list comprehension:
[x.strip() for x in d]
The logic strips extraneous characters from string in iterable d. In this
case, d is a list of strings.
The following code example converts miles to kilometers, manipulates
pets, and calculates bonuses with list comprehension:
if __name__ == "__main__":
miles = [100, 10, 9.5, 1000, 30]
kilometers = [x * 1.60934 for x in miles]
print ('miles to kilometers:')
for i, row in enumerate(kilometers):
print ('{:>4} {:>8}{:>8} {:>2}'.
format(miles[i],'miles is',
round(row,2), 'km'))
print ('\npet:')
pet = ['cat', 'dog', 'rabbit', 'parrot',
'guinea pig', 'fish']
print (pet)
print ('\npets:')
pets = [x + 's' if x != 'fish' else x for x in
pet]
print (pets)
subset = [x for x in pets if x != 'fish' and x
!= 'rabbits'
and x != 'parrots' and x != 'guinea
pigs']
print ('\nmost common pets:')
print (subset[1], 'and', subset[0])
sales = [9000, 20000, 50000, 100000]
print ('\nbonuses:')
bonus = [0 if x < 10000 else x * .02 if x >=
10000 and x <= 20000
else x * .03 for x in sales]
print (bonus)
print ('\nbonus dict:')
people = ['dave', 'sue', 'al', 'sukki']
d = {}
for i, row in enumerate(people):
d[row] = bonus[i]
print (d, '\n')
print ('{:<5} {:<5}'.format('emp', 'bonus'))
for k, y in d.items():
print ('{:<5} {:>6}'.format(k, y))
Output:
The main block begins by creating two lists—miles and kilometers. The
kilometers list is created with list comprehension , which multiplies
each mile value by 1.60934. At first, list comprehension may seem
confusing, but practice makes it easier over time. The main block
continues by printing miles and associated kilometers. Function
format() provides sophisticated formatting options. Each mile value is
({:>4}) with up to four characters right justified. Each string for miles
and kilometers is right justified ({:>8}) with up to eight characters .
Finally, each string for km is right justified ({:>2}) with up to two
characters. This may seem a bit complicated at first, but it is really quite
logical (and elegant) once you get used to it. The main block continues
by creating pet and pets lists. The pets list is created with list
comprehension, which makes a pet plural if it is not a fish. I advise you
to study this list comprehension before you go forward, because they
just get more complex. The code continues by creating a subset list with
list comprehension, which only includes dogs and cats. The next part
creates two lists—sales and bonus. Bonus is created with list
comprehension that calculates bonus for each sales value. If sales are
less than 10,000, no bonus is paid. If sales are between 10,000 and
20,000 (inclusive), the bonus is 2% of sales. Finally, if sales if greater
than 20,000, the bonus is 3% of sales. At first I was confused with this
list comprehension but it makes sense to me now. So, try some of your
own and you will get the gist of it. The final part creates a people list to
associate with each sales value, continues by creating a dictionary to
hold bonus for each person, and ends by iterating dictionary elements.
The formatting is quite elegant. The header left justifies emp and bonus
properly. Each item is formatted so that the person is left justified with
up to five characters ({:<5}) and the bonus is right justified with up to
six characters ({:>6}).
Generators
A generator is a special type of iterator, but much faster because values
are only produced as needed. This process is known as lazy (or
deferred) evaluation. Typical iterators are much slower because they
are fully built into memory. While regular functions return values,
generators yield them. The best way to traverse and access values from
a generator is to use a loop. Finally, a list comprehension can be
converted to a generator by replacing square brackets with
parentheses.
The following code example reads a CSV file and creates a list of
OrderedDict elements . It then converts the list elements into regular
dictionary elements. The code continues by simulating times for list
comprehension, generator comprehension, and generators. During
simulation, a list of times for each is created. Simulation is the imitation
of a real-world process or system over time, and it is used extensively in
data science.
def conv_reg_dict(d):
return [dict(x) for x in d]
def gen(d):
yield (x for x in d)
def avg_ls(ls):
return np.mean(ls)
if __name__ == '__main__':
f = 'data/names.csv'
headers = ['first', 'last']
r_dict = read_dict(f, headers)
dict_ls = conv_reg_dict(r_dict)
n = 1000
ls_times, gc_times = sim_times(dict_ls, n)
g_times = sim_gen(dict_ls, n)
avg_ls = np.mean(ls_times)
avg_gc = np.mean(gc_times)
avg_g = np.mean(g_times)
gc_ls = round((avg_ls / avg_gc), 2)
g_ls = round((avg_ls / avg_g), 2)
print ('generator comprehension:')
print (gc_ls, 'times faster than list
comprehension\n')
print ('generator:')
print (g_ls, 'times faster than list
comprehension')
Output:
Another Random Document on
Scribd Without Any Related Topics
collecting the Scots, and after very hard fighting the garrison was
driven in. Bruce presently came up with large reinforcements, but
the castle held out tenaciously, and surrendered only to famine. The
town was taken on March 28 (Fordun), or April 2 (Lanercost); the
castle held out gallantly till past the middle of July, and even then
Horsley marched out his famished garrison with the honours of war.
Bruce installed as warden Sir Walter the Steward. Peter of Spalding,
says John of Tynmouth, proved troublesome in insisting upon his
promised reward; and, on an accusation of plotting against the life
of King Robert, was put to death. The allegation recalls the case of
Sir Peter de Lubaud.
Edward was extremely incensed at the Mayor and burgesses of
Berwick, who had undertaken, for 6000 marks, to defend the town
for a year from June 15, 1317. He ascribed the loss of it to their
carelessness, and in the middle of April he ordered that their goods
and chattels, wheresoever found, should be confiscated, and that
such of them as had escaped into England should be imprisoned. On
June 10, 1318, he summoned his army to meet him at York on July
26, to proceed against the Scots.
Meantime the Scots were proceeding with vigour against him.
For soon after the capture of Berwick town, Bruce detached a strong
force to ravage the northern counties. They laid waste
Northumberland to the gates of Newcastle, starved the castles of
Harbottle and Wark into surrender, and took Mitford Castle by
stratagem. They sold immunity to the episcopate of Durham,
excepting Hartlepool, which Bruce threatened to burn and destroy
because some of its inhabitants had captured a ship freighted with
his 'armeours' and provisions. Northallerton, Ripon, Boroughbridge,
Knaresborough, Otley and Skipton were guiding-points in the
desolating track of the invaders. Ripon and Otley suffered most
severely, and Ripon paid 1000 marks for a cessation of destruction.
Fountains Abbey also paid ransom; Bolton Abbey was plundered;
Knaresborough Parish Church bears to this day the marks of the fire
that burnt out the fugitives. The expedition returned to Scotland
laden with spoils, and bringing numerous captives and great droves
of cattle. The Archbishop of York postponed misfortune by being too
late with measures of resistance. But he energetically
excommunicated the depredators, all and sundry.
On hearing of Bruce's reception of the envoys, the Pope had
authorised the Cardinals, on December 29, to put in execution the
two Bulls of excommunication prepared in the previous March. The
Cardinals, however, would seem to have delayed. On June 28, 1318,
when the Pope heard of the woeful adventures of Adam de Newton
and of the capture of Berwick despite his truce, he ordered them to
proceed. For Bruce, he said, had 'grievously' (dampnabiliter) 'abused
his patience and long-suffering.' In September accordingly they
excommunicated and laid under interdict Bruce himself, his brother
Edward, and all their aiders and abettors in the invasion of England
and Ireland. 'But,' says the Lanercost chronicler, 'the Scots cared not
a jot for any excommunication, and declined to pay any observance
to the interdict.' In October, Edward followed up his diplomatic
success by pressing hard for the deposition of the Bishop of St
Andrews, but the Pope easily found good technical pleas whereby to
avoid compliance.
The Irish expedition came to a disastrous close on the fatal field
of Faughart, near Dundalk, on October 5 (or 14), 1318. A vastly
superior English army, under Sir John de Bermingham, moved
against the Scots; and King Edward the Bruce, wrathfully overruling
the counsels of his staff, disdaining to wait for the approaching
reinforcements from Scotland, and despising the hesitations of his
Irish allies, dashed against the tremendous odds with his native
impetuosity.
'Now help quha will, for sekirly
This day, but mair baid, fecht vill I.
Sall na man say, quhill I may dre,
That strynth of men sall ger me fle!
God scheld that ony suld vs blame
That we defoull our nobill name!'
Barbour gives the numbers at 2000 against 40,000, no doubt
with generous exaggeration. King Edward fell at the first onset, killed
by a gigantic Anglo-Irish knight, Sir John de Maupas, who was found
lying dead across his body. Sir John the Steward, Sir John de Soulis,
and other officers were slain. Barbour tells how Sir Philip de
Mowbray, stunned in action, was led captive by two men towards
Dundalk; how he recovered his senses sufficiently to realise his
position, shook off his captors, drew his sword and turned back
towards the battle-field, and how he cleared a hundred men out of
his way as he went. John Thomasson, the leader of the Carrick men,
took him in charge, and hurried him away towards Carrickfergus. But
the brave defender of Stirling had received a mortal wound. King
Edward's body was dismembered, the trunk buried at Faughart, and
the limbs exposed in Irish towns held by the English. The head is
said to have been sent to England to Edward; but Barbour tells how
King Edward the Bruce had that day exchanged armour with Gilbert
the Harper, as he had done before at Connor, and how it was
Gilbert's head that had been mistakenly struck off and despatched to
England. The remnants of the Scots army reached Carrickfergus with
the utmost difficulty, and hastily took ship for Scotland, where the
news was received with great lamentation. Bermingham was created
Earl of Louth for his victory. It is curious to observe that his wife was
a sister of the Queen of Scotland.
The death of Edward Bruce disturbed the settlement of the
succession, which was again brought under consideration of
Parliament, on December 3, at Scone. Robert, the son of Sir Walter
the Steward and the late Princess Marjory, was recognised as heir,
with a proviso saving the right of any subsequent male issue of King
Robert. In case of a minority, Randolph was to be guardian; and
failing Randolph, Douglas.
No sooner had the sentences of excommunication been
promulgated than King Robert took measures to have them revoked
or mitigated. He had good friends at Rome. Letters from these had
fallen accidentally into the hands of Edward, who, on January 12,
1318–19, sent them to the Pope by the hands of Sir John de Neville,
and asked His Holiness to deal suitably with the writers. A few days
before, he had urged the two Cardinals to press the Pope to reject
the applications that he heard were being made on behalf of Bruce
and his friends, and stated that he would presently send envoys to
the Pope himself. Neville was graciously received, and the Pope
ordered the Scots and their abettors at his court to prison. On April
24, the Pope granted Edward's request for a Bull permitting him to
negotiate for peace with the Scots notwithstanding their
excommunication. But the pressure was not all on one side; the
nuncios in England boldly exercised their powers, and had often to
be restrained even by royal menace, while every ecclesiastical office
was steadily claimed for the papal nominee. Bruce appears to have
deemed it prudent to raise little formal objection to the papal
appointment of ecclesiastics up and down Scotland, though some of
them evidently had but a seat of thorns.
From March to May there was an interesting correspondence
between Edward and some minor states and municipalities on the
other side of the North Sea, whose people, Edward understood, had
harboured, or even assisted, his Scots enemies. They all denied the
allegation. The statesmanlike answer of the Count of Flanders,
however, is peculiarly notable. 'Our land of Flanders,' he wrote, 'is
common to all men, of whatever country, and freely open to all
comers; and we cannot deny admission to merchants doing their
business as they have hitherto been accustomed, for thereby we
should bring our land to desolation and ruin.'
But Berwick must be recaptured. On the loss of Berwick town,
Edward had angrily summoned his forces to muster at York on July
26, 1318. So few of them appeared, however, that he was forced to
postpone the expedition. On June 4, 1319, he ordered the Welsh
levies to be at Newcastle by July 24 at latest; and, two days after, he
wrote to the Pope that he hoped now 'to put a bit in the jaws of the
Scots.' But another postponement was forced on him. On July 20,
however, he issued a peremptory order for a muster at Michaelmas.
His May parliament at York had granted him certain taxes, his
treasury being 'exhausted more than is believed'; and his good
friend the Pope had added a material contribution. But the levy
could not be collected till Michaelmas, and meantime the King
appealed for an advance. There must have been a favourable
response, for early in September he encamped before Berwick with
some 10,000 or 12,000 men, his fleet occupying the harbour. Having
entrenched his lines, he delivered a general assault on September 7.
The besiegers hastily filled the dykes and placed their scaling-
ladders, but the garrison threw them down as fast as they were
raised. The lowness of the wall was not altogether in favour of the
assailants, for the besieged on the top could easily thrust their
spears in their faces. In the course of the afternoon the English
brought a ship on the flood-tide up to the wall, with a boat lashed to
midmast, whence a bridge was to be let down for landing a storming
party. They were embarrassed in their efforts, however, and the ship,
being left aground by the ebb-tide, was burned by the Scots, the
sallying party with difficulty regaining the town. The fight went on
briskly till night, when the combatants agreed to postpone its
renewal for five days.
Though King Robert had mustered a considerable force,
probably as large as Edward's, he deemed it more prudent to
despatch it on a raid into England than to launch it directly against
the English entrenchments. He had, indeed, good reason to rely
upon the skill and energy of the Steward. The five days' truce over,
the English, on September 13, moved forward on wheels an
immense sow, not only covering a mining party, but carrying
scaffolds for throwing a storming party on the wall. By this time,
John Crab, whom we have already met as a sea-captain or pirate,
and whom the Count of Flanders presently assured Edward he would
break on the wheel, if he could only get hold of him, had proved
himself engineer enough to devise a 'crane,' which must have been
of the nature of a catapult; and this engine he ran along the wall on
wheels to encounter the sow. The first shot passed over the
monster; the second just fell short; the third crashed through the
main beam, and frightened the men out. 'Your sow has farrowed,'
cried the Scots. Crab now lowered blazing faggots of combustible
stuff upon the sow, and burnt it up. But presently another attempt
was made from the harbour, and Crab's engine was hurried up to
fight ships with top-castles full of men, and with fall-bridges ready at
midmast. The first shot demolished the top gear of one of the ships,
bringing down the men; and the other ships kept a safe distance.
Meantime the general attack raged all along the wall. Sir Walter
the Steward rode from point to point, supplying here and there men
from his own bodyguard, till it was reduced from a hundred to a
single man-at-arms. The severest pressure was at Mary Gate. The
besiegers forced the advance barricade, burned the drawbridge, and
fired the gate. Sir Walter drew reinforcements from the castle, which
had not been attacked, threw open Mary Gate and sallied upon the
foe, driving them back after a very hard struggle, and saving the
gate. Night separated the combatants. Barbour tells how the women
and children of the town had carried arrows to the men on the walls,
and regards it as a miracle that not one of them was slain or
wounded. But clearly the Steward could not sustain many days of
such heavy fighting.
The Scots army under Randolph and Douglas had meanwhile
followed the familiar track through Ripon and Boroughbridge,
harrying and burning and slaying. They appear to have made a
serious attempt to capture Edward's Queen, who was then staying
near York; but the Archbishop, learning this intention from a Scots
spy that had been taken prisoner, sallied forth and brought her into
the city, and sent her by water to Nottingham. Trokelowe speaks of
certain 'false Englishmen' that had been bribed by the Scots, and
Robert of Reading specifies Sir Edmund Darel as the guide of the
invaders in the attempt. Next day the Archbishop, with Bishop
Hotham of Ely, the Chancellor of England, and an unwieldy multitude
of clergy and townspeople numbering some 10,000, advanced
against the Scots between Myton and Thornton-on-Swale, about
twelve miles north of York. 'These,' said the Scots, 'are not soldiers,
but hunters; they will not do much good.' For the English 'came
through the fields in scattered fashion, and not in united order.' The
Scots formed a schiltron, and set fire to some hay in front, the
smoke from which was blown into the faces of the English. As they
met, the Scots raised a great shout, and the enemy, 'more intent on
fleeing than on fighting,' took to their heels. The Scots mounted in
pursuit, killing (says the Lanercost chronicle) clergy and laymen,
about 4000, including Nicholas Fleming, the Mayor of York, while
about 1000, 'as was said,' were drowned in the Swale. Many were
captured and held to heavy ransom. The Archbishop lost, not only
his men, his carriages, and his equipment generally, but all his plate,
'silver and bronze as well,' which his servants had 'thoughtlessly'
taken to the field; and yet the blame may rest elsewhere, for the
York host appears to have fully anticipated that the Scots would flee
at sight of them. The Primate's official cross was saved by the
bearer, who dashed on horseback through the Swale and carefully
hid it, escaping himself in the dusk of the evening. Then a
countryman, who had observed the cross and watched the bearer's
retreat, discovered it, wound wisps of hay about it, and kept it in his
hut till search was made for it, whereupon he restored it to the
Archbishop. Such is John of Bridlington's story. The whole episode
contrasts markedly with the exploit of Bishop Sinclair in Fife. It was
contemptuously designated, from the number of ecclesiastics, 'the
Chapter of Myton.'
The Myton disaster occurred on September 20, and on
September 24 Edward raised the siege of Berwick. Certain
chroniclers speak of intestine dissensions, and particularly of a
quarrel with Lancaster over the appointment of wardens of town and
castle once Berwick was taken. The Lanercost chronicler says
Edward desired to detach a body to intercept the Scots, and with the
rest to carry on the siege; but his magnates would not hear of it. He
accordingly abandoned the siege, and marched westward to cut off
the retreat of the Scots. Randolph had penetrated to Castleford
Bridge, near Pontefract, and swept up Airedale and Wharfdale; and,
passing by Stainmoor and Gilsland, he eluded Edward's army, and
carried into Scotland many captives and immense plunder. It
remained for Edward but to disband his troops, and go home, as
usual, with empty hands.
About a month later (November 1), when the crops were
harvested in northern England, Randolph and Douglas returned with
fire and sword. They burnt Gilsland, and passed down to Brough
(Burgh) under Stainmoor; turned back on Westmorland, which they
ravaged for ten or twelve days, and went home through
Cumberland. They mercilessly burnt barns and the stored crops, and
swept the country of men and cattle.
Edward began to think of truce. In his letter of December 4 to
the Pope, he represents that urgent proposals for peace had come
to him from Bruce and his friends. In any case, the step was a most
sensible one. On December 21, terms were agreed on, and next day
Bruce confirmed them. This truce was to run for two years and the
odd days to Christmas. Bruce agreed to raise no new fortresses
within the counties of Berwick, Roxburgh, and Dumfries. He
delivered the castle of Harbottle to Edward's commissioners, 'as
private persons,' with the proviso that, unless a final peace were
made by Michaelmas, it should be either redelivered to him or
demolished. On August 25, 1321, Edward commanded that it should
be destroyed 'as secretly as possible.'
In autumn 1319, the Pope, at the instance of Edward, had given
orders for a revival of the excommunications against Bruce and his
friends; but on January 8, 1319–20, he cited Bruce and the Bishops
of St Andrews, Dunkeld, Aberdeen, and Moray, to compear before
him by May 1. The summons went unheeded; he had not addressed
Bruce as King. Excommunications were again hurled at Bruce and
his bishops, and Scotland was laid under ecclesiastical interdict.
Meanwhile, however, the Scots 'barons, freeholders, and all the
community of the realm'—no churchmen, be it observed—assembled
at Arbroath Abbey on April 6, and addressed to his Holiness a
memorable word in season. First, as to their kingdom and their King:
and that he fought his way to it and recovered it, 'taking it up with
great daintie.' This, too, is but a fantastic embellishment of the
cloister. Barbour, of course, proceeds to rout the Moors and to make
Douglas press on ahead of his company, attended by only ten men.
Seeing Sir William de St Clair surrounded, however, Douglas spurred
to his friend's rescue, but was overpowered by numbers and slain.
Among those that fell with him were Sir William de St Clair and Sir
Robert and Sir Walter Logan.
The bones of Douglas were brought home by Sir William de
Keith, who had been kept out of the battle by a broken arm, and
were buried in the church of St Bride of Douglas. The silver casket
with the heart of Bruce was buried by Randolph, 'with great
worship,' in Melrose Abbey.
Douglas has been charged with breach of trust. It is argued that
he ought not to have gone to Spain, but to have crossed the
continent to Venice or the south of France, and made direct for
Jerusalem. It is hardly worth while to remark that this is just what
Boece says he did, his death taking place in Spain on his way home.
It is more to the purpose that the Holy Sepulchre was then in the
hands of the Saracens, and that Spain was the central point of
opposition to the infidels. But what Douglas ought or ought not to
have done depends solely on the precise terms of his trust; and it
may be taken as certain that he knew King Robert's mind better than
either Barbour or Froissart, or even their critics, and that he decided
on his course in consultation with Randolph and the other magnates,
prelates as well as barons. Edward's safe conduct and
commendatory letter show by their terms that his going to Spain
was no afterthought, but his original intention. To attribute to
Douglas lack of 'strength of purpose' is to miss the whole
significance of his career.
* * * * *
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
textbookfull.com