%load_ext pretty_jupyter

Introduction - Loading Data

This walkthrough is part of the ECLR page.

Here we will demonstrate how to load data into Python. In Python, we can load data either from a file on our local system or directly from an online database. This walkthrough demonstrates both techniques using Python.

Preparing your workspace

As usual we begin a notebook or scriptfile by loading the libraries we anticipate to use.

# Importing the os module
import os
import pandas as pd
import numpy as np
from lets_plot import *
# Lets_plot requires a setup
LetsPlot.setup_html()

Later in this workthrough we will use a few more libraries/packages and we will import them then, when we introduce them. If you already know which packages you will use, it is easiest to add them to your list here.

File upload

When working with an existing data file in a Jupyter Notebook (or script file), you need to ensure that the file is located in the current working directory or specify its full path. For example, if you have saved mroz.csv in a folder named C:\Pycode, then you can change your working directory to that folder using the os module and the command below should read os.chdir("C:\Pycode").

# Set your working directory
os.chdir("C:/Pycode")  # Replace with your drive and path

# Check the current working directory
print("Current Working Directory:", os.getcwd())
Current Working Directory: C:\Pycode

Remember that the os.getcwd() gets the current working directory and tells you which folder Python currently uses as its default location for reading or saving files.

The data file we practice with here is a Comma-Separated Values (CSV) file. To load such a file in Python, we use the read_csv function from the pandas library, assuming that the data file is in the working directory:

# Load the CSV file
mydata = pd.read_csv("Mroz.csv")

If this worked, you should now be able to see an object called mydata in your list of variables.

A typical error message you could receive here is "FileNotFoundError: [Errno 2] No such file or directory: 'Mroz.csv'". If you get this message the most likely reason is that the file Mroz.csv is not in the place where Python is looking. Either it is not in the working directory, or you did not set the working directory correctly.

Remember that you can use the following functions to get some guidance in the use of this function:

  • Use the help() function to view detailed documentation.
  • Use the ? or ?? syntax in Jupyter Notebook for quick insights or to explore the source code.

An example could be:

# Get help for read_csv, any of these will access help
#help(pd.read_csv)
pd.read_csv?
#pd.read_csv??
Signature:
pd.read_csv(
    filepath_or_buffer: 'FilePath | ReadCsvBuffer[bytes] | ReadCsvBuffer[str]',
    sep=<no_default>,
    delimiter=None,
    header='infer',
    names=<no_default>,
    index_col=None,
    usecols=None,
    squeeze=None,
    prefix=<no_default>,
    mangle_dupe_cols=True,
    dtype: 'DtypeArg | None' = None,
    engine: 'CSVEngine | None' = None,
    converters=None,
    true_values=None,
    false_values=None,
    skipinitialspace=False,
    skiprows=None,
    skipfooter=0,
    nrows=None,
    na_values=None,
    keep_default_na=True,
    na_filter=True,
    verbose=False,
    skip_blank_lines=True,
    parse_dates=None,
    infer_datetime_format=False,
    keep_date_col=False,
    date_parser=None,
    dayfirst=False,
    cache_dates=True,
    iterator=False,
    chunksize=None,
    compression: 'CompressionOptions' = 'infer',
    thousands=None,
    decimal: 'str' = '.',
    lineterminator=None,
    quotechar='"',
    quoting=0,
    doublequote=True,
    escapechar=None,
    comment=None,
    encoding=None,
    encoding_errors: 'str | None' = 'strict',
    dialect=None,
    error_bad_lines=None,
    warn_bad_lines=None,
    on_bad_lines=None,
    delim_whitespace=False,
    low_memory=True,
    memory_map=False,
    float_precision=None,
    storage_options: 'StorageOptions' = None,
)
Docstring:
Read a comma-separated values (csv) file into DataFrame.

Also supports optionally iterating or breaking of the file
into chunks.

Additional help can be found in the online docs for
`IO Tools <https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html>`_.

Parameters
----------
filepath_or_buffer : str, path object or file-like object
    Any valid string path is acceptable. The string could be a URL. Valid
    URL schemes include http, ftp, s3, gs, and file. For file URLs, a host is
    expected. A local file could be: file://localhost/path/to/table.csv.

    If you want to pass in a path object, pandas accepts any ``os.PathLike``.

    By file-like object, we refer to objects with a ``read()`` method, such as
    a file handle (e.g. via builtin ``open`` function) or ``StringIO``.
