Pandas python: Create function to merge two dataframes based on defined list of columns
<p>In the script that I am writing, I want to frequently repeat the same piece of code, where I create a "numerator" dataframe with one group by, and then a "denominator" dataframe with a different group by. I then merge the two together so that I have the numerator and denominator in one place. I am trying to create a function where all I have to pass to it is the list of fields I want included in the numerator and denominator.</p>

<p>Here is the function:</p>

<pre><code>  def calcfractions(self, df, numlist, denomlist):
    print("test 1")
    numlist.append(denomlist)
    selectlist = numlist
    selectlist.append("TeamID")
    selectlist.append("PlayerID")

    print("test 2")
    numdf = df[selectlist].groupby(numlist).agg({"PlayerID": "count"})
    denomdf = df[selectlist].groupby(denomlist).agg({"PlayerID": "count"})

    print("test 3")
    mergeddf = pd.merge(numdf, denomdf, on=denomlist)

    print("test 4")
    return mergeddf
</code></pre>

<p>Here is the script I'm trying to use it in:</p>

<pre><code> def team_pr(self, df1):
    numlist = ['PlayerLevel']
    denomlist = ['TeamName', 'Year']

    mergeddf = self.calcfractions(df1, numlist, denomlist)
    print(mergeddf.head(2))
</code></pre>

<p>However, when I run this, I only get to printing "test 2" in def calcfractions, something fails after that point. I think it might have to do with trying to append denomlist to numlist. Any thoughts?</p>

<p>EDIT: The script doesn't "fail", there is no error. It just ends.</p>

<p>You are not capturing the return value from <code>calcfractions</code>. in <code>team_pr</code>, change to <code>merged_df = self.calcfractions(df1, numlist, denomlist)</code> then <code>print(merged_df.head(2))</code> to see what you get.</p>

<p>This is assuming these are methods of a class. If they are just functions, just do away with the whole <code>self</code> bit, it's syntax used for classes only, to pass in the instance as the first argument.</p>

python pandas