0% found this document useful (0 votes)
115 views91 pages

Python in Excel Boost Your Data Analysis and Automation With Powerful Python Scripts Hayden Van Der Post Download

The document discusses the integration of Python with Excel, highlighting its benefits for data analysis, automation, and advanced calculations. It covers key aspects such as data manipulation, task automation, and visualization techniques, demonstrating how Python enhances Excel's capabilities. The document also traces the historical context of this integration and outlines future prospects for deeper collaboration between the two tools.

Uploaded by

morelzilkadq
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
115 views91 pages

Python in Excel Boost Your Data Analysis and Automation With Powerful Python Scripts Hayden Van Der Post Download

The document discusses the integration of Python with Excel, highlighting its benefits for data analysis, automation, and advanced calculations. It covers key aspects such as data manipulation, task automation, and visualization techniques, demonstrating how Python enhances Excel's capabilities. The document also traces the historical context of this integration and outlines future prospects for deeper collaboration between the two tools.

Uploaded by

morelzilkadq
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 91

Python In Excel Boost Your Data Analysis And

Automation With Powerful Python Scripts Hayden


Van Der Post download

https://ebookbell.com/product/python-in-excel-boost-your-data-
analysis-and-automation-with-powerful-python-scripts-hayden-van-
der-post-57429152

Explore and download more ebooks at ebookbell.com


Here are some recommended products that we believe you will be
interested in. You can click the link to download.

Python In Excel Advanced Mastering Data Analysis And Financial


Modeling With Python Automation In Excel Van Der Post

https://ebookbell.com/product/python-in-excel-advanced-mastering-data-
analysis-and-financial-modeling-with-python-automation-in-excel-van-
der-post-57609808

Working With Excel Files In Python Clinton W Brownley

https://ebookbell.com/product/working-with-excel-files-in-python-
clinton-w-brownley-10808858

Working With Excel Files In Python Brownley Clinton W

https://ebookbell.com/product/working-with-excel-files-in-python-
brownley-clinton-w-61182750

The Python Advantage Python For Excel In 2024 Hayden Van Der Post

https://ebookbell.com/product/the-python-advantage-python-for-excel-
in-2024-hayden-van-der-post-54837502
Advanced Excel For Financial Modelling Integrating Python For
Nextlevel Analysis A Comprehensive Guide To The Implementation Of
Python In Financial Analysis Van Der Post

https://ebookbell.com/product/advanced-excel-for-financial-modelling-
integrating-python-for-nextlevel-analysis-a-comprehensive-guide-to-
the-implementation-of-python-in-financial-analysis-van-der-
post-61899020

Python In A Nutshell A Desktop Quick Reference Sixth Early Release 4th


Edition Alex Martelli

https://ebookbell.com/product/python-in-a-nutshell-a-desktop-quick-
reference-sixth-early-release-4th-edition-alex-martelli-47325054

Python In Easy Steps 2nd Edition Mike Mcgrath

https://ebookbell.com/product/python-in-easy-steps-2nd-edition-mike-
mcgrath-50200318

Python In Power Bi Unleash The Power Of Python For Dynamic Data


Analysis A Comprehensive Guide To Data Visualization Hayden Van Der
Post Vincent Bisette

https://ebookbell.com/product/python-in-power-bi-unleash-the-power-of-
python-for-dynamic-data-analysis-a-comprehensive-guide-to-data-
visualization-hayden-van-der-post-vincent-bisette-57457014

Python In A Nutshell Second Alex Martelli

https://ebookbell.com/product/python-in-a-nutshell-second-alex-
martelli-2498222
PYTHON IN EXCEL

Hayden Van Der Post

Reactive Publishing
CONTENTS

Title Page
Chapter 1: Introduction to Python and Excel Integration
Chapter 2: Setting Up the Environment
Chapter 3: Basic Python Scripting for Excel
Chapter 4: Excel Object Model and Python
Chapter 5: Data Analysis with Python in Excel
Chapter 6: Visualization Tools and Techniques
Chapter 7: Advanced Data Manipulation
Chapter 8: Automation and Scripting
Chapter 9: Py Function in Excel
CHAPTER 1:
INTRODUCTION TO
PYTHON AND EXCEL
INTEGRATION
Understanding the symbiotic relationship between Python and Excel is
paramount in leveraging the full potential of both tools. Excel, a stalwart of
data manipulation, visualization, and analysis, is ubiquitous in business
environments. Python, on the other hand, brings unparalleled versatility and
efficiency to data handling tasks. Integrating these two can significantly
enhance your data processing capabilities, streamline workflows, and open
up new possibilities for advanced analytics.

The Foundation: Why Integrate Python with Excel?

Excel is renowned for its user-friendly interface and powerful built-in


functionalities. However, it has limitations when dealing with large
datasets, performing complex calculations, or automating repetitive tasks.
Python complements Excel by offering extensive libraries such as Pandas,
NumPy, and Matplotlib, which are designed for data manipulation,
numerical computations, and visualization. This integration can mitigate
Excel's limitations, providing a robust platform for comprehensive data
analysis.

Key Integration Points

1. Data Manipulation:
Python excels in data manipulation with its Pandas library, which simplifies
tasks like filtering, grouping, and aggregating data. This can be particularly
useful in cleaning and preparing data before analysis.

```python
import pandas as pd

Reading Excel file


df = pd.read_excel('data.xlsx')

Data manipulation
df_cleaned = df.dropna().groupby('Category').sum()

Writing back to Excel


df_cleaned.to_excel('cleaned_data.xlsx')
```

2. Automating Tasks:
Python scripts can automate repetitive tasks that would otherwise require
manual intervention in Excel. For instance, generating monthly reports,
sending automated emails with attachments, or formatting sheets can all be
handled seamlessly with Python.

```python
import pandas as pd
from openpyxl import load_workbook

Load workbook and sheet


workbook = load_workbook('report.xlsx')
sheet = workbook.active
Automate formatting
for row in sheet.iter_rows(min_row=2, max_row=sheet.max_row,
min_col=1, max_col=sheet.max_column):
for cell in row:
if cell.value < 0:
cell.font = Font(color="FF0000")

workbook.save('formatted_report.xlsx')
```

3. Advanced Calculations:
While Excel is proficient with formulas, Python can handle more complex
calculations and modeling. For example, running statistical models or
machine learning algorithms directly from Excel can be accomplished with
Python libraries like scikit-learn.

```python
from sklearn.linear_model import LinearRegression
import numpy as np

Sample data
X = np.array([5, 15, 25, 35, 45, 55]).reshape((-1, 1))
y = np.array([5, 20, 14, 32, 22, 38])

Create a regression model


model = LinearRegression().fit(X, y)

Making predictions
predictions = model.predict(X)

Exporting to Excel
output = pd.DataFrame({'X': X.flatten(), 'Predicted_Y': predictions})
output.to_excel('predicted_data.xlsx')
```

4. Visualizations:
Python’s visualization libraries, such as Matplotlib and Seaborn, can
produce more sophisticated and customizable charts and graphs than Excel.
These visuals can then be embedded back into Excel for reporting purposes.

```python
import matplotlib.pyplot as plt

df = pd.read_excel('data.xlsx')

Create a plot
plt.figure(figsize=(10, 5))
plt.plot(df['Date'], df['Sales'])
plt.title('Sales Over Time')
plt.xlabel('Date')
plt.ylabel('Sales')

Save plot
plt.savefig('sales_plot.png')

Insert into Excel


from openpyxl.drawing.image import Image
img = Image('sales_plot.png')
sheet.add_image(img, 'E1')
workbook.save('report_with_chart.xlsx')
```
Historical Context of Python-Excel Integration

The fusion of Python and Excel is not merely a modern convenience; it is


the culmination of an evolving relationship between two powerful tools that
have metamorphosed over the years. Understanding their intertwined
history provides valuable insights into their current capabilities and future
potential.

Early Days of Spreadsheets and Programming Languages

In the late 1970s and early 1980s, electronic spreadsheets revolutionized the
way businesses handled data. VisiCalc, the first widely used spreadsheet
software, debuted in 1979, providing a digital alternative to manual ledger
sheets. It was followed by Lotus 1-2-3 in the early 1980s, which became a
staple in the corporate world due to its integrated charting and database
capabilities. Microsoft Excel entered the scene in 1985, eventually
overtaking its predecessors to become the gold standard of spreadsheet
applications.

During this period, programming languages were also evolving. BASIC and
COBOL were among the early languages used for business applications.
However, these languages were not designed for data manipulation on
spreadsheets, which created a gap that would eventually be filled by more
specialized tools.

The Rise of Python

Python, conceived in the late 1980s by Guido van Rossum, was not initially
targeted at data analysis or spreadsheet manipulation. Its design philosophy
emphasized code readability and simplicity, which made it an ideal choice
for general-purpose programming. Over the years, Python's ecosystem
expanded, and by the early 2000s, it had gained traction in various domains,
from web development to scientific computing.

The emergence of libraries such as NumPy in 2006 and Pandas in 2008


marked a turning point. These libraries provided powerful tools for
numerical computations and data manipulation, respectively. Python began
to gain prominence as a language for data analysis, challenging the
dominance of established tools like MATLAB and R.

Initial Attempts at Integration

As Python grew in popularity, the desire to integrate its capabilities with


Excel became more pronounced. Early attempts at integration primarily
involved using VBA (Visual Basic for Applications), which had been
Excel’s built-in programming language since 1993. VBA allowed for some
level of automation and custom functionality within Excel, but it had
limitations in handling large datasets and performing complex
computations.

To bridge this gap, developers began creating add-ins and libraries to enable
Python scripts to interact with Excel. One of the earliest and most notable
tools was PyXLL, introduced around 2009. PyXLL allowed Python
functions to be called from Excel cells, enabling more complex calculations
and data manipulations directly within the spreadsheet environment.

The Evolution of Integration Tools

The 2010s saw significant advancements in the integration of Python and


Excel. The development of libraries such as OpenPyXL and XlsxWriter
enhanced the ability to read from and write to Excel files using Python.
These libraries provided more control over Excel tasks, allowing for
automation of repetitive processes and facilitating the generation of
complex, dynamic reports.

Another critical development was the introduction of Jupyter Notebooks.


Initially part of the IPython project, Jupyter Notebooks provided an
interactive computing environment that supported multiple programming
languages, including Python. This innovation made it easier for data
scientists and analysts to write, test, and share Python code, including code
that interacted with Excel.
Modern Solutions and Microsoft’s Embrace of Python

The integration landscape reached new heights in the late 2010s and early
2020s, as Python's role in data science became undeniable. Microsoft,
recognizing the demand for Python integration, introduced several
initiatives to facilitate this synergy. The Microsoft Azure Machine Learning
service, for example, allowed users to leverage Python for advanced
analytics directly within the cloud-based Excel environment.

In 2019, Microsoft took a significant step by integrating Python as a


scripting option in Excel through the Python integration within Power
Query Editor. This feature enables users to run Python scripts for data
transformation tasks, providing a seamless bridge between Excel’s familiar
interface and Python’s powerful data processing capabilities.

Moreover, tools like Anaconda and PyCharm have made it easier to manage
Python environments and dependencies, further simplifying the process of
integrating Python with Excel. The introduction of xlwings, a library that
gained popularity in the mid-2010s, offered a more Pythonic way to interact
with Excel, supporting both Windows and Mac.

Current State and Future Prospects

Today, the integration of Python and Excel is more accessible and powerful
than ever. Professionals across various industries leverage this combination
to enhance their workflows, automate mundane tasks, and derive deeper
insights from their data. The use of Python within Excel is no longer a
fringe activity but a mainstream practice endorsed by major corporations
and educational institutions.

Looking forward, the trend towards deeper integration is likely to continue.


As Python continues to evolve and Excel incorporates more features to
support Python scripting, the boundary between these two tools will blur
further. The future promises even more seamless interactions, richer
functionalities, and expanded capabilities, cementing Python and Excel as
indispensable partners in data analysis and business intelligence.
Benefits of Using Python in Excel

The integration of Python with Excel brings a wealth of advantages to the


table, transforming how data is processed, analyzed, and visualized. By
leveraging the strengths of both technologies, users can enhance
productivity, improve accuracy, and unlock new analytical capabilities. This
section delves into the multifaceted benefits of using Python in Excel,
illuminating why this combination is increasingly favored by professionals
across various industries.

Enhanced Data Processing Capabilities

One of the standout benefits of using Python in Excel is the significant


enhancement in data processing capabilities. Excel, while powerful, can
struggle with large datasets and complex calculations. Python, on the other
hand, excels (pun intended) at handling vast amounts of data efficiently. By
leveraging libraries such as Pandas and NumPy, users can perform
advanced data manipulation and analysis tasks that would be cumbersome
or even impossible to achieve with Excel alone.

For example, consider a scenario where you need to clean and preprocess a
dataset containing millions of rows. In Excel, this task could be
prohibitively slow and prone to errors. However, with Python, you can
write a few lines of code to automate the entire process, ensuring
consistency and accuracy. Here's a simple demonstration using Pandas to
clean a dataset:

```python
import pandas as pd

Load the dataset into a pandas DataFrame


data = pd.read_excel('large_dataset.xlsx')

Remove rows with missing values


cleaned_data = data.dropna()
Convert data types and perform additional cleaning
cleaned_data['Date'] = pd.to_datetime(cleaned_data['Date'])
cleaned_data['Value'] = cleaned_data['Value'].astype(float)

Save the cleaned dataset back to Excel


cleaned_data.to_excel('cleaned_dataset.xlsx', index=False)
```

This script, executed within Excel, can process the dataset in a fraction of
the time and with greater accuracy than manual efforts.

Automation of Repetitive Tasks

Python's scripting capabilities allow for the automation of repetitive tasks,


which is a game-changer for Excel users who often find themselves
performing the same operations repeatedly. Whether it's updating reports,
generating charts, or conducting routine data transformations, Python can
streamline these processes, freeing up valuable time for more strategic
activities.

For instance, imagine needing to update a weekly sales report. Instead of


manually copying data, creating charts, and formatting everything, you can
write a Python script to automate the entire workflow. Here's an example of
automating report generation:

```python
import pandas as pd
import matplotlib.pyplot as plt

Load sales data


sales_data = pd.read_excel('sales_data.xlsx')

Create a pivot table summarizing sales by region and product


summary = sales_data.pivot_table(index='Region', columns='Product',
values='Sales', aggfunc='sum')

Generate a bar chart


summary.plot(kind='bar', figsize=(10, 6))
plt.title('Weekly Sales Report')
plt.ylabel('Sales Amount')
plt.tight_layout()

Save the chart and summary to Excel


plt.savefig('sales_report.png')
summary.to_excel('sales_summary.xlsx')
```

Embedding such a script in Excel, you can update your sales report with a
single click, ensuring consistency and reducing the risk of human error.

Advanced Data Analysis

The analytical power of Python vastly surpasses that of Excel, especially


when it comes to statistical analysis and machine learning. Python boasts an
extensive range of libraries, such as SciPy for scientific computing,
statsmodels for statistical modeling, and scikit-learn for machine learning.
These libraries enable users to perform sophisticated analyses that would be
difficult or impossible to execute within the confines of Excel.

For example, let's say you want to perform a linear regression analysis to
predict future sales based on historical data. With Python, you can easily
implement this using scikit-learn:

```python
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt

Load historical sales data


data = pd.read_excel('historical_sales.xlsx')

Prepare the data for modeling


X = data[['Marketing_Spend', 'Store_Openings']] Features
y = data['Sales'] Target variable

Split the data into training and testing sets


X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,
random_state=42)

Create and train the model


model = LinearRegression()
model.fit(X_train, y_train)

Make predictions
predictions = model.predict(X_test)

Visualize the results


plt.scatter(y_test, predictions)
plt.xlabel('Actual Sales')
plt.ylabel('Predicted Sales')
plt.title('Linear Regression Model')
plt.show()
```
This script not only performs the regression analysis but also visualizes the
results, providing clear insights into the model's performance.

Improved Data Visualization

While Excel offers a range of charting options, Python's visualization


libraries, such as Matplotlib, Seaborn, and Plotly, provide far more
flexibility and customization. These libraries allow for the creation of
highly detailed and aesthetically pleasing charts and graphs that can be
tailored to meet specific presentation needs.

For example, creating a complex visualization like a heatmap of sales data


across different regions and products is straightforward with Python:

```python
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

Load sales data


sales_data = pd.read_excel('sales_data.xlsx')

Create a pivot table


pivot_table = sales_data.pivot_table(index='Region', columns='Product',
values='Sales', aggfunc='sum')

Generate a heatmap
plt.figure(figsize=(12, 8))
sns.heatmap(pivot_table, annot=True, fmt=".1f", cmap="YlGnBu")
plt.title('Sales Heatmap')
plt.show()
```
This heatmap offers a clear, visual representation of sales performance
across regions and products, making it easier to identify trends and outliers.

Seamless Integration with Other Tools

Python's versatility extends beyond Excel, allowing for seamless integration


with other data-related tools and platforms. Whether you are pulling data
from a web API, interfacing with a database, or incorporating machine
learning models, Python serves as a bridge that connects these disparate
systems.

For instance, you may need to retrieve data from an online source, process
it, and update an Excel spreadsheet. Here's how you can achieve this using
Python:

```python
import pandas as pd
import requests

Retrieve data from a web API


url = 'https://api.example.com/data'
response = requests.get(url)
data = response.json()

Convert the data to a pandas DataFrame


df = pd.DataFrame(data)

Perform some data processing


df['Processed_Column'] = df['Original_Column'] * 1.1

Save the processed data to Excel


df.to_excel('processed_data.xlsx', index=False)
```

This script demonstrates how Python can pull data from an API, process it,
and update an Excel file, showcasing the seamless integration capabilities.

Enhanced Collaboration and Reproducibility

Python scripts can be shared easily, ensuring that data processing


workflows are reproducible and collaborative. Unlike Excel macros, which
can be opaque and difficult to understand, Python code tends to be more
transparent and easier to document. This transparency fosters better
collaboration within teams and ensures that analyses can be reproduced and
verified.

Collaborative platforms like GitHub and Jupyter Notebooks further enhance


this capability by enabling version control and interactive code sharing. For
example, you can store your Python scripts on GitHub, allowing team
members to contribute to and modify the code.

The benefits of using Python in Excel are manifold, ranging from enhanced
data processing and automation to advanced data analysis and improved
visualization. By integrating Python with Excel, users can unlock new
levels of productivity, accuracy, and analytical power. This synergy not only
streamlines workflows but also opens up new possibilities for data-driven
decision-making, making it an invaluable asset in the modern data
landscape.

Key Features of Python and Excel

The confluence of Python and Excel has revolutionized data handling,


analysis, and visualization. Each possesses unique features that, when
integrated, amplify their individual strengths, offering unparalleled
advantages to users. This section delves into the key features of both Python
and Excel, highlighting how their synergy transforms data-driven tasks.
Python: The Powerhouse of Versatility

Python’s robust features make it a preferred language for data science,


machine learning, and automation. Let's explore the pivotal elements that
contribute to its widespread adoption.

1. Comprehensive Libraries and Frameworks

Python boasts a rich ecosystem of libraries and frameworks that cater to


diverse data-related tasks. These libraries simplify complex operations,
making Python an indispensable tool for data scientists and analysts.

- Pandas: This library is pivotal for data manipulation and analysis. It


provides data structures like DataFrames that are ideal for handling large
datasets efficiently.
- NumPy: Essential for numerical computations, NumPy offers support for
large multi-dimensional arrays and matrices, along with a collection of
mathematical functions.
- Matplotlib and Seaborn: These libraries facilitate advanced data
visualization. Matplotlib offers extensive charting capabilities, while
Seaborn simplifies the creation of statistical graphics.
- scikit-learn: A go-to library for machine learning, scikit-learn provides
tools for data mining and data analysis, making it easier to build and
evaluate predictive models.

2. Simple and Readable Syntax

Python's syntax is designed to be straightforward and readable, which


reduces the learning curve for beginners. Its simplicity allows users to focus
on solving problems rather than grappling with complex syntax. For
instance, consider the following Python code to calculate the sum of a list
of numbers:

```python
numbers = [1, 2, 3, 4, 5]
total = sum(numbers)
print(total)
```

This code is intuitive and easy to understand, demonstrating Python’s user-


friendly nature.

3. Extensive Community Support

Python has a thriving community that continuously contributes to its


development. This support network ensures that users have access to a
wealth of resources, including tutorials, forums, and documentation.
Whether you're troubleshooting an issue or exploring new functionalities,
the Python community is a valuable asset.

4. Cross-Platform Compatibility

Python is cross-platform, meaning it runs seamlessly on various operating


systems like Windows, macOS, and Linux. This versatility allows users to
develop and deploy Python applications in diverse environments without
compatibility concerns.

Excel: The Ubiquitous Spreadsheet Tool

Excel's widespread usage stems from its powerful features that cater to a
variety of data management and analysis needs. Its user-friendly interface
and extensive functionality make it a staple in business, finance, and
academia.

1. Intuitive Interface and Functionality

Excel's grid-based interface is intuitive, allowing users to enter, organize,


and manipulate data with ease. Its built-in functions support a wide range of
operations, from simple arithmetic to complex financial calculations. For
instance, the SUM function facilitates quick aggregation of numbers:

```excel
=SUM(A1:A10)
```

2. Powerful Data Visualization Tools

Excel offers a variety of charting options, enabling users to create visual


representations of data. From bar charts and line graphs to pivot charts and
scatter plots, Excel provides tools to visualize trends and patterns
effectively.

3. Pivot Tables

Pivot tables are one of Excel's most powerful features. They enable users to
summarize and analyze large datasets dynamically. With pivot tables, you
can quickly generate insights by rearranging and categorizing data, making
it easier to identify trends and anomalies.

4. Integrated Functions and Add-Ins

Excel supports a vast array of built-in functions for data analysis, statistical
operations, and financial modeling. Additionally, users can enhance Excel's
capabilities through add-ins like Power Query and Power Pivot, which offer
advanced data manipulation and analysis features.

Synergy of Python and Excel: Unleashing Potential

The integration of Python with Excel marries Python’s computational


power with Excel's user-friendly interface, creating a potent combination
for data professionals.
1. Enhanced Data Processing

Python’s ability to handle large datasets and perform complex calculations


complements Excel’s data management capabilities. By embedding Python
scripts within Excel, users can automate data processing tasks, thus
enhancing efficiency and accuracy. Consider this example where Python is
used to clean data within Excel:

```python
import pandas as pd

Load data from Excel


data = pd.read_excel('data.xlsx')

Clean data
cleaned_data = data.drop_duplicates().dropna()

Save cleaned data back to Excel


cleaned_data.to_excel('cleaned_data.xlsx', index=False)
```

This script automates data cleaning, reducing the time and effort required to
prepare data for analysis.

2. Advanced Analytics and Machine Learning

Python’s extensive libraries for statistical analysis and machine learning


expand Excel’s analytical capabilities. Users can build predictive models,
perform regression analysis, and implement machine learning algorithms
within Excel, thus elevating the quality and depth of their analyses.

Here’s an example of using Python for linear regression analysis in Excel:


```python
import pandas as pd
from sklearn.linear_model import LinearRegression

Load dataset
data = pd.read_excel('sales_data.xlsx')

Prepare data
X = data[['Marketing_Spend', 'Store_Openings']]
y = data['Sales']

Train model
model = LinearRegression()
model.fit(X, y)

Make predictions
predictions = model.predict(X)

Save predictions to Excel


data['Predicted_Sales'] = predictions
data.to_excel('predicted_sales.xlsx', index=False)
```

3. Superior Data Visualization

Python’s visualization libraries offer advanced charting capabilities,


enabling the creation of highly customized and interactive plots that go
beyond Excel’s native charting options. This functionality is particularly
useful for creating detailed and visually appealing reports.

Consider this example of creating a seaborn heatmap within Excel:


```python
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

Load data
data = pd.read_excel('sales_data.xlsx')

Create pivot table


pivot_table = data.pivot_table(index='Region', columns='Product',
values='Sales', aggfunc='sum')

Generate heatmap
plt.figure(figsize=(10, 8))
sns.heatmap(pivot_table, annot=True, cmap='coolwarm')
plt.title('Sales Heatmap')

Save heatmap to Excel


plt.savefig('sales_heatmap.png')
```

4. Streamlined Automation

Integrating Python with Excel allows for the automation of repetitive tasks,
such as data entry, report generation, and data validation. This not only
saves time but also ensures consistency and reduces the likelihood of
human error.

For example, automating a weekly sales report can streamline the process
significantly:
```python
import pandas as pd
import matplotlib.pyplot as plt

Load sales data


data = pd.read_excel('weekly_sales.xlsx')

Generate summary
summary = data.groupby('Region').sum()

Create bar chart


summary.plot(kind='bar')
plt.title('Weekly Sales Summary')
plt.savefig('weekly_sales_summary.png')

Save summary to Excel


summary.to_excel('weekly_sales_summary.xlsx')
```

5. Seamless Integration with Other Tools

Python’s ability to interface with various databases, APIs, and web services
further enhances Excel’s functionality. Users can pull data from external
sources, perform complex transformations, and update Excel spreadsheets,
creating a seamless workflow.

Here’s an example of retrieving data from a web API and updating an Excel
spreadsheet:

```python
import pandas as pd
import requests

Fetch data from API


response = requests.get('https://api.example.com/data')
data = response.json()

Convert to DataFrame
df = pd.DataFrame(data)

Save to Excel
df.to_excel('api_data.xlsx', index=False)
```

This script demonstrates how Python can augment Excel’s capabilities by


integrating external data sources into the workflow.

The key features of Python and Excel, when integrated, create a powerful
toolset for data processing, analysis, and visualization. Python’s
computational prowess and Excel’s user-friendly interface complement
each other, providing users with the best of both worlds. By leveraging the
strengths of both technologies, professionals can achieve greater efficiency,
accuracy, and depth in their data-driven tasks, making Python-Excel
integration an invaluable asset in the modern data landscape.

Common Use Cases for Python in Excel

Python's versatility and Excel's widespread adoption make them a powerful


duo, especially in data-centric roles. By integrating Python with Excel, you
can automate repetitive tasks, perform complex data analysis, create
dynamic visualizations, and much more. This section delves into some
common use cases where Python can significantly enhance Excel's
capabilities, transforming how you work with data.

1. Data Cleaning and Preprocessing

Data cleaning is often the most time-consuming part of any data analysis
project. Python excels in this area, offering a wide range of tools to
automate and streamline the process.

1. Removing Duplicates

In Excel, removing duplicates can be a tedious task, especially with large


datasets. Using Python, you can efficiently remove duplicates with a few
lines of code.

```python
import pandas as pd

Read data from Excel


df = pd.read_excel('data.xlsx')

Remove duplicates
df_cleaned = df.drop_duplicates()

Write cleaned data back to Excel


df_cleaned.to_excel('cleaned_data.xlsx', index=False)
```

2. Handling Missing Values

Python provides straightforward methods to handle missing values, which


can be cumbersome to manage directly in Excel.
```python
Fill missing values with a specified value
df_filled = df.fillna(0)

Drop rows with any missing values


df_dropped = df.dropna()

Write processed data to Excel


df_filled.to_excel('filled_data.xlsx', index=False)
df_dropped.to_excel('dropped_data.xlsx', index=False)
```

2. Advanced Data Analysis

Excel is great for basic data analysis, but Python takes it to the next level
with advanced statistical and analytical capabilities.

1. Descriptive Statistics

Python's libraries like `pandas` and `numpy` make it easy to calculate


descriptive statistics such as mean, median, and standard deviation.

```python
import numpy as np

Calculate descriptive statistics


mean_value = np.mean(df['Sales'])
median_value = np.median(df['Sales'])
std_deviation = np.std(df['Sales'])
print(f"Mean: {mean_value}, Median: {median_value}, Standard
Deviation: {std_deviation}")
```

2. Regression Analysis

Performing regression analysis in Python allows you to understand


relationships between variables, which can be more complex to execute in
Excel.

```python
import statsmodels.api as sm

Define the dependent and independent variables


X = df['Advertising Spend']
y = df['Sales']

Add a constant to the independent variable matrix


X = sm.add_constant(X)

Fit the regression model


model = sm.OLS(y, X).fit()

Print the regression summary


print(model.summary())
```

3. Dynamic Visualizations

While Excel offers basic charting capabilities, Python libraries such as


`matplotlib` and `seaborn` provide more advanced and customizable
visualization options.
1. Creating Interactive Plots

Using libraries like `plotly`, you can create interactive plots that provide a
more engaging way to explore data.

```python
import plotly.express as px

Create an interactive scatter plot


fig = px.scatter(df, x='Advertising Spend', y='Sales', color='Region',
title='Sales vs. Advertising Spend')
fig.show()
```

2. Heatmaps and Correlation Matrices

Visualizing correlations between variables can provide valuable insights


that are not easily captured with standard Excel charts.

```python
import seaborn as sns
import matplotlib.pyplot as plt

Calculate the correlation matrix


corr_matrix = df.corr()

Create a heatmap
sns.heatmap(corr_matrix, annot=True, cmap='coolwarm')
plt.title('Correlation Matrix Heatmap')
plt.show()
```
4. Automating Reports and Dashboards

Generating regular reports and dashboards can be labor-intensive. Python


can automate these tasks, ensuring consistency and saving time.

1. Automated Report Generation

You can create and format Excel reports automatically with Python, adding
charts, tables, and other elements as needed.

```python
from openpyxl import Workbook
from openpyxl.chart import BarChart, Reference

Create a new workbook and select the active worksheet


wb = Workbook()
ws = wb.active

Write data to the worksheet


for row in dataframe_to_rows(df, index=False, header=True):
ws.append(row)

Create a bar chart


chart = BarChart()
data = Reference(ws, min_col=2, min_row=1, max_col=3,
max_row=len(df) + 1)
chart.add_data(data, titles_from_data=True)
ws.add_chart(chart, "E5")

Save the workbook


wb.save("automated_report.xlsx")
```

2. Dynamic Dashboards

Python can be used to create dynamic dashboards that update automatically


based on new data.

```python
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output

app = dash.Dash(__name__)

app.layout = html.Div([
dcc.Graph(id='sales-graph'),
dcc.Interval(id='interval-component', interval=1*1000, n_intervals=0)
])

@app.callback(Output('sales-graph', 'figure'),
Input('interval-component', 'n_intervals'))
def update_graph(n):
df = pd.read_excel('data.xlsx')
fig = px.bar(df, x='Product', y='Sales')
return fig

if __name__ == '__main__':
app.run_server(debug=True)
```
5. Data Integration and Connectivity

Python can seamlessly integrate with various data sources, bringing in data
from APIs, databases, and other files.

1. API Data Integration

Fetching real-time data from APIs can be automated using Python, which
can then be analyzed and visualized within Excel.

```python
import requests

Fetch data from an API


response = requests.get('https://api.example.com/data')
data = response.json()

Convert to DataFrame and save to Excel


df_api = pd.DataFrame(data)
df_api.to_excel('api_data.xlsx', index=False)
```

2. Database Connectivity

Python can connect to SQL databases, allowing you to query and


manipulate large datasets efficiently before exporting them to Excel.

```python
import sqlite3

Connect to the SQLite database


conn = sqlite3.connect('database.db')
Query the database
df_db = pd.read_sql_query('SELECT * FROM sales_data', conn)

Save to Excel
df_db.to_excel('database_data.xlsx', index=False)
conn.close()
```

6. Machine Learning and Predictive Analytics

Python's robust machine learning libraries, such as `scikit-learn` and


`TensorFlow`, can be used to build and deploy predictive models within
Excel.

1. Building Predictive Models

Train a machine learning model in Python and use it to make predictions on


new data.

```python
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_squared_error

Split the data into training and testing sets


X = df[['Advertising Spend', 'Price']]
y = df['Sales']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,
random_state=42)

Train a random forest model


model = RandomForestRegressor(n_estimators=100, random_state=42)
model.fit(X_train, y_train)

Make predictions on the test set


y_pred = model.predict(X_test)
mse = mean_squared_error(y_test, y_pred)

print(f"Mean Squared Error: {mse}")


```

2. Integrating Models with Excel

Use the trained model to make predictions directly within Excel, allowing
for seamless integration of advanced analytics into your spreadsheets.

```python
from openpyxl import load_workbook

Load the Excel workbook


wb = load_workbook('data.xlsx')
ws = wb.active

Make predictions and write them to the Excel file


for row in ws.iter_rows(min_row=2, min_col=1, max_col=3,
values_only=True):
X_new = pd.DataFrame([row[1:]])
y_new = model.predict(X_new)
ws.cell(row=row[0], column=4, value=y_new[0])

Save the updated workbook


wb.save('predictions.xlsx')
```

Integrating Python with Excel opens up a world of possibilities, from


automating mundane tasks to performing sophisticated data analysis and
visualization. By leveraging Python’s extensive libraries and combining
them with Excel's familiar interface, you can significantly enhance your
productivity and gain deeper insights from your data. As we continue
exploring this synergy, each new use case will further demonstrate the
transformative potential of Python in the realm of Excel.
CHAPTER 2: SETTING UP
THE ENVIRONMENT
Installing Python on your computer is the first crucial step in this journey of
integrating Python seamlessly with Excel. This section provides a
comprehensive guide, ensuring you set up Python correctly, paving the way
for effective and efficient data manipulation, analysis, and automation.

Step 1: Downloading Python

To begin, you need to download the Python installer. Here are the steps to
follow:

1. Visit the Official Python Website:


Open your preferred web browser and navigate to the [official Python
website](https://www.python.org/). The homepage prominently displays the
latest version of Python available for download.

2. Choose the Appropriate Version:


For most users, the download button listed first will be the latest stable
release, such as Python 3.x. Ensure you select the version compatible with
your operating system (Windows, macOS, or Linux). While Python 2.x is
available, it's recommended to use Python 3.x due to its ongoing support
and updates.

3. Download the Installer:


Click the download button. Depending on your system, you might need to
choose between different installers. For example, on Windows, you
typically have an option between an executable installer and a web-based
installer. Opt for the executable installer for ease of use.

Step 2: Running the Installer

Once downloaded, run the installer to start the installation process. Follow
these detailed steps:

1. Windows Installation:
1. Open the Installer:
Double-click the downloaded file (e.g., `python-3.x.x.exe`).
2. Customize Installation:
Before proceeding, check the box that says "Add Python 3.x to PATH". This
ensures that Python is added to your system's PATH environment variable,
allowing you to run Python from the command prompt.
3. Choose Installation Type:
You can choose either the default installation or customize the installation.
For beginners, the default settings are usually sufficient. Click "Install
Now" to proceed with the default settings.
4. Installation Progress:
The installer will extract files and set up Python on your computer. This
may take a few minutes.
5. Completing Installation:
Once the installation is complete, you’ll see a success message. Click
"Close" to exit the installer.

2. macOS Installation:
1. Open the Installer:
Open the downloaded `.pkg` file (e.g., `python-3.x.x-macosx.pkg`).
2. Welcome Screen:
A welcome screen will appear. Click "Continue" to proceed.
3. License Agreement:
Read and accept the license agreement by clicking "Continue" and then
"Agree".
4. Destination Select:
Choose the destination for the installation. The default location is usually
fine. Click "Continue".
5. Installation Type:
Click "Install" to begin the installation process.
6. Admin Password:
You’ll be prompted to enter your macOS admin password to authorize the
installation.
7. Installation Progress:
The installer will copy files and set up Python. This might take a few
minutes.
8. Completing Installation:
Once the installation is complete, you’ll see a confirmation message. Click
"Close" to exit the installer.

3. Linux Installation:
On Linux, Python might already be installed. Check by opening a terminal
and typing `python3 --version`. If Python is not installed or you need a
different version, follow these steps:
1. Update Package Lists:
```bash
sudo apt update
```
2. Install Python:
```bash
sudo apt install python3
```
3. Verify Installation:
Ensure Python is installed by checking its version:
```bash
python3 --version
```

Step 3: Verifying the Installation

After installation, verifying that Python has been successfully installed and
is working correctly is vital. Follow these steps:

1. Open Command Prompt or Terminal:


For Windows, open the Command Prompt. For macOS and Linux, open the
Terminal.

2. Check Python Version:


Type the following command and press Enter:
```bash
python --version
```
or for Python 3:
```bash
python3 --version
```
You should see output indicating the installed version of Python, confirming
that Python is installed correctly.
Step 4: Installing pip

The package installer for Python, pip, is essential for managing libraries and
dependencies. It is usually included with Python 3.x. Verify pip installation
with:
```bash
pip --version
```
If pip is not installed, follow these steps:

1. Download get-pip.py:
Download the `get-pip.py` script from the official [pip website]
(https://pip.pypa.io/en/stable/installing/).

2. Run the Script:


Navigate to the download location and run the script:
```bash
python get-pip.py
```
or for Python 3:
```bash
python3 get-pip.py
```

Step 5: Setting Up a Virtual Environment

A virtual environment allows you to create isolated Python environments,


ensuring that dependencies for different projects do not interfere with each
other. Here's how to set it up:
1. Install virtualenv:
Use pip to install the virtual environment package:
```bash
pip install virtualenv
```
or for Python 3:
```bash
pip3 install virtualenv
```

2. Create a Virtual Environment:


Navigate to your project directory and create a virtual environment:
```bash
virtualenv env
```
or for Python 3:
```bash
python3 -m venv env
```

3. Activate the Virtual Environment:


- On Windows:
```bash
.\env\Scripts\activate
```
- On macOS and Linux:
```bash
source env/bin/activate
```

4. Deactivate the Virtual Environment:


When you need to exit the virtual environment, simply type:
```bash
deactivate
```

Installing Python on your computer is the foundational step towards


leveraging its powerful capabilities in conjunction with Excel. Ensuring that
Python is set up correctly and understanding how to manage environments
will streamline your workflow and prepare you for the advanced tasks
ahead. With Python installed and ready, you’re now equipped to dive into
the exciting world of Python-Excel integration. The next chapter will guide
you through installing and setting up Excel, making sure it's ready to work
seamlessly with Python scripts.

Installing and Setting Up Excel

Installing and setting up Excel properly is critical for creating a seamless


integration with Python, enabling sophisticated data manipulation and
analysis. This section provides a detailed guide on how to install Excel,
configure it for optimal performance, and prepare it for Python integration.

Step 1: Installing Microsoft Excel

Most users will likely have a subscription to Microsoft Office 365, which
includes the latest version of Excel. If you don't already have it, follow
these steps to install Excel.
1. Purchase Office 365:
- Visit the [Office 365 website](https://www.office.com/) and choose a
suitable subscription plan. Options include Office 365 Home, Business, or
Enterprise plans, each offering access to Excel.
- Follow the on-screen instructions to complete your purchase and sign up
for an Office 365 account.

2. Download Office 365:


- After purchasing, log in to your Office 365 account at [office.com]
(https://www.office.com/) and navigate to the "Install Office" section.
- Click the "Install Office" button, and download the Office 365 installer
appropriate for your operating system.

3. Run the Installer:


- Locate the downloaded file (e.g., `OfficeSetup.exe` on Windows or
`OfficeInstaller.pkg` on macOS) and run it.
- Follow the on-screen instructions to complete the installation process.
Ensure you have a stable internet connection, as the installer will download
and install the full suite of Office applications, including Excel.

4. Activation:
- Once installation is complete, open Excel.
- You will be prompted to sign in with your Office 365 account to activate
the product. Ensure you use the account associated with your subscription.

Step 2: Configuring Excel for Optimal Performance

Configuring Excel correctly ensures you can maximize its efficiency and
performance, especially when handling large datasets and complex
operations.

1. Update Excel:
- Keeping Excel up-to-date is crucial for performance and security. Open
Excel and go to `File > Account > Update Options > Update Now` to check
for and install any available updates.

2. Excel Options:
- Navigate to `File > Options` to open the Excel Options dialog, where you
can customize settings for better performance and user experience.
- General:
- Set the `Default view` for new sheets to your preference (e.g., Normal
view or Page Layout view).
- Adjust the number of `sheets` included in new workbooks based on your
typical usage.
- Formulas:
- Enable iterative calculation for complex formulas that require multiple
passes to reach a solution.
- Set `Manual calculation` if working with very large datasets, to avoid
recalculating formulas automatically and improving performance.
- Advanced:
- Adjust the number of `decimal places` shown in cells if you frequently
work with highly precise data.
- Change the number of `recent documents` displayed for quick access to
frequently used files.

3. Add-Ins:
- Excel supports various add-ins that can enhance its functionality. Navigate
to `File > Options > Add-Ins` to manage these.
- COM Add-Ins:
- Click `Go` next to `COM Add-Ins` and enable tools like Power Query and
Power Pivot, which are invaluable for data manipulation and analysis.
- Excel Add-Ins:
- Click `Go` next to `Excel Add-Ins` and select any additional tools that
might benefit your workflow, such as Analysis ToolPak.

Step 3: Preparing Excel for Python Integration

To fully leverage Python within Excel, a few additional steps are required to
ensure smooth integration.

1. Installing PyXLL:
- PyXLL is a popular Excel add-in that allows you to write Python code
directly in Excel.
- Visit the [PyXLL website](https://www.pyxll.com/) and download the
installer. Note that PyXLL is a commercial product and requires a valid
license.
- Run the installer and follow the setup instructions. During installation, you
will need to specify the path to your Python installation.
- Once installed, open Excel, navigate to `File > Options > Add-Ins`, and
ensure `PyXLL` is listed and enabled under `COM Add-Ins`.

2. Installing xlwings:
- xlwings is an open-source library that makes it easy to call Python from
Excel and vice versa.
- Open a Command Prompt or Terminal window and install xlwings using
pip:
```bash
pip install xlwings
```
- After installation, you need to enable the xlwings add-in in Excel. Open
Excel, go to `File > Options > Add-Ins`, and at the bottom, choose `Excel
Add-ins` and click `Go`. Check the box next to `xlwings` and click `OK`.

3. Setting Up Jupyter Notebook:


- Jupyter Notebook provides an interactive environment where you can
write and execute Python code, including code that interacts with Excel.
- Install Jupyter Notebook using pip:
```bash
pip install notebook
```
- To launch Jupyter Notebook, open Command Prompt or Terminal and
type:
```bash
jupyter notebook
```
- This will open Jupyter in your default web browser. Create a new
notebook and start writing Python code that integrates with Excel.

4. Configuring Excel for Automation:


- Ensure Excel is configured to work well with automation tools. For
example, you might need to adjust macro settings.
- Navigate to `File > Options > Trust Center > Trust Center Settings >
Macro Settings`.
- Choose `Enable all macros` and `Trust access to the VBA project object
model`. Note that enabling all macros can pose a security risk, so ensure
you understand the implications or consult your IT department if needed.

Step 4: Verifying the Setup

Before diving into complex tasks, it's crucial to verify that everything is set
up correctly.

1. Run a Basic PyXLL Command:


- Open Excel and enter a simple PyXLL function to ensure it runs correctly.
- Example: In a cell, type `=PYXLL.ADD(1, 2)` and press Enter. The cell
should display `3`.

2. Test xlwings Setup:


- Create a simple Python script using xlwings to interact with Excel. Save
this script as `test_xlwings.py`:
```python
import xlwings as xw
wb = xw.Book()
sht = wb.sheets[0]
sht.range('A1').value = 'Hello, Excel!'
```
- Run the script and check if the message "Hello, Excel!" appears in cell A1
of a new workbook.

3. Verify Jupyter Notebook Integration:


- Open a new Jupyter Notebook and execute a Python command to interact
with Excel:
```python
import xlwings as xw
wb = xw.Book()
sht = wb.sheets[0]
sht.range('A1').value = 'Hello from Jupyter!'
```
- Ensure that the message "Hello from Jupyter!" appears in cell A1 of a new
workbook.
Setting up Excel correctly is just as important as installing Python. With
both systems configured and verified, you are now ready to leverage the
combined power of Python and Excel for advanced data manipulation,
analysis, and automation. This setup will serve as the foundation for all the
forthcoming chapters, where we will delve into the specifics of using
Python to enhance Excel's capabilities.

Introduction to Jupyter Notebook

Jupyter Notebook is a powerful tool in the realm of data science and


analytics, facilitating an interactive environment where you can combine
code execution, rich text, mathematics, plots, and media. This section
delves into how to set up and use Jupyter Notebook, especially in the
context of integrating Python with Excel.

Step 1: Installing Jupyter Notebook

Before we get into how to use Jupyter Notebook, we need to install it. If
you already have Python installed, you can install Jupyter Notebook using
pip, Python’s package installer.

1. Open a Command Prompt or Terminal:


- On Windows, press `Win + R`, type `cmd`, and press Enter.
- On macOS/Linux, open your Terminal application.

2. Install Jupyter Notebook:


- In the Command Prompt or Terminal, type the following command and
press Enter:
```bash
pip install notebook
```
3. Verify the Installation:
- After the installation is complete, you can verify it by typing:
```bash
jupyter notebook
```
- This command should start a Jupyter Notebook server and open a new tab
in your default web browser, displaying the Jupyter Notebook interface.

Step 2: Understanding the Interface

Once Jupyter Notebook is installed and running, it's essential to understand


its interface to make the most of its capabilities.

1. The Dashboard:
- The first page you see is the Jupyter Dashboard. It lists all the files and
folders in the directory where the Notebook server was started. You can
navigate through directories, create new notebooks, and manage files
directly from this interface.

2. Creating a New Notebook:


- To create a new notebook, click on the "New" button on the right side of
the dashboard and select "Python 3" from the dropdown menu. This creates
a new notebook in the current directory.

3. Notebook Layout:
- The notebook consists of cells. There are two main types of cells:
- Code Cells: These cells allow you to write and execute Python code.
When you run a code cell, the output is displayed directly below it.
- Markdown Cells: These cells allow you to write rich text using Markdown
syntax. You can include headings, lists, links, images, LaTeX for
mathematical expressions, and more.
4. Toolbars and Menus:
- The notebook interface includes toolbars and menus at the top, providing a
variety of options for file management, cell operations, and kernel control
(the kernel is the computational engine that executes the code in the
notebook).

Step 3: Writing and Running Python Code

The primary use of Jupyter Notebook is to write and run Python code
interactively.

1. Code Execution:
- Enter Python code into a code cell and press `Shift + Enter` to execute it.
For example:
```python
print("Hello, Jupyter!")
```
- The output "Hello, Jupyter!" will appear directly below the cell.

2. Using Python Libraries:


- You can import and use any Python libraries installed in your
environment. For example, to use the Pandas library:
```python
import pandas as pd
data = {'Name': ['John', 'Anna', 'Peter', 'Linda'],
'Age': [28, 24, 35, 32]}
df = pd.DataFrame(data)
print(df)
```
- This will create a DataFrame and print it in the notebook.
Random documents with unrelated
content Scribd suggests to you:
Bank is a great, grinding monster without bowels of compassion for
anybody. God damn the Bank and all its fools and flunkeys!"
"Magnus Stephenson," said the Pastor, raising his little fat hand,
"I will ask you to remember that a clergyman is in your company,
and if you take God's name in vain----"
"Take God's name in vain! You do that often enough--you do it
every Sunday."
"I'll not pretend to misunderstand you, Magnus Stephenson, for
I know you are deeply tainted with skepticism, and since you ceased
to come to church----"
"Church! You pray to God in your churches, and what does He
do for you? What does He do for any one? What has He done for
me?"
"If your life had been straight and pure God would have
watched over you."
"And hasn't it? Haven't I tried to do what was right? And yet
God is seeing me sold up and turned out, and my dear ones left to
die in a ditch."
"God chastises His own, and if we only have faith in Him----"
"Faith in Him? Where is He? Is He in the Northlands? I have
never heard of it. Is He in the Southlands? I've never seen Him here,
though I've seen the devil often enough. He's in the clouds if He's
anywhere, and that's no use to me."
"Magnus Stephenson----"
"If God is on the earth let Him do something. Here's His chance.
You call the poor His people, don't you? Well, I've fed and sheltered
His people for fifteen years, and now I want feeding and sheltering
myself. I want eight thousand crowns before nine o'clock to-morrow
morning, and if God can do anything in the world let him find me the
money and save my mother and my child from starvation. But He
can't do it! He can do nothing!"
"Magnus Stephenson," said the little clergyman, raising his little
fat hand again, "when you come to stand before the great white
throne God will have something to forgive you."
"Pastor Peter, when I come to stand before the great white
throne I shall have something to forgive God, it seems to me."
"Blasphemy! Blasphemy!" cried the Pastor, and as he followed
the Sheriff out of the house Magnus sent a ringing laugh of
contempt after him into the darkness of the night. At the same
moment two sheep-dogs that had been lying at the door with their
snouts on their paws, as if anxious to join the uproar, began to growl
and bark, whereupon Magnus (who had always been a lover of
animals) kicked them savagely and then reeled back to his seat by
the stove.
The strangers being gone and the little family alone, Elin, who
had been standing by the dresser, went over to Magnus and slid into
her seat on his knee and said:
"You must not think about me, Uncle Magnus. Wherever you
have to go I will go too, and what is good enough for you is good
enough for Elin. And then, who knows what may happen before the
Sheriff comes back in the morning? This is New Year's Eve, you
know. All good things come at New Year--miracles come at New
Year, Uncle."
But the sweet buoyancy of her girlish spirits, which had been
the sunshine of his life for so many years, was failing him at last,
and putting her aside with petulant expressions he got up and went
out to the back.
Then Anna, who had been sitting in silence by the table, took
the Bible and four hymn-books from the corner cupboard and rang
the bell for prayers.
"I wonder why I did that?" she said. "I forgot that Eric was
gone. I hope he found shelter somewhere, poor boy--I should pity a
dog that had to be out of doors on a night like this."
And then Elin, in default of Magnus, read the lesson which Anna
had marked for her. It was the psalm beginning, "The Lord is my
Shepherd, I shall not want." And when the short chapter was
finished the two women stood up and sang a hymn--Elin in the
silvery treble of youth and Anna in the husky tones of age, they two
only in the lonely house among the solitary hills, with nothing about
them but the darkness and the snow--nothing but that and the
immeasurable wings of God.

"Happy the man whose tender care


Relieves the poor distressed;
When he by trouble's compassed round
The Lord will give him rest."

Anna sat down when the hymn was ended, but Elin continued to
stand by the table, and closing her eyes with her innocent face
uplifted, she said a little prayer for herself.
"O Father," she said, "bless Uncle Magnus, so that he may fear
no evil. Show me how to help him, so that I may not be a burden
and a care. Dear Jesus, send the miracle that will save Uncle Magnus
and grandma and me. It will be such a little thing to you, but such a
great, great thing to us, and we shall all be so happy and dwell in
the house of the Lord forever. For Christ's sake. Amen."
Then she opened her trustful eyes and said, "I'm sure He will,
grandma," and kissing Anna she said "Good night" in a cheery voice
and went off to bed.
Prayers being over, Magnus returned to the hall and began to
rake out the stove for the night. The clouds hung heavier on him
than ever, and thinking to banish them Anna talked of Elin.
"She grows more and more like her mother, and sometimes I
think it can only be a dream that our dear Thora is dead. If you had
heard her praying for the miracle it would have filled your heart
brimful. She has gone to bed quite certain that the miracle will come
before morning."
"It would have to be a miracle to help us now, mother," said
Magnus. "And miracles don't happen--except such of them as we
make for ourselves."
"What do you mean by that, Magnus?" said Anna, lighting the
candles.
"I mean--if I had to live my life over again, I shouldn't try to do
what is right, mother."
"You wouldn't do what is wrong, would you?"
"There is no wrong and no right, mother; there is only what is
best, and if I had to begin over again, I should do what was best--
best for myself and for the people about me."
"You don't know what you are saying, Magnus. There are
moments when it might seem to be best to rob, even to kill----"
"And why not?" said Magnus--he was bolting the door. "If a man
came to this house to-night with eight thousand crowns in his
pocket, do you think I should hesitate to take them?"
"My son, you don't mean it."
"I do!"
"You are driven to despair, Magnus, and a despairing man's
words belong to the wind. If I thought you meant it I should die--I
should die this very minute."
She was crying and there was silence for a moment, and then
Magnus said:
"Never mind, mother. It doesn't matter whether I meant it or
not, the temptation isn't likely to come to me. Give me the candle
and let us go to bed."
"You have borne a terrible burden, Magnus, and if I could only
have helped you to bear it----"
"You have, mother. If it had not been for you and Elin I should
have gone under ten years ago."
"Your father knew he had robbed you of your inheritance, and
perhaps that helped to kill him in the end."
"It wasn't father's fault altogether. He tried to do what was
right, too. But the poor wretch who comes after the prodigal gleans
in a barren field, you know."
With their candles in hand they were turning to go--Anna to the
badstofa above, and Magnus to the guest-room off the hall--when
the dogs, who had risen again, and were snuffling at the bottom of
the door, began to growl and bark.
"There's somebody coming," said Magnus.
A moment later there was a sharp knock at the window, as with
a metal end of a riding-whip, and a tremulous, high-pitched voice
outside, making the customary Icelandic salutation, "God be with
you!"
They looked at each other in blank surprise, while backward
thoughts galloped through their minds, and then Magnus, forgetting
to give the customary reply, walked back to the door, and threw it
open.
There was a dull thud of heavy feet on the outside steps, and at
the next moment a man stood on the threshold. He seemed to be an
old man, for his eyebrows, beard, and mustache, and as much as
could be seen of his hair under the peaked hood of his ulster, were
white with snow. One moment he stood there as if breathless after
his journey, looking from Magnus to the mother, and from the
mother to Magnus. Then he said, in the same tremulous voice as
before:
"Can I have a bed here to-night, and shelter for my horse?"
It seemed to Anna that he spoke to her, but instead of
answering immediately, she looked across at Magnus with helpless
eyes that were full of inexpressible fears. Magnus looked back at his
mother and hesitated for an instant, while he held the door open
with his hand. Then:
"Come in, sir," he said, and the stranger stepped into the house.

PART VII
"The ball no question makes of ayes and noes,
But right or left, as strikes the player goes;
And He who tossed you down into the field,
He knows about it all--He knows--HE knows."

"The little mare is hot--she'll want a rub down and a rest before you
give her a feed."
"I'll see to that, sir," said Magnus, and he went out and pulled
the door after him.
Christian Christiansson had taken two paces into the hall, and
was standing there like a man who is dazed. His heart was thumping
against his ribs, and his pulse was beating violently, and he felt that
he would fall if he took another step forward. So often had he
pictured himself in that place that he could not at first believe in the
reality. Coming out of the darkness, the light of the candles dazzled
him, but he looked round the room, trying to remember. At one
glance he took in everything--the old portraits on the wall, the old
Bornholme clock in the corner, the stove and the armchair in front of
it--and, fresh from the warm comfort of Government House, the Inn-
farm seemed bare and bleak. This sent a chill pang of remorse to his
mind, and the pain of conscience increased when he looked at his
mother.
Her hair was white that had once been dark, and her face,
which had been full of the loveliness of love and the beauty of
happiness, was scored deep with lines of suffering. His heart
yearned over her, and notwithstanding his determination not to
reveal his identity until morning, it was as much as he could do to
restrain himself from saying as well as he could for the emotion that
was mastering him, "Mother, don't you know me? I am Oscar," and
then throwing his arms about her dear neck as he had always meant
to do.
Meantime Anna, who had recovered her self-control and was
lighting the lamp that swung from the ceiling, glanced across at the
new-comer and thought, "He's nearly frozen stiff, and no wonder."
With that thought she bustled about to rekindle the stove, and called
on him to remove his snow-covered clothing.
"Won't you take off your cloak and boots, sir?" she said, and
though the question was so commonplace he could not answer
immediately, for his voice would not come.
"Your cloak and boots, sir, and I'll put them to dry by the stove."
"Ah yes, of course, certainly."
She stood by him while he threw off his ulster and shook the
snow from his hair and beard, emerging a younger and stronger
man, but she only thought, "A stranger, I suppose. Why does he
travel in this weather?"
When he had pulled off his riding-boots, she brought him a pair
of Magnus's slippers and said:
"You must have had a terrible ride, sir."
"It was pretty bad certainly," he said, and after that he got on
better.
"A gentleman must have been anxious to get on with his
journey to travel on a day like this."
"I was--I had something to do at the end of it."
"Have you come far, sir?"
"Altogether? Yes, very far."
"From Reykjavik perhaps?"
"Farther than that--from England."
"From England!"
"From London."
As he stooped to put on the slippers he thought his mother was
looking at him, and he trembled between fear and hope of being
recognized.
"I suppose," he said--his head was down--"I suppose you've
never been as far as that, landlady?"
"No, sir."
"Nor any of your family?"
He could not resist the temptation to say this, but his mother
did not seem to hear him--she was on her knees, breaking sticks
into the stove.
"Sit up and warm yourself, sir. My son raked out the fire, but
these sticks will burn presently. You are here on business, I
suppose?"
"Yes, I'm here on business."
Anna thought of the auction and waited for the stranger to
speak of it. When he did not do so she said, "Travelers come from
England to buy sheep and ponies, but they don't often come in the
winter, sir."
Still he did not speak (he was thinking of Elin and looking round
for any trace of her), and rising from the stove Anna said:
"But you'll be hungry after your long ride--what can I give you
to eat?"
"Anything at all--anything you have ready."
"I'm afraid I have nothing ready--that is to say, nothing that is
good enough for the like of you, sir."
As soon as he could find his voice after that he said, "Don't you
always keep smoked mutton in an Iceland house?"
"Well, yes, if that will do, sir."
"I should like it above all things."
There was a moment's silence, and he thought his mother was
looking at him again. "Then perhaps you are an Icelander?" she
said.
"Yes, I'm an Icelander," he answered.
"What is your name?"
Another wild impulse to reveal himself immediately to his
mother, nearly swept down his fears, for he was choking with a
sense of duplicity and his conscience was fighting in contrary ways,
but after a moment his prudence conquered, and with a gulp in his
throat he said:
"They call me Christian Christiansson."
"Well, it's lucky you found us up, sir. We were on the point of
going to bed."
"I suppose the other members of your family are gone already?"
"There's only one besides what you've seen--my granddaughter-
-and she had just gone off as you came in, sir."
He looked at her as she was crossing in front of him, and saw
that she was wearing the brooch which he had given her when he
came back from Oxford. That sent all the blood to his head again,
and he was saying, before he was aware of it--
"Do you know, landlady, I've slept in this house before?"
"It must have been a long time ago then--I don't remember
you."
"It was a long time ago. That," pointing to the portrait of Anna
on the wall, "that is a portrait of yourself, isn't it?"
"It used to be, but I was younger when it was like me, sir."
A sudden softening came into his voice as he replied, "It was
exactly like you when I saw you last, landlady."
"Then you've not been here for ten years at least, sir."
"Quite ten years," he answered. "And that," pointing to the
portrait of the Governor, "is a portrait of your husband."
"It must be more than ten years since you were here, sir, for my
husband is more than twelve years in his grave."
"It is more than ten years. In fact it is sixteen years--nearly
sixteen."
She looked fixedly at him for a moment and something in her
memory seemed to stir, for her bosom heaved perceptibly, but she
only said, with a deep sigh, "We've seen trouble since you traveled
in these parts before, sir."
"Ah, yes, I've heard of it--I heard of it in Reykjavik. You had a
son----"
"That was my son who opened the door to you."
"But you had another son--a younger son."
"Yes, but--we never talk of him now, sir."
"Who's portrait is that in your brooch, landlady?"
"It's his--he is dead."
"Died in disgrace, didn't he?"
"Who knows that, sir? Man sees the deed, they say, but God the
circumstance."
"They think hard things of him in Reykjavik, though. They say
he robbed his father of every penny when he went away, and never
sent anything home toward the maintenance of his child."
"It needs no skill to wound the defenceless," said Anna, bridling
up. "The father robbed himself to save his son, if you want to know
the truth, and as for never sending anything home for the child the
poor boy had nothing to send, for he was poor himself, sir."
"So you found that out, did you?"
"After he was dead we did--one of his father's English friends
wrote to tell us so. And all the time he had been writing letters to
me to say how busy he was and how well he was succeeding--just
to keep up my heart and save me from fretting."
The mother's lingering fondness for her prodigal was rising in
her eyes and breaking in her voice and she was trying to turn away,
but he could not let her go.
"What a pity his father didn't live long enough to hear that! It
would have softened his heart toward him, perhaps."
"It didn't need softening, sir--not at the end at all events."
"His father forgave him, did he?"
"He died thinking his son had become a great man and had
justified all his hopes and atoned for everything. It was only a
delusion, sir, but it made him very happy."
"Your son was a musician, wasn't he?"
"Yes, sir, and from the time he was a child he used to scribble
things and call them his compositions. The pieces of paper always
disappeared and I never knew what had become of them, but when
his father was lying dead I found out where they were."
"And where were they?"
"In his poor father's hands."
Christian Christiansson had gone on and on, while the hot blood
throbbed in his brain, struggling between the desire to reveal himself
and the fear of doing so, but he was drawn up at last by a stifling
sense of his own unworthiness, and before he knew what he was
doing he said:
"The man who could do wrong to a father who loved him like
that must have been a scoundrel--a bad-hearted scoundrel, and he
deserved everything that happened to him."
"He was nothing of the kind, sir," said Anna. "He may have done
wrong--I'm not defending him--but a better-hearted boy was never
born into the world. Everybody loved him, and he loved everybody,
and as for me----"
Christian Christiansson recovered himself at the sound of Anna's
faltering words. "God bless her!" he thought, and his heart danced
to a new song, but he only said, with a perceptible lowering of his
voice, "I beg your pardon! Naturally his mother cannot think so, but
this is the first time I've heard a good word for him since I came to
Iceland."
"I hadn't meant to speak of him at all, sir. I never do when my
other son is near--Hush! He is coming back."
But the noise which they heard behind them was that of the
opening and closing of a bedroom not a kitchen door, and it was
followed by the light footstep of a girl, whereupon Anna said:
"Elin! I thought you were in bed and asleep, my child."
"I was, but I awoke and heard you had a visitor, so I got up to
help, grandma."
Christian Christiansson trembled from head to foot. The silvery
voice at his back seemed to come to him from across a wide abyss--
for it was a familiar voice but vague as with the mist of dreams and
dim as with the clouds of night.
"This is my granddaughter, sir," said Anna. And then Christian
Christiansson turned and saw her--a young girl as tall as a woman,
with fair complexion, a soft smiling face, and beautiful blue eyes.
She wore a laced bodice, a turned-down collar, a hufa, a tassel,
plaited hair, and looked like the living picture of what her mother had
been when he came from college.
It was his daughter, his little Elin, whom he had traveled so far
to see, but it seemed to him as if all the cruel years had rolled back
in a moment, and it was Thora returned to life.

II

"Well, now that you are here, you had better lay the table," said
Anna.
"Yes, grandma," said the girl.
"Put on the smoked mutton and the Rullapilsa and the Rikling,
while I go to the elt-house to make coffee."
"Yes, grandma."
"Make yourself at home, Christian Christiansson--my
granddaughter will wait on you."
"I will," he tried to say, but his voice would scarcely come.
Anna being gone, he sat for some moments looking at Elin while
she tripped from dresser to table, and in and out of the pantry,
spreading the cloth, and laying the plates and the food. The girl was
so simple, so natural, so free from self-consciousness, that she
seemed to be hardly aware of his presence, for she hummed to
herself softly as if some song-bird in her breast could not be kept
quite still. His heart swelled and throbbed as his eyes followed her
about, and when she left the room the light seemed to fail in it, and
when she came back the air seemed to become warm. In the dizzy
happiness of that hour he felt as if he had lost a daughter in every
one of the fifteen years he had lived without her, and now that she
was near, so close, his hands burned and itched to hold her. He
wanted to take her in his arms and say, "My child! My child! Doesn't
something tell you who I am? I am your father, and I have wanted
you so much and thought of you so often, and now I have come to
fetch you and we shall never be parted again!" But between fear of
frightening her and dread of disclosing himself, all he could do was
to conquer the fluttering in his throat and say:
"Your name is Elin, isn't it?"
"Yes, sir," said the girl.
"What a beautiful name it is, too--Eleen! Your father chose it,
didn't he?"
"I have never heard that, sir. Did grandmother say so?"
"Grandmother and I," he stammered, "have been talking of your
father. You don't remember him?"
"Oh no, sir--he died when I was quite little."
"What a loss that must have been to you, my child!"
"I can't say that, sir," said the girl, "because, you see, Uncle
Magnus has been the same as a father to me all my life, and I have
never known any difference."
"What a loss to your father himself then! How happy you would
have made him, and how proud he would have been of you!"
"I can't say that either," said the girl again, "because he lived
five years after I was born, and it seems he never took any notice of
me."
"Did grandmother tell you so?"
"Oh no, sir. Indeed no! Nor Uncle Magnus neither. But
everybody know all about my father, and even the girls at school
knew that."
A feeling of mortal shame came over him, and the warm pulsing
place in his breast grew still and cold.
"So you are not sorry your father is dead, Elin?"
"It wouldn't be right to say that, sir."
"At all events you feel no love for him?"
"I never knew him--you can't love somebody you never knew,
can you? Perhaps if he had lived longer and returned home I might
have come to love him. But I don't see how I could if what people
say about him is true."
"What do they say, my child?"
"They say he was unkind to my mother, and that that was one
of the reasons why she died so early."
"Then you never wish you could have seen and known your
father?"
"How can I? If he wasn't good to my poor mother, why should I
think he would have been good to me? But see, your supper is
ready. Grandma will bring the coffee presently; won't you begin with
the meat, sir?"
He sat down to the table but his hunger was gone. For a
moment he almost wished himself back in the black night from
which he had come. The girl's simple words had been ringing the
death-knell of his expectations. He had left her all these years to the
keeping and care of others--could he expect to come back now and
find the affection he had forfeited? Ah no! He had come too late--too
late! But just as one part of the plan he had formed for himself was
becoming vague and shadowy a gleam of new light was shot into his
brain, and his heart rose with a bound.
"Didn't grandma call you Christian Christiansson?" asked the
girl.
"Yes," he answered. "Ever hear that name before, my child?"
The girl turned to him with a face glowing with excitement and
said, "Everybody in Iceland has heard it, sir. It is the same as the
name of the great composer who lives in England."
A deafening tumult of joy was rising within him, and he said,
"So you--you have heard of him, have you?"
"I sing his songs, sir. They are beautiful! I think they are the
most beautiful songs in the world. Would you like me to sing one of
them while you eat your supper?"
"Will you?"
"I should like to," she said, and before he could catch the breath
which had been suspended she had slipped off like a shaft of
moonlight and was back like a ray of the sun, bringing a guitar in
her hands.
"This was my mother's guitar, and now it's mine, and it's such a
good one," she said, and with the utter freedom from self-
consciousness which is the charm of children she sat and began to
play. After a moment she stopped, with her head aside, and said:
"Which should it be, I wonder? But perhaps you know them all
and would like me to sing something in particular?"
His face was down, the waves of emotion were surging through
and through him. "Sing--sing anything you like, my darling," he
replied.
The fluttered earnestness of his words startled her for a
moment, but she only smiled with a new sweetness and began to
sing, first in low, clear half-tones, and then in a high, tremulous
treble that was like the peal of a lark at the gate of heaven.
Christian Christiansson could not eat; he could only rest his
elbows on the table and cover his face with his hand. His own child
was singing his own song to him in a voice that was like her
mother's voice and like his own voice too!
When the song was done she turned to him again with eyes
shining with unshed tears and said, "Isn't that beautiful?"
"It was beautifully sung, my child, beautifully!" he said. And
then, after a moment, "Elin, would you like to hear something of the
man who wrote that song and how he came to write it?"
Elin's eagerness was heart-breaking. "Indeed, indeed I should,"
she said. "Do you know your namesake then?"
"I have known him all his life, my child."
"Tell me about him. Oh, do tell me. One who has such beautiful
thoughts and feelings must be so good and noble."
"He is neither the one nor the other, Elin, but only a poor
wayward sinner like ourselves. In early life he did wrong by his
young wife and she died. Then he did wrong by his father and he
had to fly from his country. After that he went through many
sufferings and was guilty of many sins, but he came to himself at the
end, and then he remembered a little daughter whom he had left
behind him. He wished to return to her immediately, and be a father
to her at last, and make it up to her for all that he had done amiss
to her mother who was dead. But there were many things to do
first, for he was like one who was buried under an avalanche which
he had brought down on himself, and he had to work his way back
to life and the world. So when he was far away and his heart was
hungry for the love of his little girl, and he didn't know what was
happening to her, and he wanted so much--oh so much--to go to
her, but could not do so yet because he had sinned and must pay his
penalty, he wrote that song, and it was the cry of his soul to the
mother in heaven to comfort and care for their child on earth."
As Elin listened to the story of Christian Christiansson the tears
which had been standing in her eyes rolled down her cheeks, and
her bosom under her laced bodice slowly rose and as slowly fell
again.
"How beautiful!" she said. And seeing how much she was
moved by the sorrows of the man who was not her father, the new
light came to him and he asked himself why, if she could not care for
him in his true character, she should not love him as Christian
Christiansson.
There was a shadowy ghost of pain in that thought too, but he
put it aside. After years of hope and heavy labor he had come home
to claim his child, and what he had dreaded had come to pass--her
heart had been poisoned against him. But while she loathed him as
Oscar Stephenson she loved him as Christian Christiansson! Oh,
beautiful, blind, pathetic fallacy, could he not let it be?
In a tumult of heart and brain that was like a whirlpool in a dark
river, he had risen to go to the girl, hardly knowing what he was to
do or say, when Anna came back with a smoking coffee-pot in her
hand, saying in a cheery voice:
"Here it is at last! The fire had gone out in the elt-house, and I
had work enough to kindle it."
And then, having both in the room at one moment--his mother
and his daughter--his feelings almost mastered him again, and he
had as much as he could do to keep himself from blurting out
everything and so being done with further torture. But just as the
words of his confession were trembling on his lips he thought, "Not
to-night; to-morrow morning; and then what joy, what happiness!"
Almost at the same moment Magnus returned to the house and
said, "The little mare was nearly done, sir, but I've rubbed her down
and given her hay, and she shall have a mash before I go to bed."
"Let us have a bottle of brandy first," said Christian
Christiansson, and a few minutes later Elin was carrying away the
dishes to wash them, Anna was going into Magnus's bedroom to
make it ready for the guest, and the two brothers were sitting at
opposite sides of the table with the bottle between them.

III

They were less like each other now than ever before--the elder with
his matted, black beard, his strong features, and the vertical lines in
his low brow under the upright stubble of his iron-grey hair; the
younger with his luminous brown eyes and delicate face, his full
round forehead, and his thin, silken, light hair brushed backward to
the crown.
Christian Christiansson was quivering to the core at this first
encounter with the brother whom he had wronged and ruined, but
he tried to bear himself bravely and to see how safe it would be to
reveal his identity when the time came to do so.
"It's good of you to give up your room to me," he began.
"That's nothing--nothing at all," said Magnus.
"And perhaps you ought to know why I'm here to-night."
"Please yourself, sir--please yourself."
"To tell you the truth, then, I'm here to attend the auction to-
morrow morning. I only heard of it in Reykjavik yesterday, having
arrived by the 'Laura' the day before."
"So that was the business that brought you, sir?"
"It was. I've been abroad for fifteen years, and I've made some
money, and now I've come home to invest it. So knowing this was a
good farm----"
"None better in Iceland, sir, if it only had a chance, and if you
can afford to buy it out and out----"
"I think I can--I've money enough in my pocket at this moment
to buy the place to-morrow and leave some for something else. I'm
sorry for you, though, and if it's painful to you to hear me talk like
this----"
Magnus, who had been rolling in his chair like a man whose
mind as well as his body was uneasy, began to laugh immoderately.
"Not at all, sir! Not at all!" he said, filling his glass. "It's pleasant to
hear of anybody having more money than he wants. For my part,
I've never had enough to pay my debts, sir. For sixteen years I've
been ploughing the waves and now," raising his glass and draining
it, "I'm reaping the breakers, b---- them!"
Christian Christiansson trembled to his very heart at the sound
of Magnus's laughter--the bitter laughter of rebellion and despair--
but he tried to cover up his fear and to carry it off with a cheery
tone.
"Don't be too depressed," he said. "Nobody knows what the
future has in store for him. It's a pretty dark night outside, but all
the same the sun will rise to-morrow morning. Besides, there's
always a sunny side to misfortune if we'll only allow ourselves to see
it. Life is sweet, my friend, whatever happens."
"You think it is, sir?"
"I know it is, so why should we sit down on our little handful of
thorns?"
"Because some of us have nothing else to sit upon," said
Magnus, and he laughed again--the same cold, quaking laughter.
Christian Christiansson shuddered, but struggled on. "You think
you've failed, but I know some that have succeeded who would be
glad to change places with you any minute. They've got their gold or
their fame or both pouring down on them like an avalanche, and
nothing to do with it, nobody to share it with--so it is only so much
Dead Sea fruit being piled on their backs. You are not like that. Even
if you have to lose your land, you've got your health, and a good
character and a clean conscience, and your dear ones left to you,
haven't you?"
"That's why!" said Magnus. "You don't suppose I'm thinking of
myself, do you? It's just because I've got my dear ones left to me
that this accursed ill-luck is so hard to bear. What's it to me to have
my houses full of lambs, if the floods have come and they are
floating on the lake? You talk like a man who has never known
misfortune, sir."
Christian Christiansson felt dizzy. "Perhaps I haven't--perhaps I
have," he said in a faint voice, "but I've known despair, and I know
that no man can live by that. We can only live by hope--not what is,
but what is to be--and if we cannot believe when the clouds are
dark, that the world is ruled in righteousness----"
"And is it?" said Magnus. "Does the bad man suffer in this
world? Do his sheep die of the rot and his cattle tumble over the
rocks, or do they increase faster than anybody else's? No, sir," he
said, turning away in his seat, "if you're a rascal ready to rob your
own father, the chances are you'll prosper in this world, but if you're
an honest man trying to do good to everybody, as likely as not you'll
do no good to yourself or to anybody about you."
The dizziness which had seized Christian Christiansson was
increasing every moment, but he said:
"The world has its own way of punishing offenders, and even if
they escape in life, death is always waiting for them----"
"Death?" said Magnus, swinging round in his creaking chair.
"Death is a blind, blundering monster who strikes down the young
and leaves the old, the happy and leaves the miserable, the innocent
and leaves the guilty, the poor helpless betrayed one and leaves the
betrayer! We have all seen that, haven't we? I have, I know that
much."
The heat and flame of Magnus's husky voice had fallen to a
thick whisper that was like a broken sob. Christian Christiansson
dared not raise his face, but he tried to say:
"God brings out all things well in the end. I have always found it
so. The march of the world may be enveloped in darkness, but it
tends toward justice in the long run."
"What is the long run to me, sir?" said Magnus. "I'm only here
for a few years and I want justice now. I want to see the bad man
punished in the present, not in some future generation. Justice, you
say! The sins of the fathers visited on the children--that's the only
justice I see in this world. A poor child left penniless because her
father gambled or drank the money he didn't make--do you call that
justice, sir? I don't!"
Magnus's thick voice was breaking again, and there was silence
for a little while.
"No, no, sir! Don't tell me we get our deserts in this world--any
of us--good or bad. Life gives the lie to that old story--always has,
always will do. If you are a cheat or a profligate, or a prodigal, you
may live in luxury and travel as far as the sun, but if you are a poor
devil staying at home and working your fingers to the bone you'll get
thrown out into the road. But what's the good of talking? The evil
day is coming. Let it come!"
Never before had Christian Christiansson felt so little and so
mean. The sources of pride were dry in him and he was brought
very low in his own esteem. In the presence of the brother who had
borne his burdens and broken down under them he saw himself as
an abject and pitiful thing. He could not raise his head, for he felt as
if his shame were written on his forehead, but he struggled to say
something, and the only words that came to him seemed to scorch
his tongue and parch his throat.
"I can not dispute with you," he said. "You've suffered more
than I have, and no doubt your present troubles are the legacy that
was left to you by the prodigal brother your mother was talking
about."
Magnus's manner changed instantly at the mention of his
mother. "She was talking about him again, was she?" he said.
"Does she often talk of him then?"
"Too often, and she seems to think of nothing else. He was the
foundation she built her house upon, poor soul, and it fell, but she
holds to him all the same."
"God bless her!" said Christian Christiansson involuntarily. "God
bless all women, I say. They're always on the side of the sinners and
the sufferers. They'll get their compensation somewhere--they
must,"--he was thinking of to-morrow morning.
"I see no sign of it in this case," said Magnus. "She was the best
mother to him a man ever had, and he knew it, but he repaid her
with neglect and contempt."
"Contempt?"
"What else would you call it? He lived five years abroad and
wrote to her only once in all that time. Yet every night she used to
stand outside the door until the post passed, winter and summer,
dry or fine, waiting for the letter that never came."
Christian Christiansson felt as if his very soul were shriveling up
with shame.
"She forgave him for that, though, and when he died--you know
how he died, everybody knows it--she thought that all he had been
trying to do when he fell into that foul dishonor was to get money
enough to come back home and make amends."
"She thought that, did she?"
"She still thinks it."
Christian Christiansson had a sense of hysterical oppression at
his heart. Again he wanted to tell all, and he dared not. "But if it had
been true," he said--"I don't say it was, but if it had been--if your
brother had really been trying for years to make money solely in
order to wipe out the debts he had left behind him--if he had come
home with the fortune in his hands----"
Magnus's dark face darkened ominously, and bringing his great
fist down on to the table he said, "There would have been a curse
on every coin of it, and I should have flung it in his face."
Christian Christiansson did not ask him why. He knew too well
what Magnus meant. In an instant, by such a flash of the lightning
of the mind as must come to the guilty soul on the Day of Judgment,
the past of his life lay open before him, and the most awful fact of it
stood out with naked vividness--the desecration of his wife's grave.
It was impossible to plead that this had been only the act of a
moment; that he had repented it a thousand times with bitter tears;
that he had derived no profit or advantage from it, and had endured
for ten years its fearful penalty in the death of his identity. Again and
again he had soothed himself with such excuses, but he could not
cheat his conscience now. Why was he Christian Christiansson? How
had it come to pass that he had two hundred thousand crowns in his
pocket and that his works were known all over the world?
All the miserable sophistry and false reasoning which had made
him what he was, the owner of fame and fortune, had been riddled
through and through by Magnus's terrible words. All the mocking
vanity which had lured him onward to that hour with promises of the
great surprise, the great dénouement, when he should say, "See, I
am here; I have justified all expectations," lay stark and dead and
cold.
No, he could not reveal himself to his family to-morrow
morning. He could not reveal himself at all. Having once become
Christian Christiansson, he could never again be known as Oscar
Stephenson. Thus did the dead punish him, and the desecration of
his wife's grave had but rendered the vow he made to himself
perpetual and registered the oath he made to her in heaven.
Christian Christiansson was feeling as if all the world had gone
away from him when Anna came out of the guest-room, saying:
"There, sir! Your room is ready and you can go to bed at any
time."
Magnus got up to go to the elt-house to mix the mash for the
pony, and then mother and son were together again.

IV

In the confusion of that heart-quelling moment he was asking


himself how he could carry out his plan of rescuing his family from
their misfortunes if he could not tell them who he was, and how he
could claim his daughter and take her away with him, if he could not
say, "I am her father, she is mine," when chance and a
commonplace word--those twin sisters of invention and wisdom--
showed him what he was to do.
"I shall want to be awakened early in the morning, landlady, for
I suppose the Sheriff will come soon."
"The Sheriff, sir?"
"I've just been telling your son that I intend to bid for your farm
at the auction to-morrow morning."
"So that was what you had to do at the end of your journey?"
"Yes, it was what I had to do, landlady."
She looked at him for a moment, and then asked, "What can a
gentleman like you want with a farm like this?"
He did not reply, so she said, "You can not think of living in such
a lonesome place as Thingvellir."
Still he did not speak, and she said again, "You might let the
farm certainly, but it is hungry land, I assure you, and everything
depends on how you work it."
She busied herself about the table as if trying to find something
to do. "My son," she said, "is the only one who has ever been able
to work it properly, and if he has got into difficulties at last it wasn't
his fault, for there isn't a man in Iceland who would have been able
to keep his head above water."
She waited for him to say something, but he gave no sign. "His
difficulties are not so very serious, either. Eight thousand crowns
arrears of interest--that is all, in sixteen years, sir."
Again she waited, but he was still silent. "When the Sheriff went
off this evening, he said if my son could find the money before nine
o'clock to-morrow morning, he wouldn't go on with the auction."
Christian Christiansson had rested his head on his hand and
seemed to be listening intently.
"If my son could only find somebody to lend him the money----"
There was a ring of appeal in her voice which startled herself,
for she stopped, and looking nervously round at the stranger, said:
"I'm sure he would never regret it, sir. Magnus would work his
fingers to the bone to repay every penny. He has always been a boy
like that, and with better seasons and a little luck----"
It was then that the new scheme came to Christian
Christiansson and he covered his face with his hand to think of it,
whereupon Anna, mistaking the meaning of the altered gesture,
faltered and began again.
"I'm taking a great liberty, sir, but I'm not thinking of myself--
I'm thinking of my son. In one sense I'm to blame for all that has
happened to him. He doesn't know it and I daren't tell him, but I
am."
Christian Christiansson looked up at her.
"It was all my fault that his father took the mortgage."
"Your fault?"
"Yes, sir. My husband loved the poor boy who is gone, but he
was the Governor of Iceland and every eye was on him to see that
he kept his own house in order, and but for me he might have let the
law take its course. I pleaded and prayed with him, thinking that we
ourselves would be the ones to suffer. But I only ruined one son in
trying to save the other--and I didn't save him."
Christian Christiansson dropped his head, for the waters of
bitterness were falling over him in a flood, and Anna, thinking she
had touched him, went on more eagerly:
"Then there's the girl, sir, my granddaughter. You've seen her
yourself, and you'll say she doesn't look like a servant, but if the
auction comes off she'll have to go out to service. They treat girls
shamefully in some farmhouses, and my son can not bear the
thought of it. Neither can I, for I can't help thinking of her father.
Whatever else he may have been he was a gentleman, and to think
of his daughter being a drudge to somebody----"
Anna's voice was faltering again, but after a moment she went
on bravely.
"As for myself, I'm an old woman, and a little misfortune more
or less doesn't matter to me now. My time is short in any case, and I
shall be glad to go when I'm called. Most of my loved ones are gone
already--my son and my granddaughter are all that are left--and if I
could feel that I was leaving them happy and comfortable----"
Christian Christiansson could bear no more. "Landlady," he said,
"I had set my heart on buying the farm--I had a particular reason for
wishing to buy it--but instead of doing so I'll lend your son the
money to pay the interest."
Anna's eyes opened wide in astonishment, and now that her
prayer was answered her breath seemed to be suspended. "You will,
sir?" she said.
"I will, on one condition.
"Oh, never mind the condition, let me go and tell him."
"My condition is that you give me the girl to adopt as my
daughter."
"Ah!"
"I'm a lonely person, too, though I'm not so old as you are, and
when I'm in England I haven't wife or child or mother or brother to
share my life with me. The girl's sweet face would be a great
comfort to me there, and I'm ready to pay this interest if you are
willing to let her go."
The light had died out of Anna's eyes--her head was down.
"I should give you every guarantee that she would be taken
care of. I am rich, as men of my class go, and she should want for
nothing."
"But I didn't think your condition would be like that, sir," said
Anna.
"Why not? Are you thinking of the girl or of yourself, landlady?"
"I am thinking of my son. No man was ever so wrapped up in a
child. He has had her nearly all her life, and he is very, very fond of
her. When she was little and the snow was deep as it is to-day he
used to take her to school on his shoulder, and at night when she
was sleepy he would carry her in his arms to bed. If she were his
own he could not love her more dearly. It is like fatherhood to him,
and he will never be a father now, because----"
Anna hesitated as if trying to say something which she was
afraid to say, and then through her gathering tears she blurted out
her secret.
"To tell you the truth, sir, he cared for her mother, but gave her
up to somebody else and she died, and from that day forward all the
best years of his life were wasted in a cruel longing for something to
love. Then the child came, and it was almost as if the mother herself
had sent her little one to comfort him. She could not love him, for
she loved the other one to the last, but the child might, and she has-
-God bless her, she has!"
Christian Christiansson was wrung to the heart, but he struggled
on. "So you think he could not part with the girl even for her own
welfare and happiness?"
"I don't say that, sir; and perhaps if it were put to him properly-
---"
"Put it yourself, landlady."
"I daren't! He might suppose that I was thinking of myself."
"And if he did, would that be such a serious matter? Can it be
nothing to him that his mother will be saved from being homeless if
no harm is to come to the girl? And no harm shall come to her--you
may take my word for that."
Anna thought for a moment and then she said, "You would tell
us where she is to go, and what she is to do, and how she is to be
brought up?"
"Indeed I would."
"She might write to us constantly and come to see us
sometimes, perhaps?"
"Certainly she might."
"After all, it would just be like going into service."
"Just."
"Only she would be a lady, not a servant?"
"Only that."
"You would be good to her? Something tells me you would. And
you would, wouldn't you?"
"I should be as good to the girl as if--as if I were her own
father," said Christian Christiansson.
Anna dried her eyes and said:
"I don't know what to say, sir--I really don't know what to say to
you."
"Say nothing to me--speak to your son, landlady."
"You will lend him the money to pay the interest immediately?"
"Immediately."
"Eight thousand crowns--you can find it all by nine o'clock to-
morrow morning?"
"See," said Christian Christiansson, taking the pocketbook out of
his breast-pocket, "there's enough in this purse to pay the interest
twenty times over. And I'll not lend the money to your son--I'll give it
to him if he will give me the girl instead."
"He will be sorry to part with her, but after all it will be one
mouth less to feed, and when I'm gone that will be another, and
then perhaps, having no burdens and no embarrassments----"
"Speak to him--he's here," said Christian Christiansson, and just
at that moment Magnus returned to the hall carrying a wooden bowl
of smoking bran.
Then in a low and trembling tone, hardly daring to raise her
eyes to his face, Anna told her son of the stranger's offer, dwelling
chiefly on the advantages to himself when Elin would be provided
for, and she herself would be under the earth, and he, no longer
crippled by grinding debt, would be able to pay his way and win
back his lost inheritance. But as she went on her voice faltered, and
her words became confused, for he was looking down at her with a
lowering brow, and at last she stopped altogether, saying:
"I didn't mean any harm, Magnus. I only thought----"
"You thought I could sacrifice Elin to save myself, mother," said
Magnus, and at that hard word Anna sank into a chair and sobbed.
Then Magnus turned to Christian Christiansson and said, "I'm
much obliged for your offer, sir, but my niece is not for sale."
With that he was passing out of the house, when Christian
Christiansson, who was quivering from head to foot, cried, "Wait!"
"Well?"
"You have decided for yourself fast enough--have you thought
of anybody else?"
"Who else is there to think about?"
"Your mother for one. If you refuse my offer and the house is
sold over your heads to-morrow morning, what is to become of
her?"
Magnus flushed as if an invisible hand had smitten him across
the face.
"What is to become of the girl, too--have you thought of that?
Have you a right to send her into service--to be a drudge to
somebody?"
Magnus was shuddering visibly--even the bowl was trembling in
his hands.
"No doubt you are fond of the girl and have been good to her,
but if she were your own daughter she would be a separate being,
and in a case like this you would have no right to speak for her."
"Then she shall speak for herself," said Magnus, and putting the
smoking bowl on the table he crossed to the inner door and cried in
an agitated voice, "Elin! Elin! Elin!"
In a moment the girl came running into the room with a look of
alarm, saying, "What is it? Has anything happened?"
"Listen!" said Magnus, and Christian Christiansson could see
that though his voice shook as if his soul were shaken he was trying
to speak calmly. "This gentleman," he said, "has told your
grandmother that he wishes to adopt you as a daughter, and he
offers to pay my debts if I am willing to let you go."
"Uncle!" cried the girl.
"I have told him you shall speak for yourself, and so you shall,
and whatever you decide to do your grandmother and I will agree
to."
"But, Uncle!"
"Don't speak yet, my child. It is only fair that you should hear
everything. Elin, I am a broken man and I have no longer a home to
offer you. After the auction to-morrow morning I don't know what is
to become of grandmother and you and me, or where we are to go
or what roof is to cover us. But this gentleman is rich, and he
promises to provide for you all your life, and to give you all you need
and everything you could wish for. If you stay with me you may
suffer privations, but if you go to him you will never know a poor
day again as long as you live."
His deep voice had all it could do to support itself, but he bore
up to the end, and then Anna, whose eyes were filling as fast as she
could wipe them, said:
"Isn't it wonderful, Elin? Isn't it like a miracle? Like an answer to
your prayer, my child, just when we were so low and downhearted?
The gentleman will satisfy us that you are going to a good Christian
home and that you will be properly brought up and cared for."
And then Christian Christiansson himself, though he could
scarcely speak for the contending emotions that shook Him to the
soul, stepped forward and said:
"Let me tell you who I am, Elin. We spoke of Christian
Christiansson the composer, and you sang his song to me and said
you would like to hear something about him. I am Christian
Christiansson."
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.

More than just a book-buying platform, we strive to be a bridge


connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.

Join us on a journey of knowledge exploration, passion nurturing, and


personal growth every day!

ebookbell.com

You might also like