Professional Documents
Culture Documents
A Python Data Analyst's Toolkit: Learn Python and Python-Based Libraries With Applications in Data Analysis and Statistics Gayathri Rajagopalan
A Python Data Analyst's Toolkit: Learn Python and Python-Based Libraries With Applications in Data Analysis and Statistics Gayathri Rajagopalan
https://textbookfull.com/product/data-analysis-from-scratch-with-
python-peters-morgan/
https://textbookfull.com/product/data-analysis-with-python-and-
pyspark-meap-v07-jonathan-rioux/
https://textbookfull.com/product/python-for-data-analysis-data-
wrangling-with-pandas-numpy-and-ipython-wes-mckinney/
https://textbookfull.com/product/python-data-analysis-perform-
data-collection-data-processing-wrangling-visualization-and-
model-building-using-python-3rd-edition-avinash-navlani/
Practical Python Data Visualization: A Fast Track
Approach To Learning Data Visualization With Python
Ashwin Pajankar
https://textbookfull.com/product/practical-python-data-
visualization-a-fast-track-approach-to-learning-data-
visualization-with-python-ashwin-pajankar/
https://textbookfull.com/product/python-2-and-3-compatibility-
with-six-and-python-future-libraries-nanjekye/
https://textbookfull.com/product/learning-data-mining-with-
python-layton/
https://textbookfull.com/product/a-tour-of-data-science-learn-r-
and-python-in-parallel-nailong-zhang/
https://textbookfull.com/product/hands-on-scikit-learn-for-
machine-learning-applications-data-science-fundamentals-with-
python-david-paper/
A Python Data
Analyst’s Toolkit
Learn Python and Python-based
Libraries with Applications in Data
Analysis and Statistics
—
Gayathri Rajagopalan
A Python Data
Analyst’s Toolkit
Learn Python and Python-based
Libraries with Applications in Data
Analysis and Statistics
Gayathri Rajagopalan
A Python Data Analyst’s Toolkit: Learn Python and Python-based Libraries with
Applications in Data Analysis and Statistics
Gayathri Rajagopalan
Introduction������������������������������������������������������������������������������������������������������������xix
v
Table of Contents
vi
Table of Contents
Indexing������������������������������������������������������������������������������������������������������������������������������������ 169
Type of an index object�������������������������������������������������������������������������������������������������������� 170
Creating a custom index and using columns as indexes���������������������������������������������������� 171
Indexes and speed of data retrieval������������������������������������������������������������������������������������ 173
Immutability of an index������������������������������������������������������������������������������������������������������ 174
Alignment of indexes����������������������������������������������������������������������������������������������������������� 176
Set operations on indexes��������������������������������������������������������������������������������������������������� 177
Data types in Pandas���������������������������������������������������������������������������������������������������������������� 178
Obtaining information about data types������������������������������������������������������������������������������ 179
Indexers and selection of subsets of data�������������������������������������������������������������������������������� 182
Understanding loc and iloc indexers����������������������������������������������������������������������������������� 183
Other (less commonly used) indexers for data access�������������������������������������������������������� 188
Boolean indexing for selecting subsets of data������������������������������������������������������������������� 192
Using the query method to retrieve data����������������������������������������������������������������������������� 192
Operators in Pandas������������������������������������������������������������������������������������������������������������������ 193
Representing dates and times in Pandas��������������������������������������������������������������������������������� 194
Converting strings into Pandas Timestamp objects������������������������������������������������������������ 195
Extracting the components of a Timestamp object������������������������������������������������������������� 196
Grouping and aggregation�������������������������������������������������������������������������������������������������������� 197
Examining the properties of the groupby object����������������������������������������������������������������� 199
Filtering groups������������������������������������������������������������������������������������������������������������������� 201
Transform method and groupby������������������������������������������������������������������������������������������ 202
Apply method and groupby������������������������������������������������������������������������������������������������� 204
How to combine objects in Pandas������������������������������������������������������������������������������������������� 204
Append method for adding rows����������������������������������������������������������������������������������������� 205
Concat function (adding rows or columns from other objects)������������������������������������������� 207
Join method – index to index���������������������������������������������������������������������������������������������� 210
Merge method – SQL type join based on common columns����������������������������������������������� 211
viii
Table of Contents
ix
Table of Contents
lmplot���������������������������������������������������������������������������������������������������������������������������������� 266
Strip plot������������������������������������������������������������������������������������������������������������������������������ 267
Swarm plot�������������������������������������������������������������������������������������������������������������������������� 268
Catplot��������������������������������������������������������������������������������������������������������������������������������� 269
Pair plot������������������������������������������������������������������������������������������������������������������������������� 270
Joint plot������������������������������������������������������������������������������������������������������������������������������ 272
Summary���������������������������������������������������������������������������������������������������������������������������������� 273
Review Exercises���������������������������������������������������������������������������������������������������������������������� 274
x
Table of Contents
Index��������������������������������������������������������������������������������������������������������������������� 393
xi
About the Author
Gayathri Rajagopalan works for a leading Indian
multinational organization, with ten years of experience
in the software and information technology industry.
She has degrees in computer engineering and business
adminstration, and is a certified Project Management
Professional (PMP). Some of her key focus areas include
Python, data analytics, machine learning, statistics, and
deep learning. She is proficient in Python, Java, and C/C++
programming. Her hobbies include reading, music, and
teaching programming and data science to beginners.
xiii
About the Technical Reviewer
Manohar Swamynathan is a data science practitioner
and an avid programmer, with over 14 years of experience
in various data science related areas that include data
warehousing, Business Intelligence (BI), analytical tool
development, ad hoc analysis, predictive modeling, data
science product development, consulting, formulating
strategy, and executing analytics programs. He’s had a
career covering the life cycle of data across different
domains such as US mortgage banking, retail/ecommerce,
insurance, and industrial IoT. He has a bachelor’s degree
with a specialization in physics, mathematics, and
computers, and a master’s degree in project management. He’s currently living in
Bengaluru, the Silicon Valley of India.
xv
Acknowledgments
This book is a culmination of a year-long effort and would not have been possible
without my family’s support. I am indebted to them for their patience, kindness, and
encouragement.
I would also like to thank my readers for investing their time and money in this book. It is
my sincere hope that this book adds value to your learning experience.
xvii
Introduction
I had two main reasons for writing this book. When I first started learning data science,
I could not find a centralized overview of all the important topics on this subject.
A practitioner of data science needs to be proficient in at least one programming
language, learn the various aspects of data preparation and visualization, and also
be conversant with various aspects of statistics. The goal of this book is to provide
a consolidated resource that ties these interconnected disciplines together and
introduces these topics to the learner in a graded manner. Secondly, I wanted to provide
material to help readers appreciate the practical aspects of the seemingly abstract
concepts in data science, and also help them to be able to retain what they have learned.
There is a section on case studies to demonstrate how data analysis skills can be applied
to make informed decisions to solve real-world challenges. One of the highlights of
this book is the inclusion of practice questions and multiple-choice questions to help
readers practice and apply whatever they have learned. Most readers read a book and
then forget what they have read or learned, and the addition of these exercises will help
readers avoid this pitfall.
The book helps readers learn three important topics from scratch – the Python
programming language, data analysis, and statistics. It is a self-contained introduction
for anybody looking to start their journey with data analysis using Python, as it focuses
not just on theory and concepts but on practical applications and retention of concepts.
This book is meant for anybody interested in learning Python and Python-based libraries
like Pandas, Numpy, Scipy, and Matplotlib for descriptive data analysis, visualization,
and statistics. The broad categories of skills that readers learn from this book include
programming skills, analytical skills, and problem-solving skills.
The book is broadly divided into three parts – programming with Python, data analysis
and visualization, and statistics. The first part of the book comprises three chapters. It
starts with an introduction to Python – the syntax, functions, conditional statements,
data types, and different types of containers. Subsequently, we deal with advanced
concepts like regular expressions, handling of files, and solving mathematical problems
xix
Introduction
with Python. Python is covered in detail before moving on to data analysis to ensure that
the readers are comfortable with the programming language before they learn how to
use it for purposes of data analysis.
The second part of the book, comprising five chapters, covers the various aspects of
descriptive data analysis, data wrangling and visualization, and the respective Python
libraries used for each of these. There is an introductory chapter covering basic concepts
and terminology in data analysis, and one chapter each on NumPy (the scientific
computation library), Pandas (the data wrangling library), and the visualization
libraries (Matplotlib and Seaborn). A separate chapter is devoted to case studies to
help readers understand some real-world applications of data analysis. Among these
case studies is one on air pollution, using data drawn from an air quality monitoring
station in New Delhi, which has seen alarming levels of pollution in recent years. This
case study examines the trends and patterns of major air pollutants like sulfur dioxide,
nitrogen dioxide, and particulate matter for five years, and comes up with insights and
recommendations that would help with designing mitigation strategies.
The third section of this book focuses on statistics, elucidating important principles in
statistics that are relevant to data science. The topics covered include probability, Bayes
theorem, permutations and combinations, hypothesis testing (ANOVA, chi-squared
test, z-test, and t-test), and the use of various functions in the Scipy library to enable
simplification of tedious calculations involved in statistics.
By the end of this book, the reader will be able to confidently write code in Python, use
various Python libraries and functions for analyzing any dataset, and understand basic
statistical concepts and tests. The code is presented in the form of Jupyter notebooks
that can further be adapted and extended. Readers get the opportunity to test their
understanding with a combination of multiple-choice and coding questions. They
also get an idea about how to use the skills and knowledge they have learned to make
evidence-based decisions for solving real-world problems with the help of case studies.
xx
CHAPTER 1
Getting Familiar
with Python
Python is an open source programming language created by a Dutch programmer
named Guido van Rossum. Named after the British comedy group Monty Python,
Python is a high-level, interpreted, open source language and is one of the most sought-
after and rapidly growing programming languages in the world today. It is also the
language of preference for data science and machine learning.
In this chapter, we first introduce the Jupyter notebook – a web application for running
code in Python. We then cover the basic concepts in Python, including data types,
operators, containers, functions, classes and file handling and exception handling, and
standards for writing code and modules.
The code examples for this book have been written using Python version 3.7.3 and
Anaconda version 4.7.10.
T echnical requirements
Anaconda is an open source platform used widely by Python programmers and data
scientists. Installing this platform installs Python, the Jupyter notebook application, and
hundreds of libraries. The following are the steps you need to follow for installing the
Anaconda distribution.
2. Click the installer for your operating system, as shown in Figure 1-1.
The installer gets downloaded to your system.
1
© Gayathri Rajagopalan 2021
G. Rajagopalan, A Python Data Analyst’s Toolkit, https://doi.org/10.1007/978-1-4842-6399-0_1
Chapter 1 Getting Familiar with Python
3. Open the installer (file downloaded in the previous step) and run it.
Please follow the following steps for downloading all the data files used in this book:
Now that we have installed and launched Jupyter, let us understand how to use this
application in the next section.
JupyterLab is the IDE for Jupyter notebooks. Jupyter notebooks are web applications that
run locally on a user’s machine. They can be used for loading, cleaning, analyzing, and
modeling data. You can add code, equations, images, and markdown text in a Jupyter
notebook. Jupyter notebooks serve the dual purpose of running your code as well as
serving as a platform for presenting and sharing your work with others. Let us look at the
various features of this application.
Type “jupyter notebook” in the search bar next to the start menu.
This will open the Jupyter dashboard. The dashboard can be used
to create new notebooks or open an existing one.
Click inside the first cell in your notebook and type a simple line
of code, as shown in Figure 1-4. Execute the code by selecting Run
Cells from the “Cell” menu, or use the shortcut keys Ctrl+Enter.
3
Chapter 1 Getting Familiar with Python
5. Renaming a notebook
Click the default name of the notebook and type a new name, as
shown in Figure 1-6.
Table 1-1 gives some of the familiar icons found in Jupyter notebooks, the corresponding
menu functions, and the keyboard shortcuts.
5
Chapter 1 Getting Familiar with Python
Adding a new cell to a Esc+b (adding a cell below the Insert ➤ Insert Cell
Jupyter notebook current cell), or Esc+a (adding Above or Insert ➤
a cell above the current cell) Insert Cell Below
Running a given cell Ctrl+Enter (to run selected cell); Cell ➤ Run
Shift+Enter (to run selected cell Selected Cells
and insert a new cell)
If you are not sure about which keyboard shortcut to use, go to: Help ➤ Keyboard
Shortcuts, as shown in Figure 1-8.
• Shift+Enter to run the code in the current cell and move to the next
cell.
T ab Completion
This is a feature that can be used in Jupyter notebooks to help you complete the code
being written. Usage of tab completions can speed up the workflow, reduce bugs, and
quickly complete function names, thus reducing typos and saving you from having to
remember the names of all the modules and functions.
For example, if you want to import the Matplotlib library but don’t remember the
spelling, you could type the first three letters, mat, and press Tab. You would see a drop-
down list, as shown in Figure 1-9. The correct name of the library is the second name in
the drop-down list.
7
Chapter 1 Getting Familiar with Python
One commonly used magic command, shown in the following, is used to display
Matplotlib graphs inside the notebook. Adding this magic command avoids the need
to call the plt.show function separately for showing graphs (the Matplotlib library is
discussed in detail in Chapter 7).
CODE:
%matplotlib inline
Magic commands, like timeit, can also be used to time the execution of a script, as shown
in the following.
CODE:
%%timeit
for i in range(100000):
i*i
Output:
16.1 ms ± 283 μs per loop (mean ± std. dev. of 7 runs, 100 loops each)
Now that you understand the basics of using Jupyter notebooks, let us get started with
Python and understand the core aspects of this language.
P
ython Basics
In this section, we get familiar with the syntax of Python, commenting, conditional
statements, loops, and functions.
C
omments
A comment explains what a line of code does, and is used by programmers to help others
understand the code they have written. In Python, a comment starts with the # symbol.
8
Chapter 1 Getting Familiar with Python
Proper spacing and indentation are critical in Python. While other languages like Java
and C++ use brackets to enclose blocks of code, Python uses an indent of four spaces
to specify code blocks. One needs to take care of indents to avoid errors. Applications
like Jupyter generally take care of indentation and automatically add four spaces at the
beginning of a block of code.
Printing
The print function prints content to the screen or any other output device.
CODE:
print("Hello!")
To print multiple lines of code, we use triple quotes at the beginning and end of the
string, for example:
CODE:
Output:
Note that we do not use semicolons in Python to end statements, unlike some other
languages.
The format method can be used in conjunction with the print method for embedding
variables within a string. It uses curly braces as placeholders for variables that are passed
as arguments to the method.
Let us look at a simple example where we print variables using the format method.
9
Chapter 1 Getting Familiar with Python
CODE:
weight=4.5
name="Simi"
print("The weight of {} is {}".format(name,weight))
Output:
The preceding statement can also be rewritten as follows without the format method:
CODE:
Note that only the string portion of the print argument is enclosed within quotes. The name
of the variable does not come within quotes. Similarly, if you have any constants in your
print arguments, they also do not come within quotes. In the following example, a Boolean
constant (True), an integer constant (1), and strings are combined in a print statement.
CODE:
Output:
The format fields can specify precision for floating-point numbers. Floating-point
numbers are numbers with decimal points, and the number of digits after the decimal
point can be specified using format fields as follows.
CODE:
x=91.234566
print("The value of x upto 3 decimal points is {:.3f}".format(x))
Output:
We can specify the position of the variables passed to the method. In this example, we
use position “1” to refer to the second object in the argument list, and position “0” to
specify the first object in the argument list.
10
Chapter 1 Getting Familiar with Python
CODE:
y='Jack'
x='Jill'
print("{1} and {0} went up the hill to fetch a pail of water".format(x,y))
Output:
I nput
The input function accepts inputs from the user. The input provided by the user is stored
as a variable of type String. If you want to do any mathematical calculations with any
numeric input, you need to change the data type of the input to int or float, as follows.
CODE:
Output:
V
ariables and Constants
A constant or a literal is a value that does not change, while a variable contains a value
can be changed. We do not have to declare a variable in Python, that is, specify its data
type, unlike other languages like Java and C/C++. We define it by giving the variable a
name and assigning it a value. Based on the value, a data type is automatically assigned
to it. Values are stored in variables using the assignment operator (=). The rules for
naming a variable in Python are as follows:
• a variable name cannot have spaces
11
Chapter 1 Getting Familiar with Python
Operators
The following are some commonly used operators in Python.
Arithmetic operators: Take two integer or float values, perform an operation, and return
a value.
• **(Exponent)
• %(modulo or remainder),
• //(quotient),
• *(multiplication)
• -(subtraction)
• +(addition)
CODE:
(1+9)/2-3
Output:
2.0
12
Chapter 1 Getting Familiar with Python
In the preceding expression, the operation inside the parenthesis is performed first,
which gives 10, followed by division, which gives 5, and then subtraction, which gives the
final output as 2.
Comparison operators: These operators compare two values and evaluate to a true or
false value. The following comparison operators are supported in Python:
• >: Greater than
• < : Less than
• <=: Less than or equal to
• >=: Greater than or equal to
• == : equality. Please note that this is different from the assignment
operator (=)
• !=(not equal to)
Logical (or Boolean) operators: Are similar to comparison operators in that they
also evaluate to a true or false value. These operators operate on Boolean variables or
expressions. The following logical operators are supported in Python:
Output:
False
CODE:
(2>1) or (1>3)
13
Another random document with
no related content on Scribd:
to about two hundred young priests and theological students on “The
Personal Qualifications for a Minister of Religion.” The address was
in no important respect different from that which would be suitable on
the same subject for an audience of theological students in England
or the United States; nor did its reception and appropriation seem
any less thorough and sincere.
After inspecting the work in drawing and water-colours of which—so
the posted notice read—“An Exhibition is given in honour of ——,”
Mrs. Ladd returned to Tokyo; but I remained to carry out my purpose
of spending a full day and night among my priestly Buddhist friends.
In our many confidential talks while we were in the relations of
teacher and pupil, the latter had avowed his life-work to be the moral
reform and improved mental culture of the priesthood of his sect. It
had then seemed to me a bold, even an audacious undertaking. But
seeming audacity was quite characteristic of the youth of all those
very men who now, in middle life and old-age, are holding the posts
of leadership in Japan in a way to conserve the best results of the
earlier period of more rapid change. Besides, I knew well that my
pupil had the necessary courage and devotion; for he was not only a
priest but also a soldier, and had been decorated for his bravery in
the Chino-Japanese war. And again, toward the close of the Russo-
Japanese war, when he had been called out with the reserves, he
had once more left the position of priestly student and teacher to
take his place at arms in the defence of his country.
How wholesome and thoroughly educative of their whole manhood
was the training which was being given to these young temple boys,
I had abundant reason to know before leaving the Nichiren College
at Osaki. After tea and welcome-addresses by one of the teachers
and two of the pupils, followed by a response by the guest, an
exhibition of one side of this training was given in the large dining-
hall of the school. For as it was in ancient Greece, so it is now in
Japan; arms and music must not be neglected in the preparation to
serve his country of the modern Buddhist priest. Sword-dancing—
one of the chants which accompanied the action being Saigo’s
celebrated “death song”—and a duet performed upon a flute and a
harp constructed by the performer out of split bamboo and strings of
silk, followed by banzais for their guest, concluded the
entertainment.
Of the nine who sat down to dinner that evening in a private room
belonging to another building of the school, four besides the host
were priests of the Nichiren sect. They constituted the body of the
more strictly religious or theological instructors; the courses in
literature and the sciences being taught for the most part by
professors from the Imperial University or from the private university
founded by Japan’s great teacher of youth, the late Mr. Fukuzawa.
Of the priests the most conspicuous and communicative was proud
to inform me that he had been the chaplain of General Noghi at the
siege of Port Arthur. With reference to the criticisms passed at the
time upon that great military leader he said with evident emotion that
General Noghi was “as wise as he was undoubtedly brave.” This
same priest had also interesting stories to tell of his experiences in
China. In speaking of the ignorance of the teachers of religion in that
country he declared, that of the hundreds of Tâoist priests he had
met, the vast majority could not even read the Chinese ideographs
when he wrote them; and none of the numbers he had known could
make any pretence to scholarship. They were quite universally
ignorant, superstitious, and physically and morally filthy. Among the
Buddhist priests in China, however, the case was somewhat better;
for perhaps three or four in every ten could make some pretence of
education; and there were even a very few who were real scholars.
But neither Tâoists nor Buddhists had much influence for good over
the people; and “priest, priest,” was a cry of insult with which to
follow one. As to their sincerity, at one of the Tâoist temples he had
asked for meat and wine, but had been told that none could be had,
because they abstained religiously from both. But when he replied
that he had no scruples against either, but needed them for his
health and wished to pay well for them, both were so quickly
produced he knew they could not have come from far away. (I may
remark in this connection that if the experiences and habits of the
Chinese in Manchuria resemble at all closely the experiences and
customs of the Koreans in their own country, the unwillingness to
furnish accommodations to travelling strangers is caused rather by
the fear of having them requisitioned without pay than to any
scruples, religious or otherwise, as to what they themselves eat and
drink or furnish to others for such purposes).
The same subject which had been introduced at the priests-house,
on occasion of the all-night festival at Ikegami, was now brought
forward again. What had been my impressions received from the
spectacle witnessed at that time? When to the inquiry I made a
similar answer,—namely, that only a portion of the vast crowd
seemed to be sincere worshippers, but that with the exception of a
few rude young men in the procession, who appeared to have had
too much saké, I saw no immoral or grossly objectional features—all
the priests expressed agreement with my views. Where the
superstitions connected with the celebration were not positively
harmful, it was the policy of the reforming and progressive party of
the sect to leave them to die away of themselves as the people at
large became more enlightened.
After a night of sound sleep, Japanese fashion, on the floor of the
study in my pupil’s pretty new home, we rose at six and hastened
across the fields to attend the morning religious services in the
chapel of the school. Here for a full half-hour, or more, what had
every appearance of serious and devout religious worship was held
by the assembled teachers and pupils. All were neatly dressed in
black gowns; no evidences of having shuffled into unbrushed
garments, with toilets only half-done or wholly neglected, were
anywhere to be seen, nor was there the vacant stare, the loud
whisper, the stolen glance at newspaper or text-book; but all
responded to the sutras and intoned the appointed prayers and
portions of the Scriptures, while the time was accented by the not too
loud beating of a musical gong. Certainly, the orderliness and
apparent devotion quite exceeded that of any similar service at
“morning prayers” in the average American college or university.
A brief exhibition of judo, (a modified form of jiujitsu), and of
Japanese fencing, which was carried on in the dining-room while the
head-master was exchanging his priestly for his military dress, in
order to take part in a memorial service to deceased soldiers, at
which General Noghi was expected to be present, terminated my
entertainment at this Buddhist school for the training of temple boys.
As we left the crowd of them who had accompanied us thus far on
the way, and stood shouting banzais on the platform of the station,
there was no room for doubting the heartiness of their friendly feeling
toward the teacher of their teacher; although the two, while sharing
many of the most important religious views, were called by names
belonging to religions so different as Christianity and Buddhism.
The impressions from these two visits to Ikegami regarding the
changes going on in Buddhistic circles in Japan, and in the attitude
of Buddhism toward Christianity, were amply confirmed by
subsequent experiences. At Kyoto, the ancient capital and religious
centre of the empire, I was invited by the Dean of the Theological
Seminary connected with the Nishi Honwangi to address some six
hundred young priests of various sects on the same topic as that on
which the address was given at the Nichiren College near Ikegami. It
should be explained that this temple is under the control of the Shin-
shu, the most numerous and probably the most wealthy sect in the
Empire. The high priest of this sect is an hereditary count and
therefore a member of the House of Peers. He is also a man of
intelligence and of a wide-spreading interest in religion. At the time of
my visit, indeed, the Count was absent on a missionary tour in
China. This address also was listened to with the same respectful
attention by the several hundred Buddhist priests who had gathered
at the temple of Nishi Honwangi. Here again Mrs. Ladd and I were
made the recipients of the same courteous and unique hospitality.
Before the lecture began, we were entertained in the room which
had been distinguished for all time in the estimate of the nation by
the fact that His Majesty the Emperor held within its walls the first
public reception ever granted to his subjects by the Mikado; and after
the lecture we were further honoured by being the first outsiders ever
invited to a meal with the temple officers within one of the temple
apartments.
Later on at Nagoya, further evidence was afforded of the important
fact that the old-time religious barriers are broken down or are being
overridden, wherever the enlightenment and moral welfare of the
people seem likely to be best served in this way. Now Nagoya has
hitherto been considered one of the most conservative and even
bigoted Buddhist centres in all Japan. Yet a committee composed of
Buddhists and of members of the Young Men’s Christian Association
united in arrangements for a course of lectures on education and
ethics. This was remarked upon as the first instance of anything of
the sort in the history of the city.
When we seek for the causes which have operated to bring about
these important and hopeful changes in the temper and practises of
the Buddhism which is fast gaining currency and favour in Japan, we
are impressed with the belief that the greatest of them is the
introduction of Christianity itself. This influence is obvious in the
following three essential ways. Christian conceptions and doctrines
are modifying the tenets of the leading Buddhistic thinkers in Japan.
As I listened for several hours to his exposition of his conception of
the Divine Being, the divine manner of self-revelation, and of his
thoughts about the relations of God and man, by one of the most
notable theologians of the Shin Shu (the sect which I have already
spoken of as the most popular in Japan), I could easily imagine that
the exponent was one of the Alexandrine Church-Fathers, Origen or
Clement, discoursing of God the Unrevealed and of the Logos who
was with God and yet who became man. But Buddhism is also giving
much more attention than formerly to raising the moral standards of
both priests and people. It is sharing in the spirit of ethical quickening
and revival which is so important an element of the work of Christian
missions abroad, but which is alas! so woefully neglected in the so-
called Christian nations at home. Japanese Buddhism is feeling now
much more than formerly the obligation of any religion which asks
the adherence and support of the people, to help the people, in a
genuine and forceful way, to a nobler and better way of living.
Hitherto in Japan it has been that peculiar development of Confucian
ethics called Bushidō, which has embodied and cultivated the nobler
moral ideals. Religion, at least in the form which Buddhism has taken
in Japan, has had little to do with inspiring and guiding men in the life
which is better and best, here and now. But as its superstitions with
regard to the future are falling away and are ceasing practically to
influence the body of the people, there are some gratifying signs that
its influence upon the spiritual interests of the present is becoming
purer and stronger.
That Buddhism is improving its means of educating its followers, and
is feeling powerfully the quickening of the national pulse, due to the
advancing strides in educational development, is obvious enough to
any one able to compare its condition to-day with its condition not
more than a score of years ago. There are, of course, in the ranks of
all the Buddhist sects leaders who are ready to cry out against
heresies and the mischief of changes concealed under the guise of
reforms. The multitudes of believers are still far below the desirable
standard of either intelligence in religious matters, or of morals as
controlled by religious motives. But the old days of stagnation and
decay seem to be passing away; and the outlook now is that the
foreign religion, instead of speedily destroying the older native
religion, will have helped it to assume a new and more vigorous and
better form of life.
As the period of more bitter conflict and mutual denunciation gives
way to a period of more respectful and friendly, and even co-
operative attitude in advancing the welfare of the nation, the future of
both Buddhism and Christianity in Japan affords a problem of more
complicated and doubtful character. The nation is awakening to its
need of morals and religion,—in addition to a modern army and
navy, and to an equipment for teaching and putting to practical uses,
the physical sciences,—as never before. The awakening is
accompanied there, as elsewhere in the modern world, by a thirst for
reality. Whatever can satisfy this thirst, however named, will find
acceptance and claim the allegiance of both the thoughtful and the
multitudes of the common people; for in Japan, as elsewhere in the
modern world, men are not easily satisfied or permanently satisfied
with mere names.
CHAPTER X
HIKONÉ AND ITS PATRIOT MARTYR
Among the feudal towns of Japan which can boast of a fine castle
still standing, and of an illustrious lord as its former occupant, there
are few that can rival Hikoné. Picturesquely seated on a wooded hill
close to the shores of Lake Biwa, with the blue waters and almost
equally blue surrounding mountains in full sight, the castle enjoys the
advantages of strength combined with beauty; while the lords of the
castle are descended from a very ancient family, which was awarded
its territory by the great Iyéyasu, the founder of the Tokugawa
Shōgunate, in return for the faithful services of their ancestor,
Naomasa, in bringing the whole land under the Tokugawa rule. They
therefore belonged to the rank of the Fudai Daimio, or Retainer
Barons, from whom alone the Roju, or Senators, and other officers of
the first class could be appointed. Of these lords of Hikoné much the
most distinguished was Naosuké, who signed the treaty with the
United States negotiated in 1857 and 1858. And yet, so strange are
the vicissitudes of history, and so influential the merely incidental
occurrences in human affairs, that only a chance visit of the Mikado
saved this fine feudal castle from the “general ruin of such buildings
which accompanied the mania for all things European and the
contempt of their national antiquities, whereby the Japanese were
actuated during the past two decades of the present régime.” Nor
was it until recent years that Baron Ii Naosuké’s memory has been
rescued from the charge of being a traitor to his country and a
disobedient subject of its Emperor, and elevated to a place of
distinction and reverence, almost amounting to worship, as a clear-
sighted and far-seeing statesman and patriot.
“PICTURESQUELY SEATED ON A WOODED HILL”
However we may regard the unreasonableness of either of these two
extreme views of Naosuké’s character, one thing seems clear. In
respect to the laying of foundations for friendly relations between the
United States and Japan, we owe more to this man than to any other
single Japanese. No one can tell what further delays and resulting
irritation, and even accession of blood-shed, might have taken place
in his time had it not been for his courageous and firm position
toward the difficult problem of admitting foreigners to trade and to
reside within selected treaty-ports of Japan. This position cost him
his life. For a generation, or more, it also cost him what every true
Japanese values far more highly than life; it cost the reputation of
being loyal to his sovereign and faithful to his country’s cause. Yet
not five Americans in a million, it is likely, ever heard the name of
Baron Ii Kamon-no-Kami, who as Tairō, or military dictator, shared
the responsibility and should share the fame of our now celebrated
citizen, then Consul General at Shimoda, Townsend Harris. My
purpose, therefore, is two-fold: I would gladly “have the honour to
introduce” Ii Naosuké to a larger audience of my own countrymen;
and by telling the story of an exceedingly interesting visit to Hikoné, I
would equally gladly introduce to the same audience certain ones of
the great multitude of Japanese who still retain the knightly courtesy,
intelligence and high standards of living—though in their own way—
which characterised the feudal towns of the “Old Japan,” now so
rapidly passing away.
Baron Ii Naosuké, better known in foreign annals as Ii Kamon-no-
Kami, was his father’s fourteenth son. He was born November 30,
1815. The father was the thirteenth feudal lord from that Naomasa
who received his fief from the great Iyéyasu. Since the law of
primogeniture—the only exceptions being cases of insanity or bodily
defect—was enforced throughout the Empire, the early chances that
Naosuké would ever become the head of the family and lord of
Hikoné, seemed small indeed. But according to the usage of the Ii
clan, all the sons except the eldest were either given as adopted
sons to other barons, or were made pensioned retainers of their
older brother. All his brothers, except the eldest, had by adoption
become the lords of their respective clans. But from the age of
seventeen onward, Naosuké was given a modest pension and
placed in a private residence. He thus enjoyed years of opportunity
for training in arms, literature, and reflective study, apart from the
corrupting influences of court life and the misleading temptations to
the exercise of unrestricted authority—both of which are so injurious
to the character of youth. Moreover, he became acquainted with the
common people. That was also true of him, which has been true of
so many of the great men of Japan down to the present time. He
made his friend and counsellor of a man proficient in the military and
literary education of the day. And, indeed, it has been the great
teachers who, more than any other class, through the shaping of
character in their pupils, have influenced mankind to their good. It
was Nakagawa Rokurō who showed to Naosuké, when a young
man, the impossibility of the further exclusion of Japan from foreign
intercourse. It was he also who “influenced the future Tairō to make a
bold departure from the old traditions” of the country.
On the death, without male issue, of his oldest brother, Naosuké was
declared heir-apparent of the Hikoné Baronetcy. And on Christmas
day of 1850 he was publicly authorised by the Shōgunate to assume
the lordly title of Kamon-no-Kami. It is chiefly through the conduct of
the man when, less than a decade later, he came to the position
which was at the same time the most responsible, difficult and
honourable but dangerous of all possible appointments in “Old
Japan,” that the character of Baron Ii must be judged. On the side of
sentiment—and only when approached from this side can one
properly appreciate the typical knightly character of Japanese
feudalism—we may judge his patriotism by this poem from his own
hand: