Calculating percentage of days covered in a range with a groupby Pandas function
<p>I have a simple <code>Pandas</code> <code>dataframe</code> where each row represents a person and a date range. For each person, I'd like to know what percentage of days in a hard-coded range (defined by variables <code>period_start</code> and <code>period_end</code>) are covered across the various entries in the <code>dataframe</code>. </p>

<p>I assume there is an easy way to do this with <code>Pandas</code>, but I haven't been able to find one. I have a solution with multiple <code>dataframes</code> and several nested loops, but this is inefficient at scale. How can I do this more effectively utilizing <code>Pandas</code>? I think a <code>groupby</code> makes sense, but not sure how to do that when the ranges are across two columns and may overlap.</p>

<pre><code>import pandas as pd
from datetime import datetime
df = pd.DataFrame(data=[['2016-01-01', '2016-01-31', 'A'],
                        ['2016-02-02', '2016-02-10', 'A'],
                        ['2016-03-01', '2016-04-01', 'A'],
                        ['2016-01-01', '2016-03-01', 'B']],
                  columns=['startdate', 'enddate', 'person'])

# start and end date
period_start = datetime(year=2016, month=01, day=01)
period_end = datetime(year=2016, month=12, day=31)

# dates_dfculate totals days
total_days =  (period_end-period_start).days  + 1

# convert columns to dates
df['startdate']= pd.to_datetime(df['startdate'],  format='%Y-%m-%d')
df['enddate']= pd.to_datetime(df['enddate'],  format='%Y-%m-%d')

# create a TimeIndex dataframe with columns for each person
rng = pd.date_range(period_start, periods=total_days, freq='D')
people = list(set(df['person'].tolist()))
dates_df = pd.DataFrame(columns=[people], index=rng).fillna(False)

# loop over each date (index)
for index, row in dates_df.iterrows():

   # loop over each column (person) 
   for person in people:
       tmp = df[df['person'] == person]

       # loop over each each entry for the person
       for index1, row1 in tmp.iterrows():

           # check if the date is date index in dates_df is within range
           value = row1['startdate'] &lt;= index &lt;= row1['enddate']

           # if it's not already set to true, set it to true
           if dates_df.ix[index, person] == False and value == True:
               dates_df.ix[index, person] = True

# for each person, show the percentage of days in range that are covered
for person in people:
    print  person, sum(dates_df[person].tolist())/float(total_days)
</code></pre>

<p>Desired Output:</p>

<pre><code>A 0.196721311475
B 0.166666666667
</code></pre>