Functions¶

Applied Review¶

Conditions¶

  • Conditions allow us to execute different chunks of code depending on whether a condition is true or false.
  • The condition syntax is
if condition:
    my_code()
else:
    my_other_code()

Iteration¶

  • Python supports several kinds of iteration structures, which we generally call loops.
  • for loops iterate through elements in a collection
for x in collection:
        do_something_with_x()
  • while loops run until a condition is no longer true
while x > 3:
        do_something()

DRY¶

A fundamental precept of good programming is Don't Repeat Yourself, often abbreviated DRY. Repetition can happen when you want to do one operation (or a slight variant) several times and simply copy and paste your code to achieve that goal.

Copy-pasting is almost always a red flag that you're violating DRY!

Repetition leads to a few problems:

  • Longer, more verbose code
  • Worse readability
    • Others have to spend a lot of time looking through your code to realize you're doing the same thing over and over.
  • Difficulty in updating methodology
    • If you want to change something about the code block you repeated, you have to change it everywhere that code occurs.
    • And this can lead to errors -- manually changing things multiple times is mistake-prone

Functions to the Rescue¶

The best solution to DRY is usually functions.

Functions are code blocks that can be saved. Functions have names, and if they're named well you can easily understand what they're for.

In [1]:
mylist = ['brad', 'ethan']
len(mylist)
Out[1]:
2

len is a function to return the length of a list. Functions that come with Python tend to have short names since they're used so much.

len abstracts away a block of code so we don't have to think about how it works. But what might be inside the len function?

In [2]:
counter = 0
for item in mylist:
    counter = counter + 1
print(counter)
2

The great thing about functions, like len, is that they allow us to avoid rewriting the underlying logic (like the above for loop) every time we want to do a common operation.

Functions in other libraries are often named more verbosely -- which can be helpful since it tells us how to use them.

In [3]:
date_string = '2019-01-01'
date_string
Out[3]:
'2019-01-01'
In [4]:
import pandas as pd
# Convert the date string into a timestamp
pd.to_datetime(date_string)
Out[4]:
Timestamp('2019-01-01 00:00:00')

Pandas' to_datetime function converts an object into a timestamp.

Terminology¶

The most fundamental property of a function -- both in math and in programming -- is that it transforms inputs into outputs.

For example, absolute value is a function. The absolute value of x (in math, often written |x|) is x when x is positive, but (-x) when x is negative.

x f(x)
1 1
2 2
-1 1
-5 5

Python has a built-in version of the absolute value function.

In [5]:
abs(1)
Out[5]:
1
In [6]:
abs(-5)
Out[6]:
5

In the context of functions, inputs are called arguments, and outputs are called return values.

In abs(-5), the function argument is -5 and the return value is 5.

Defining Your Own Functions¶

You've used plenty of functions that others have written for you, but as your Python projects become more complicated you'll want to begin writing your own functions to follow the DRY principle.

In Python, functions are created using two new keywords, def (as in define) and return. The general structure is:

def myfunction(arguments):
    code_block
    return return_value

The return keyword is optional -- your function doesn't have to return a value. It might do something else, like modify a DataFrame.

But if your function produces some kind of output, return is the way to express that.

Let's write a function that doubles a number and call that function double.

In [7]:
def double(number):
    doubled_number = number * 2
    return doubled_number

We can call our new function the same way we would with any function in Python.

In [8]:
double(3)
Out[8]:
6
In [9]:
x = 5
double(x)
Out[9]:
10

double works just the same as abs -- in Python, there's nothing stopping you from building new functions that work as seamlessly as the built-in functions.

Functions can take multiple arguments. We could write a function to return the product of two numbers.

In [10]:
def multiply(x, y):
    product = x * y
    return product
In [11]:
multiply(7, 4)
Out[11]:
28

Note that the names we use for arguments and return values (here x, y, and product) aren't relevant outside the function. We say that they exist only within the scope of the function.

Your Turn¶

The area of a triangle is \begin{equation*} A = \frac{h * b}{2} \end{equation*} where h is the height and b is the length of the base.

Write a function called area that takes arguments h and b and returns the area of a triangle with those dimensions.

More Complex Functions¶

Functions unlock a great deal of power in programming. It's often handy to write functions that handle data manipulation workflows that you do regularly.

Take this data:

In [13]:
df
Out[13]:
agency_id agency_name
0 001 Smith Real Estate, Inc.
1 002 Johnson Realty
2 NaN John Doe Real Estate, LLC

Maybe you commonly work with data like this and always:

  1. Filter out rows with missing data in the 'ID' column
  2. Convert the name column to all lowercase so it's consistent.

It's simple to write a function that will do that in a single line for you.

In [14]:
def clean(df):
    # Functions that transform DataFrames should always start by
    # making a copy.
    df = df.copy()
    # Drop rows where agency_id is null
    df = df[df['agency_id'].notnull()]
    # Make agency_name lowercase
    df['agency_name'] = df['agency_name'].str.lower()
    return df
In [15]:
clean(df)
Out[15]:
agency_id agency_name
0 001 smith real estate, inc.
1 002 johnson realty

We can then apply this function to other similarly-structured data.

In [17]:
df2
Out[17]:
agency_id agency_name
0 123 Berkshire Hathaway
1 NaN Howard Hannah
2 321 Southeby's
In [18]:
clean(df2)
Out[18]:
agency_id agency_name
0 123 berkshire hathaway
2 321 southeby's

There's no limit to how much complexity or code can be put in a function. In software development, it's not uncommon to find functions with hundreds of lines.

Moving lots of logic into functions can help programmers simplify their code -- rather than look at the function logic each time, they can get an idea of what's happening by just seeing the function name.

Named Arguments¶

How does Python know which argument is which when we pass multiple?

For example

In [19]:
def raise_to_power(a, b):
    return a ** b
In [20]:
raise_to_power(2, 3)
Out[20]:
8

It's clear that a was set to 2 and b to 3, because we got 8 (23) as our result.

Why didn't the opposite happen? How did Python know that we didn't mean that b should be 3 and a should be 2?

It's because Python respects the order of arguments; it assigns our arguments to variables in the order that they're passed in.

There's another, more explicit, way to tell Python which value goes with which argument: named arguments, also called keyword arguments.

In [21]:
raise_to_power(a=3, b=1)
Out[21]:
3
In [22]:
raise_to_power(b=1, a=3)
Out[22]:
3

In this format, the syntax argument_name=value specifies which value goes where; the order no longer is important.

If you mix positional and keyword arguments, all the positional ones must come first -- this allows Python to disambiguate how to match the inputs to arguments.

Default Values¶

A handy feature of Python is default argument values -- the ability to set a default for arguments the user may choose not to pass in.

Let's look at an example.

In [23]:
def favorite(number=5):
    return 'My favorite number is ' + str(number)

This function takes an input -- your favorite number -- and prints out a sentence indicating that it's your favorite.

In [24]:
favorite(10)
Out[24]:
'My favorite number is 10'
In [25]:
favorite(number=8)
Out[25]:
'My favorite number is 8'

However, this function also has a default number in case you don't specify one; that's what number=5 means, as one of the arguments.

If we call favorite without specifying an input, it assumes we want number to be 5.

In [26]:
favorite()
Out[26]:
'My favorite number is 5'

This functionality is extremely useful for functions that allow the user to customize certain options -- but don't want the user to have to specify them every time.

A good example is the read_csv function from pandas. We've seen it before, but we usually only specify a single argument: a filename.

pd.read_csv('mydata/data.csv')

However, if you consult the help documentation, you discover the read_csv allows for many optional customizations. We usually pass the first one (named filepath_or_buffer), but not the others, like sep, delimiter, or header.

In [27]:
import pandas as pd
pd.read_csv?
Signature:
pd.read_csv(
    filepath_or_buffer: 'FilePath | ReadCsvBuffer[bytes] | ReadCsvBuffer[str]',
    *,
    sep: 'str | None | lib.NoDefault' = <no_default>,
    delimiter: 'str | None | lib.NoDefault' = None,
    header: "int | Sequence[int] | None | Literal['infer']" = 'infer',
    names: 'Sequence[Hashable] | None | lib.NoDefault' = <no_default>,
    index_col: 'IndexLabel | Literal[False] | None' = None,
    usecols=None,
    dtype: 'DtypeArg | None' = None,
    engine: 'CSVEngine | None' = None,
    converters=None,
    true_values=None,
    false_values=None,
    skipinitialspace: 'bool' = False,
    skiprows=None,
    skipfooter: 'int' = 0,
    nrows: 'int | None' = None,
    na_values=None,
    keep_default_na: 'bool' = True,
    na_filter: 'bool' = True,
    verbose: 'bool' = False,
    skip_blank_lines: 'bool' = True,
    parse_dates: 'bool | Sequence[Hashable] | None' = None,
    infer_datetime_format: 'bool | lib.NoDefault' = <no_default>,
    keep_date_col: 'bool' = False,
    date_parser=<no_default>,
    date_format: 'str | None' = None,
    dayfirst: 'bool' = False,
    cache_dates: 'bool' = True,
    iterator: 'bool' = False,
    chunksize: 'int | None' = None,
    compression: 'CompressionOptions' = 'infer',
    thousands: 'str | None' = None,
    decimal: 'str' = '.',
    lineterminator: 'str | None' = None,
    quotechar: 'str' = '"',
    quoting: 'int' = 0,
    doublequote: 'bool' = True,
    escapechar: 'str | None' = None,
    comment: 'str | None' = None,
    encoding: 'str | None' = None,
    encoding_errors: 'str | None' = 'strict',
    dialect: 'str | csv.Dialect | None' = None,
    on_bad_lines: 'str' = 'error',
    delim_whitespace: 'bool' = False,
    low_memory=True,
    memory_map: 'bool' = False,
    float_precision: "Literal['high', 'legacy'] | None" = None,
    storage_options: 'StorageOptions' = None,
    dtype_backend: 'DtypeBackend | lib.NoDefault' = <no_default>,
) -> 'DataFrame | TextFileReader'
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.
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.

    .. versionadded:: 1.5.0

        Support for defaultdict was added. Specify a defaultdict as input where
        the default determines the dtype of the columns which are not explicitly
        listed.
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 in addition to case-insensitive variants of "True".
false_values : list, optional
    Values to consider as False in addition to case-insensitive variants of "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', 'None',
    '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``.

    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.

    .. deprecated:: 2.0.0
        A strict version of this argument is now the default, passing it has no effect.

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.

    .. deprecated:: 2.0.0
       Use ``date_format`` instead, or read in as ``object`` and then apply
       :func:`to_datetime` as-needed.
date_format : str or dict of column -> format, default ``None``
   If used in conjunction with ``parse_dates``, will parse dates according to this
   format. For anything more complex,
   please read in as ``object`` and then apply :func:`to_datetime` as-needed.

   .. versionadded:: 2.0.0
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.

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 'filepath_or_buffer' is
    path-like, then detect compression from the following extensions: '.gz',
    '.bz2', '.zip', '.xz', '.zst', '.tar', '.tar.gz', '.tar.xz' or '.tar.bz2'
    (otherwise no compression).
    If using 'zip' or 'tar', 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'``, ``'tar'``} and other
    key-value pairs are forwarded to
    ``zipfile.ZipFile``, ``gzip.GzipFile``,
    ``bz2.BZ2File``, ``zstandard.ZstdDecompressor`` or
    ``tarfile.TarFile``, 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}``.

    .. versionadded:: 1.5.0
        Added support for `.tar` files.

    .. 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, default "utf-8"
    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.
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.request.Request`` as header options. For other
    URLs (e.g. starting with "s3://", and "gcs://") the key-value pairs are
    forwarded to ``fsspec.open``. Please see ``fsspec`` and ``urllib`` for more
    details, and for more examples on storage options refer `here
    <https://pandas.pydata.org/docs/user_guide/io.html?
    highlight=storage_options#reading-writing-remote-files>`_.

    .. versionadded:: 1.2

dtype_backend : {"numpy_nullable", "pyarrow"}, defaults to NumPy backed DataFrames
    Which dtype_backend to use, e.g. whether a DataFrame should have NumPy
    arrays, nullable dtypes are used for all dtypes that have a nullable
    implementation when "numpy_nullable" is set, pyarrow is used for all
    dtypes if "pyarrow" is set.

    The dtype_backends are still experimential.

    .. versionadded:: 2.0

Returns
-------
DataFrame or TextFileReader
    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:      /opt/homebrew/anaconda3/envs/uc-python/lib/python3.11/site-packages/pandas/io/parsers/readers.py
Type:      function

Usually, you don't need to specify things like the text encoding, datetime format, or delimiter; pandas has intelligent defaults so you only need to worry about them if your data isn't loaded as you expected.

Docstrings¶

Just as it's best practice to document your code by using comments, it's good form to notate your functions so others (and you) can quickly learn about them -- what they do, what arguments they take, and what value they return.

In Python, this is typically done using a docstring, an optional but very helpful annotation of a function.

In [28]:
def double(x):
    '''Multiply x by 2 and return the result.'''
    doubled = x * 2
    return doubled

Of course, for a function as simple as the above, you could just figure it out from the code. But as functions grow more complex, this documentation becomes more and more useful.

Docstrings are what you've been seeing if you use the function? syntax. Python fetches that function's docstring and shows it to you.

In [29]:
double?
Signature: double(x)
Docstring: Multiply x by 2 and return the result.
File:      /var/folders/_s/v67g4_p57y75rpkw8gglwlpc0000gn/T/ipykernel_95879/3158182334.py
Type:      function

Your Turn¶

Look at the docstrings of two functions in Pandas. What arguments do they take?

You can see that docstrings in commonly-used packages are very descriptive, extensively documenting inputs, outputs, and functionality.

Here is a great guide to writing well structured and consistent docstrings.

Your Turn¶

  1. Take a look at the below function
def divide(dividend, divisor):
    quotient = dividend / divisor
    return quotient

What variables are the arguments? What variable is the return value?

  1. Write a function cat that takes 3 strings and returns those strings concatenated together with spaces between. E.g. cat('hello', 'friend', 'happy thursday') would return 'hello friend happy thursday'.

  2. Update the function from #2 to give a default value for the third argument. Make the default value a period ('.').

  3. Update the function from #3 to have a docstring. In one sentence, document what the function does.

  4. Update the function from #4 to give a default value for the first argument. Choose any default you like. Does Python allow this? Why?

Lambda Functions¶

Occasionally, you may encounter a Python function that is created without using the def keyword: lambda functions. Lambda functions are one-line functions that do something simple, and are defined using the lambda keyword.

A lambda function to add 5 to an input and return the result would look like

lambda x: x + 5

This means

"For any input x, return that x plus 5."

As you may have noticed, this function doesn't have a name -- we didn't use the define <function_name> syntax. Lambda functions are sometimes called anonymous functions because they don't have names.

Occasionally lambda functions can be handy, but there is no situation where lambda functions are necessary. For this reason, we recommend using named (non-lambda) functions until you've become very comfortable with functions in Python.

Questions¶

Are there any questions before moving on?