sep : str, default ','
    Delimiter to use. If sep is None, the C engine cannot automatically detect
    the separator, but the Python parsing engine can, meaning the latter will
    be used and automatically detect the separator by Python's builtin sniffer
    tool, ``csv.Sniffer``. In addition, separators longer than 1 character and
    different from ``'\s+'`` will be interpreted as regular expressions and
    will also force the use of the Python parsing engine. Note that regex
    delimiters are prone to ignoring quoted data. Regex example: ``'\r\t'``.
delimiter : str, default ``None``
    Alias for sep.
header : int, list of int, None, default 'infer'
    Row number(s) to use as the column names, and the start of the
    data.  Default behavior is to infer the column names: if no names
    are passed the behavior is identical to ``header=0`` and column
    names are inferred from the first line of the file, if column
    names are passed explicitly then the behavior is identical to
    ``header=None``. Explicitly pass ``header=0`` to be able to
    replace existing names. The header can be a list of integers that
    specify row locations for a multi-index on the columns
    e.g. [0,1,3]. Intervening rows that are not specified will be
    skipped (e.g. 2 in this example is skipped). Note that this
    parameter ignores commented lines and empty lines if
    ``skip_blank_lines=True``, so ``header=0`` denotes the first line of
    data rather than the first line of the file.
names : array-like, optional
    List of column names to use. If the file contains a header row,
    then you should explicitly pass ``header=0`` to override the column names.
    Duplicates in this list are not allowed.
index_col : int, str, sequence of int / str, or False, optional, default ``None``
  Column(s) to use as the row labels of the ``DataFrame``, either given as
  string name or column index. If a sequence of int / str is given, a
  MultiIndex is used.

  Note: ``index_col=False`` can be used to force pandas to *not* use the first
  column as the index, e.g. when you have a malformed file with delimiters at
  the end of each line.
usecols : list-like or callable, optional
    Return a subset of the columns. If list-like, all elements must either
    be positional (i.e. integer indices into the document columns) or strings
    that correspond to column names provided either by the user in `names` or
    inferred from the document header row(s). If ``names`` are given, the document
    header row(s) are not taken into account. For example, a valid list-like
    `usecols` parameter would be ``[0, 1, 2]`` or ``['foo', 'bar', 'baz']``.
    Element order is ignored, so ``usecols=[0, 1]`` is the same as ``[1, 0]``.
    To instantiate a DataFrame from ``data`` with element order preserved use
    ``pd.read_csv(data, usecols=['foo', 'bar'])[['foo', 'bar']]`` for columns
    in ``['foo', 'bar']`` order or
    ``pd.read_csv(data, usecols=['foo', 'bar'])[['bar', 'foo']]``
    for ``['bar', 'foo']`` order.

    If callable, the callable function will be evaluated against the column
    names, returning names where the callable function evaluates to True. An
    example of a valid callable argument would be ``lambda x: x.upper() in
    ['AAA', 'BBB', 'DDD']``. Using this parameter results in much faster
    parsing time and lower memory usage.
squeeze : bool, default False
    If the parsed data only contains one column then return a Series.

    .. deprecated:: 1.4.0
        Append ``.squeeze("columns")`` to the call to ``read_csv`` to squeeze
        the data.
prefix : str, optional
    Prefix to add to column numbers when no header, e.g. 'X' for X0, X1, ...

    .. deprecated:: 1.4.0
       Use a list comprehension on the DataFrame's columns after calling ``read_csv``.
mangle_dupe_cols : bool, default True
    Duplicate columns will be specified as 'X', 'X.1', ...'X.N', rather than
    'X'...'X'. Passing in False will cause data to be overwritten if there
    are duplicate names in the columns.
dtype : Type name or dict of column -> type, optional
    Data type for data or columns. E.g. {'a': np.float64, 'b': np.int32,
    'c': 'Int64'}
    Use `str` or `object` together with suitable `na_values` settings
    to preserve and not interpret dtype.
    If converters are specified, they will be applied INSTEAD
    of dtype conversion.
engine : {'c', 'python', 'pyarrow'}, optional
    Parser engine to use. The C and pyarrow engines are faster, while the python engine
    is currently more feature-complete. Multithreading is currently only supported by
    the pyarrow engine.

    .. versionadded:: 1.4.0

        The "pyarrow" engine was added as an *experimental* engine, and some features
        are unsupported, or may not work correctly, with this engine.
converters : dict, optional
    Dict of functions for converting values in certain columns. Keys can either
    be integers or column labels.
true_values : list, optional
    Values to consider as True.
false_values : list, optional
    Values to consider as False.
skipinitialspace : bool, default False
    Skip spaces after delimiter.
skiprows : list-like, int or callable, optional
    Line numbers to skip (0-indexed) or number of lines to skip (int)
    at the start of the file.

    If callable, the callable function will be evaluated against the row
    indices, returning True if the row should be skipped and False otherwise.
    An example of a valid callable argument would be ``lambda x: x in [0, 2]``.
skipfooter : int, default 0
    Number of lines at bottom of file to skip (Unsupported with engine='c').
nrows : int, optional
    Number of rows of file to read. Useful for reading pieces of large files.
na_values : scalar, str, list-like, or dict, optional
    Additional strings to recognize as NA/NaN. If dict passed, specific
    per-column NA values.  By default the following values are interpreted as
    NaN: '', '#N/A', '#N/A N/A', '#NA', '-1.#IND', '-1.#QNAN', '-NaN', '-nan',
    '1.#IND', '1.#QNAN', '<NA>', 'N/A', 'NA', 'NULL', 'NaN', 'n/a',
    'nan', 'null'.
keep_default_na : bool, default True
    Whether or not to include the default NaN values when parsing the data.
    Depending on whether `na_values` is passed in, the behavior is as follows:

    * If `keep_default_na` is True, and `na_values` are specified, `na_values`
      is appended to the default NaN values used for parsing.
    * If `keep_default_na` is True, and `na_values` are not specified, only
      the default NaN values are used for parsing.
    * If `keep_default_na` is False, and `na_values` are specified, only
      the NaN values specified `na_values` are used for parsing.
    * If `keep_default_na` is False, and `na_values` are not specified, no
      strings will be parsed as NaN.

    Note that if `na_filter` is passed in as False, the `keep_default_na` and
    `na_values` parameters will be ignored.
na_filter : bool, default True
    Detect missing value markers (empty strings and the value of na_values). In
    data without any NAs, passing na_filter=False can improve the performance
    of reading a large file.
verbose : bool, default False
    Indicate number of NA values placed in non-numeric columns.
skip_blank_lines : bool, default True
    If True, skip over blank lines rather than interpreting as NaN values.
parse_dates : bool or list of int or names or list of lists or dict, default False
    The behavior is as follows:

    * boolean. If True -> try parsing the index.
    * list of int or names. e.g. If [1, 2, 3] -> try parsing columns 1, 2, 3
      each as a separate date column.
    * list of lists. e.g.  If [[1, 3]] -> combine columns 1 and 3 and parse as
      a single date column.
    * dict, e.g. {'foo' : [1, 3]} -> parse columns 1, 3 as date and call
      result 'foo'

    If a column or index cannot be represented as an array of datetimes,
    say because of an unparsable value or a mixture of timezones, the column
    or index will be returned unaltered as an object data type. For
    non-standard datetime parsing, use ``pd.to_datetime`` after
    ``pd.read_csv``. To parse an index or column with a mixture of timezones,
    specify ``date_parser`` to be a partially-applied
    :func:`pandas.to_datetime` with ``utc=True``. See
    :ref:`io.csv.mixed_timezones` for more.

    Note: A fast-path exists for iso8601-formatted dates.
infer_datetime_format : bool, default False
    If True and `parse_dates` is enabled, pandas will attempt to infer the
    format of the datetime strings in the columns, and if it can be inferred,
    switch to a faster method of parsing them. In some cases this can increase
    the parsing speed by 5-10x.
keep_date_col : bool, default False
    If True and `parse_dates` specifies combining multiple columns then
    keep the original columns.
date_parser : function, optional
    Function to use for converting a sequence of string columns to an array of
    datetime instances. The default uses ``dateutil.parser.parser`` to do the
    conversion. Pandas will try to call `date_parser` in three different ways,
    advancing to the next if an exception occurs: 1) Pass one or more arrays
    (as defined by `parse_dates`) as arguments; 2) concatenate (row-wise) the
    string values from the columns defined by `parse_dates` into a single array
    and pass that; and 3) call `date_parser` once for each row using one or
    more strings (corresponding to the columns defined by `parse_dates`) as
    arguments.
dayfirst : bool, default False
    DD/MM format dates, international and European format.
cache_dates : bool, default True
    If True, use a cache of unique, converted dates to apply the datetime
    conversion. May produce significant speed-up when parsing duplicate
    date strings, especially ones with timezone offsets.

    .. versionadded:: 0.25.0
iterator : bool, default False
    Return TextFileReader object for iteration or getting chunks with
    ``get_chunk()``.

    .. versionchanged:: 1.2

       ``TextFileReader`` is a context manager.
chunksize : int, optional
    Return TextFileReader object for iteration.
    See the `IO Tools docs
    <https://pandas.pydata.org/pandas-docs/stable/io.html#io-chunking>`_
    for more information on ``iterator`` and ``chunksize``.

    .. versionchanged:: 1.2

       ``TextFileReader`` is a context manager.
compression : str or dict, default 'infer'
    For on-the-fly decompression of on-disk data. If 'infer' and '%s' is
    path-like, then detect compression from the following extensions: '.gz',
    '.bz2', '.zip', '.xz', or '.zst' (otherwise no compression). If using
    'zip', the ZIP file must contain only one data file to be read in. Set to
    ``None`` for no decompression. Can also be a dict with key ``'method'`` set
    to one of {``'zip'``, ``'gzip'``, ``'bz2'``, ``'zstd'``} and other
    key-value pairs are forwarded to ``zipfile.ZipFile``, ``gzip.GzipFile``,
    ``bz2.BZ2File``, or ``zstandard.ZstdDecompressor``, respectively. As an
    example, the following could be passed for Zstandard decompression using a
    custom compression dictionary:
    ``compression={'method': 'zstd', 'dict_data': my_compression_dict}``.

    .. versionchanged:: 1.4.0 Zstandard support.

thousands : str, optional
    Thousands separator.
decimal : str, default '.'
    Character to recognize as decimal point (e.g. use ',' for European data).
lineterminator : str (length 1), optional
    Character to break file into lines. Only valid with C parser.
quotechar : str (length 1), optional
    The character used to denote the start and end of a quoted item. Quoted
    items can include the delimiter and it will be ignored.
quoting : int or csv.QUOTE_* instance, default 0
    Control field quoting behavior per ``csv.QUOTE_*`` constants. Use one of
    QUOTE_MINIMAL (0), QUOTE_ALL (1), QUOTE_NONNUMERIC (2) or QUOTE_NONE (3).
doublequote : bool, default ``True``
   When quotechar is specified and quoting is not ``QUOTE_NONE``, indicate
   whether or not to interpret two consecutive quotechar elements INSIDE a
   field as a single ``quotechar`` element.
escapechar : str (length 1), optional
    One-character string used to escape other characters.
comment : str, optional
    Indicates remainder of line should not be parsed. If found at the beginning
    of a line, the line will be ignored altogether. This parameter must be a
    single character. Like empty lines (as long as ``skip_blank_lines=True``),
    fully commented lines are ignored by the parameter `header` but not by
    `skiprows`. For example, if ``comment='#'``, parsing
    ``#empty\na,b,c\n1,2,3`` with ``header=0`` will result in 'a,b,c' being
    treated as the header.
encoding : str, optional
    Encoding to use for UTF when reading/writing (ex. 'utf-8'). `List of Python
    standard encodings
    <https://docs.python.org/3/library/codecs.html#standard-encodings>`_ .

    .. versionchanged:: 1.2

       When ``encoding`` is ``None``, ``errors="replace"`` is passed to
       ``open()``. Otherwise, ``errors="strict"`` is passed to ``open()``.
       This behavior was previously only the case for ``engine="python"``.

    .. versionchanged:: 1.3.0

       ``encoding_errors`` is a new argument. ``encoding`` has no longer an
       influence on how encoding errors are handled.

encoding_errors : str, optional, default "strict"
    How encoding errors are treated. `List of possible values
    <https://docs.python.org/3/library/codecs.html#error-handlers>`_ .

    .. versionadded:: 1.3.0

dialect : str or csv.Dialect, optional
    If provided, this parameter will override values (default or not) for the
    following parameters: `delimiter`, `doublequote`, `escapechar`,
    `skipinitialspace`, `quotechar`, and `quoting`. If it is necessary to
    override values, a ParserWarning will be issued. See csv.Dialect
    documentation for more details.
error_bad_lines : bool, optional, default ``None``
    Lines with too many fields (e.g. a csv line with too many commas) will by
    default cause an exception to be raised, and no DataFrame will be returned.
    If False, then these "bad lines" will be dropped from the DataFrame that is
    returned.

    .. deprecated:: 1.3.0
       The ``on_bad_lines`` parameter should be used instead to specify behavior upon
       encountering a bad line instead.
warn_bad_lines : bool, optional, default ``None``
    If error_bad_lines is False, and warn_bad_lines is True, a warning for each
    "bad line" will be output.

    .. deprecated:: 1.3.0
       The ``on_bad_lines`` parameter should be used instead to specify behavior upon
       encountering a bad line instead.
