How do I know when to use parenthesis when chaining datetime functions in python?

I am learning Python and was hoping someone here can help clear something up for me.

I have the following code:

import pandas as pd

ser = pd.Series(['01-01-2010', '02-02-2011', '03-03-2012', '04-04-2013'])
ser_ts = pd.to_datetime(ser)

ser_ts_daynum = ser_ts.dt.weekday.tolist()
ser_ts_dayname = ser_ts.dt.day_name().tolist()

print(ser_ts_daynum)
print(ser_ts_dayname)

Why do I need parenthesis in day_name() when defining ser_ts_dayname, but not for weekday within ser_ts_daynum? I get an error if I try the opposite.

I feel like I'm missing something about how to chain functions in Python. I'm very familiar with piping in R (%>%) but things don't seem to work the same way in Python. Greatly appreciate any insight!

1 answer

  • answered 2021-09-11 18:46 mozway

    There is no direct way of knowing. Here are a few pointers to try to determine what to do:

    1. Check the documentation

    pandas.Series.dt.day_name gives a use case, with parentheses, while pandas.Series.dt.weekday is without parentheses.

    2. Check the type

    Methods needs parentheses to be executed

    >>> type(ser_ts.dt.day_name)
    method
    

    This is more tricky to identify properties (which do not need parentheses) as the type of the linked object will be returned:

    >>> type(ser_ts.dt.weekday)
    pandas.core.series.Series
    

    3. Check the signature/docstring (interactive interpreter)

    When using ipython/jupyter or any interactive interpreter, you can add a ? at the end of the name (without parentheses)

    If a property, this is a reference to a inner object, you do not need parentheses.

    >>> ser_ts.dt.weekday?
    Type:        property
    String form: <property object at 0x7fd0234d3770>
    Docstring:  
    The day of the week with Monday=0, Sunday=6.
    ...
    

    else, you have a signature, this is a method, you need parentheses.

    >>> ser_ts.dt.day_name?
    Signature: ser_ts.dt.day_name(*args, **kwargs)
    Docstring:
    Return the day names of the DateTimeIndex with specified locale.
    ...
    

    4. Give parentheses a try ;)

    >>> ser_ts.dt.weekday()
    TypeError: 'Series' object is not callable
    

    OK, looks like you did not need it

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum