Suggest a better counting process using Python | Pandas?
Question: I'm using Python and Pandas to pull metrics (inbound calls, abandoned calls,
etc.) from our call switch (csv format). The code works well but how I'm
calculating the metrics feels kludige and I'm hoping someone can suggest a
better way.

Data looks like:

    
    
    Date/Time   VPSNumber   Duration    CallerID    ConnectingNum   Extension   Direction   Type
    
    2016-05-31 12:52:35 1-555-555-5555  1:00    1-555-555-0000  0   3 - Support » In    Inbound leg of forwarded call
    2016-05-31 12:53:19 1-555-555-5555  0:18    Unknown 1-555-555-5555  3 - Support « Out   Forwarded call connected
    2016-05-31 11:13:13 1-555-555-5555  1:18    1-555-555-1234  0   3 - Support » In    Inbound leg of forwarded call
    

Code looks like:

    
    
    import pandas as pd
    
    allData = r'phoneSwitch.csv'
    
    phone_df = pd.read_csv((allData),parse_dates=['Date/Time'],index_col='Date/Time')
    phone_df.columns = ["VPSNumber","Duration","CallerID","ConnectingNum","Extension","Direction","Type"]
    phone_df.fillna(0,inplace=True)
    
    # USE 2016, WHOLE MONTH DATA ONLY
    phone_2016_df = (phone_df.loc['2016-01-01':'2016-05-31'])
    
    allInboundCalls = phone_2016_df[(phone_2016_df.Extension == "3") & (phone_2016_df.Direction == "» In") | \
                                       (phone_2016_df.Extension == "717") & (phone_2016_df.Direction == "» In") | \
                                       (phone_2016_df.Extension == "726") & (phone_2016_df.Direction == "» In")].count()["Extension"]
    

Again, rolling up the data works fine this way - it's more or less a big
countifs statement - but it feels a little bush league and I was hoping there
are any suggestions for improvment and or making the code simpler.

Thanks!


Answer: First filter for inbound calls using a boolean mask `df[df.Direction == "»
In"]`. You can then is `loc` with `isin(...)` to located all those inbound
calls with an extension in your desired group (e.g. 3, 717 and 726).

    
    
    df = (phone_df.loc['2016-01-01':'2016-05-31'])
    allInboundCalls = \
        df[df.Direction == "» In"].loc[df.Extension.isin(["3", "717", "726"])].count()["Extension"]
    