on_bad_lines : {'error', 'warn', 'skip'} or callable, default 'error'
    Specifies what to do upon encountering a bad line (a line with too many fields).
    Allowed values are :

        - 'error', raise an Exception when a bad line is encountered.
        - 'warn', raise a warning when a bad line is encountered and skip that line.
        - 'skip', skip bad lines without raising or warning when they are encountered.

    .. versionadded:: 1.3.0

    .. versionadded:: 1.4.0

        - callable, function with signature
          ``(bad_line: list[str]) -> list[str] | None`` that will process a single
          bad line. ``bad_line`` is a list of strings split by the ``sep``.
          If the function returns ``None``, the bad line will be ignored.
          If the function returns a new list of strings with more elements than
          expected, a ``ParserWarning`` will be emitted while dropping extra elements.
          Only supported when ``engine="python"``

delim_whitespace : bool, default False
    Specifies whether or not whitespace (e.g. ``' '`` or ``'    '``) will be
    used as the sep. Equivalent to setting ``sep='\s+'``. If this option
    is set to True, nothing should be passed in for the ``delimiter``
    parameter.
low_memory : bool, default True
    Internally process the file in chunks, resulting in lower memory use
    while parsing, but possibly mixed type inference.  To ensure no mixed
    types either set False, or specify the type with the `dtype` parameter.
    Note that the entire file is read into a single DataFrame regardless,
    use the `chunksize` or `iterator` parameter to return the data in chunks.
    (Only valid with C parser).
memory_map : bool, default False
    If a filepath is provided for `filepath_or_buffer`, map the file object
    directly onto memory and access the data directly from there. Using this
    option can improve performance because there is no longer any I/O overhead.
float_precision : str, optional
    Specifies which converter the C engine should use for floating-point
    values. The options are ``None`` or 'high' for the ordinary converter,
    'legacy' for the original lower precision pandas converter, and
    'round_trip' for the round-trip converter.

    .. versionchanged:: 1.2

storage_options : dict, optional
    Extra options that make sense for a particular storage connection, e.g.
    host, port, username, password, etc. For HTTP(S) URLs the key-value pairs
    are forwarded to ``urllib`` as header options. For other URLs (e.g.
    starting with "s3://", and "gcs://") the key-value pairs are forwarded to
    ``fsspec``. Please see ``fsspec`` and ``urllib`` for more details.

    .. versionadded:: 1.2

Returns
-------
DataFrame or TextParser
    A comma-separated values (csv) file is returned as two-dimensional
    data structure with labeled axes.

See Also
--------
DataFrame.to_csv : Write DataFrame to a comma-separated values (csv) file.
read_csv : Read a comma-separated values (csv) file into DataFrame.
read_fwf : Read a table of fixed-width formatted lines into DataFrame.

Examples
--------
>>> pd.read_csv('data.csv')  # doctest: +SKIP
File:      c:\users\msassrb2\anaconda3\lib\site-packages\pandas\io\parsers\readers.py
Type:      function

The pd.read_csv() function reads the csv file and creates a DataFrame (a table-like structure) in Python.

Now, let's load the datafile again after correcting the error:

In Python's Jupyter Notebook, you have several options to explore and understand your data, helping you get a good "sense" of the dataset you're working with. These tools provide insights into the structure, content, and summary statistics of your data. Let's start by getting a first glimpse at the data using the info() function:

# Display structure and types of columns
mydata.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 753 entries, 0 to 752
Data columns (total 22 columns):
 #   Column    Non-Null Count  Dtype  
---  ------    --------------  -----  
 0   inlf      753 non-null    int64  
 1   hours     753 non-null    int64  
 2   kidslt6   753 non-null    int64  
 3   kidsge6   753 non-null    int64  
 4   age       753 non-null    int64  
 5   educ      753 non-null    int64  
 6   wage      753 non-null    object 
 7   repwage   753 non-null    float64
 8   hushrs    753 non-null    int64  
 9   husage    753 non-null    int64  
 10  huseduc   753 non-null    int64  
 11  huswage   753 non-null    float64
 12  faminc    753 non-null    int64  
 13  mtr       753 non-null    float64
 14  motheduc  753 non-null    int64  
 15  fatheduc  753 non-null    int64  
 16  unem      753 non-null    float64
 17  city      753 non-null    int64  
 18  exper     753 non-null    int64  
 19  nwifeinc  753 non-null    float64
 20  lwage     753 non-null    object 
 21  expersq   753 non-null    int64  
dtypes: float64(5), int64(15), object(2)
memory usage: 129.5+ KB

The info() function provides a concise summary of the DataFrame, including:

  • The number of rows and columns.
  • Column names and their data types.
  • Number of non-missing values in each column

The dataset has 753 observations (rows) and 22 columns (variables). Most of the data are recognised as numerical data types, such as int64 (for integer values) and float64 (for decimal values). However, you can see that two columns, namely wage and lwageare recognised as objects, which is Python's generic type for non-numeric data (e.g., strings or mixed types). Why didn't Python recognise wage and lwage as numeric?

As we explore our data we can see that the wage column and therefore the lwage column contain observations which do not have a number but rather a ".". This is this spreadsheet’s way of telling you that for these observations there is no wage information. The information is missing. Different spreadsheets code missing values in different ways. Sometimes it will just be empty cells; sometimes it will say “NA” or “na”. You need to help Python to recognise missing values. That is what the na_values="." option in the read_csv function does.

loading data missing valuesJPG.JPG

# Handle missing data
mydata = pd.read_csv("Mroz.csv", na_values=".")

# Verify the updated column types
mydata.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 753 entries, 0 to 752
Data columns (total 22 columns):
 #   Column    Non-Null Count  Dtype  
---  ------    --------------  -----  
 0   inlf      753 non-null    int64  
 1   hours     753 non-null    int64  
 2   kidslt6   753 non-null    int64  
 3   kidsge6   753 non-null    int64  
 4   age       753 non-null    int64  
 5   educ      753 non-null    int64  
 6   wage      428 non-null    float64
 7   repwage   753 non-null    float64
 8   hushrs    753 non-null    int64  
 9   husage    753 non-null    int64  
 10  huseduc   753 non-null    int64  
 11  huswage   753 non-null    float64
 12  faminc    753 non-null    int64  
 13  mtr       753 non-null    float64
 14  motheduc  753 non-null    int64  
 15  fatheduc  753 non-null    int64  
 16  unem      753 non-null    float64
 17  city      753 non-null    int64  
 18  exper     753 non-null    int64  
 19  nwifeinc  753 non-null    float64
 20  lwage     428 non-null    float64
 21  expersq   753 non-null    int64  
dtypes: float64(7), int64(15)
memory usage: 129.5 KB

The na_values="." tells pandas to interpret cells with "." as missing values (NaN) in the DataFrame. After reloading the dataset, mydata.info() will show the updated data types, where observations in wage and lwage previously containing "." will now have missing values (NaN) and be treated as numerical data.

To check the updated dataset, we can use the iloc[] function, which allows us to slice the data in Python and display specific rows. In this case, we want to select rows 430 through 440. See this walkthrough for more advice on how to access particular subsets of your data.

# Check rows 425 to 430, note Python starts counting at 0, and does not include the last referenced row
mydata.iloc[425:431]
inlf hours kidslt6 kidsge6 age educ wage repwage hushrs husage ... faminc mtr motheduc fatheduc unem city exper nwifeinc lwage expersq
425 1 2144 0 2 43 13 5.8675 0.00 2140 43 ... 34220 0.5815 7 7 7.5 1 22 21.64008 1.769429 484
426 1 1760 0 1 33 12 3.4091 3.21 3380 34 ... 30000 0.5815 12 16 11.0 1 14 23.99998 1.226448 196
427 1 490 0 1 30 12 4.0816 2.46 2430 33 ... 18000 0.6915 12 12 7.5 1 7 16.00002 1.406489 49
428 0 0 0 1 49 12 NaN 0.00 2550 54 ... 21025 0.6615 14 12 7.5 1 2 21.02500 NaN 4
429 0 0 2 0 30 16 NaN 0.00 1928 34 ... 23600 0.6615 14 7 9.5 1 5 23.60000 NaN 25
430 0 0 1 0 30 12 NaN 0.00 1100 39 ... 22800 0.6615 12 12 7.5 0 12 22.80000 NaN 144

6 rows × 22 columns

You can now observe that the observations in wage and lwage, which previously contained "." (e.g. rows 428 to 430), have been replaced with missing values (NaN). This allows these columns to be correctly treated as numerical data.

However, what if your data comes as an excel file, such as mroz.xlsx? In this case, you can use the read_excel function (assuming that yo downloaded that file into your working directory).

# Load an Excel file
mydata_excel = pd.read_excel("Mroz.xlsx", na_values=".")

# Display rows 425 to 430 to confirm that NaNs were recognised 
mydata_excel.iloc[425:431]
inlf hours kidslt6 kidsge6 age educ wage repwage hushrs husage ... faminc mtr motheduc fatheduc unem city exper nwifeinc lwage expersq
425 1 2144 0 2 43 13 5.8675 0.00 2140 43 ... 34220 0.5815 7 7 7.5 1 22 21.64008 1.769429 484
426 1 1760 0 1 33 12 3.4091 3.21 3380 34 ... 30000 0.5815 12 16 11.0 1 14 23.99998 1.226448 196
427 1 490 0 1 30 12 4.0816 2.46 2430 33 ... 18000 0.6915 12 12 7.5 1 7 16.00002 1.406489 49
428 0 0 0 1 49 12 NaN 0.00 2550 54 ... 21025 0.6615 14 12 7.5 1 2 21.02500 NaN 4
429 0 0 2 0 30 16 NaN 0.00 1928 34 ... 23600 0.6615 14 7 9.5 1 5 23.60000 NaN 25
430 0 0 1 0 30 12 NaN 0.00 1100 39 ... 22800 0.6615 12 12 7.5 0 12 22.80000 NaN 144

6 rows × 22 columns

The csv file (Mroz.csv) you downloaded earlier can also be accessed directly from a place on the internet. On this occasion you get this if you click on the Raw button on this page You then get to this page (https://raw.githubusercontent.com/datasquad/ECLR/refs/heads/gh-pages/data/Mroz.csv) which basically just contains the csv file, data separated by commas.

Such a url can be used directly to access the csv file as follows:

# Load the CSV file
mydata_direct = pd.read_csv("https://raw.githubusercontent.com/datasquad/ECLR/refs/heads/gh-pages/data/Mroz.csv",
                            na_values=".")

This means that there is no need to download the data, but yo are relying on that url not changing through time and you need to be online when you work. It is often saver to download the file. A direct url is particularly useful however if you access data that are regularly updated.

In Python, there several packages that allow you to easily download data directly within your code. These data are fetched on demand and are not stored on your computer, which is highly convenient. However, this approach requires an active internet connection while working.

The packages we will explore include:

  • yfinance, is used to download financial data, such as stock prices and market indices.
  • pandas_datareader, for accessing economic and financial datasets from various online sources, like Yahoo Finance, FRED, or World Bank.

yfinance

We can use the yfinance package to download data directly from Yahoo Finance. If you never used this package you will first have to install the package (pip install yfinance in your Terminal).

Once we have installed the appropriate package we can now demonstrate how to download financial data with Yahoo Finance. More specifically, let's download the S&P 500 index (6GSPC) data from Yahoo Finance.

# Import yfinance
import yfinance as yf

# Download S&P 500 data
sp500 = yf.download("^GSPC", start="1960-01-04", end="2024-01-01")

# Display the first few rows
sp500.tail()
Price Close High Low Open Volume
Ticker ^GSPC ^GSPC ^GSPC ^GSPC ^GSPC
Date
2023-12-22 4754.629883 4772.939941 4736.770020 4753.919922 3046770000
2023-12-26 4774.750000 4784.720215 4758.450195 4758.859863 2513910000
2023-12-27 4781.580078 4785.390137 4768.899902 4773.450195 2748450000
2023-12-28 4783.350098 4793.299805 4780.979980 4786.439941 2698860000
2023-12-29 4769.830078 4788.430176 4751.990234 4782.879883 3126060000

The import yfinance as yf, imports the yfinance library for downloading financial data. Then the yf.download() function downloads the stock price or index data from Yahoo Finance. The "^GSPC" is the symbol used for the S&P 500 index and at the same time we use the start and end to specify the date range that we want to focus on from the dataset. After running this line of code we could run the sp500.tail() command to get a display of the last 5 rows of the S&P 500 data.

It is also possible in Python to donwload multiple series at the same time, say share prices for Amazon (AMZN) and Fedex (FDX).

# Download multiple stocks
stocks = yf.download(["AMZN", "FDX"], start="2000-01-04", end="2024-01-01")

# Display the first few rows
stocks.tail()
Price Close High Low Open Volume
Ticker AMZN FDX AMZN FDX AMZN FDX AMZN FDX AMZN FDX
Date
2023-12-22 153.419998 243.041031 154.350006 244.403071 152.710007 240.904887 153.770004 242.247326 29480100 3343100
2023-12-26 153.410004 246.921387 153.979996 248.195226 153.029999 244.187497 153.559998 244.971409 25067200 3594500
2023-12-27 153.339996 245.892502 154.779999 249.527869 153.119995 245.676926 153.559998 247.675886 31434700 3134400
2023-12-28 153.380005 248.479401 154.080002 248.871349 152.949997 245.559346 153.720001 245.735718 27057000 2246900
2023-12-29 151.940002 247.881668 153.889999 250.488167 151.029999 246.803788 153.100006 248.959548 39789000 1947400

As you can indicate from the ouput provided, the yf.download(["AMZN", "FDX"], function fetches the stock prices for both companies over the specified date range.

pandas_datareader

In Python, a commonly used equivalent for accessing online databases and downloading data in a time-series format is the pandas_datareader library. It integrates seamlessly with pandas and supports downloading financial and economic data from various sources, including FRED, Yahoo Finance, World Bank, and others. To install this package before your first use run pip install pandas-datareader in your Terminal.

Let's import what we need as follows:

from pandas_datareader import data as pdr

What this has done is that it has gone to the pandas_datareader library. That library has a number of different modules and we only wish to access the data module. We also specify that we shall address this with the prefix pdr. For a more detailed description of how to load libraries have a look at this walkthrough.

If you are interested in analyzing time series data, such as trends in U.S. Public Debt, you can obtain this data from the FRED database, maintained by the Federal Reserve Bank of St. Louis. This data can be accessed programmatically in Python using the pdr.DataReader function from the pandas_datareader library.

To retrieve data from FRED, you need the specific series identifier for your desired dataset. For instance, if you want to analyze the size of U.S. public debt, the relevant indicator is GFDEBTN. You can search for this or other indicators directly on the FRED website to find their corresponding identifiers. This streamlined approach enables efficient data retrieval for analysis.

We load the data using debt_data = pdr.DataReader(name = "GFDEBTN", data_source = "fred"). The data_source tells the function on which database to look for the data, and data indicates which exact data series you are looking for. You can find a list of available data sources from the function's documentation. Recall that you can call up help on this function through pdr.DataReader?.

# Download data from FRED
debt_data = pdr.DataReader(name = "GFDEBTN", data_source = "fred", start = '1970-01-01', end = '2024-01-01')

Let's now display the dataframe information.

# Display the first few rows
debt_data.info()
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 217 entries, 1970-01-01 to 2024-01-01
Data columns (total 1 columns):
 #   Column   Non-Null Count  Dtype
---  ------   --------------  -----
 0   GFDEBTN  217 non-null    int64
dtypes: int64(1)
memory usage: 3.4 KB

It has one variable, GFDEBTN, and the index is a time index (DatetimeIndex: 19 entries, 2020-01-01 to 2024-07-01).

Let's say now that you want to plot the data. In this case, you can use the ggplot function from the lets_plot library (see more guidance in this walkthrough). This requires an explicit date series and therefore we use the index to define a new series first.

#debt_data['Date'] = pd.to_datetime(debt_data.index)
debt_data['Date'] = np.arange(1970.0,2024.25,0.25)
#debt_data.info()
from datetime import datetime
DATE
1970-01-01   1970-01-01
1970-04-01   1970-04-01
1970-07-01   1970-07-01
1970-10-01   1970-10-01
1971-01-01   1971-01-01
                ...    
2023-01-01   2023-01-01
2023-04-01   2023-04-01
2023-07-01   2023-07-01
2023-10-01   2023-10-01
2024-01-01   2024-01-01
Name: Date, Length: 217, dtype: datetime64[ns]

You can now see that there are two data series, an additional Date series. Now we can use the ggplot function.

(
    ggplot(debt_data, aes(x='Date', y = 'GFDEBTN')) + 
        geom_line() +
        labs(title="U.S. Public Debt (GFDEBTN)",
             x = "Time",
             y = "Public Debt (in billions USD)")
)

What conclusions can you make from the graph? The graph shows a significant rise in U.S. public debt starting in 2020, driven by pandemic-related fiscal measures, particularly emergency spending to support the economy during the COVID-19 pandemic. This sharp increase was followed by a steady upward trend through 2024, reflecting ongoing budget deficits and borrowing. By 2024, the total public debt reaches approximately $35 trillion.

Summary

In this walkthrough, you learned how to load data into Python using two techniques: loading data from a file on your computer (e.g., CSV or EXCEL files) and retrieving data directly from an online database (e.g., FRED using pandas_datareader). You may encounter other datasets you want to imporrt (eg. STATA or SAS) and for many of these the pandas library will have the right function. The internet is your friend. If you, for instance, search for "Python import STATA file" you will be directed to good advice.

This walkthrough is part of the ECLR page.