Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to apply "first" and "last" functions to columns while using group by in pandas?
    text
    copied!<p>I have a data frame and I would like to group it by a particular column (or, in other words, by values from a particular column). I can do it in the following way: <code>grouped = df.groupby(['ColumnName'])</code>.</p> <p>I imagine the result of this operation as a table in which some cells can contain sets of values instead of single values. To get a usual table (i.e. a table in which every cell contains only one a single value) I need to indicate what function I want to use to transform the sets of values in the cells into single values.</p> <p>For example I can replace sets of values by their sum, or by their minimal or maximal value. I can do it in the following way: <code>grouped.sum()</code> or <code>grouped.min()</code> and so on.</p> <p>Now I want to use different functions for different columns. I figured out that I can do it in the following way: <code>grouped.agg({'ColumnName1':sum, 'ColumnName2':min})</code>.</p> <p>However, because of some reasons I cannot use <code>first</code>. In more details, <code>grouped.first()</code> works, but <code>grouped.agg({'ColumnName1':first, 'ColumnName2':first})</code> does not work. As a result I get a NameError: <code>NameError: name 'first' is not defined</code>. So, my question is: Why does it happen and how to resolve this problem.</p> <p><strong>ADDED</strong></p> <p><a href="http://pandas.pydata.org/pandas-docs/dev/groupby.html" rel="noreferrer">Here</a> I found the following example:</p> <pre><code>grouped['D'].agg({'result1' : np.sum, 'result2' : np.mean}) </code></pre> <p>May be I also need to use <code>np</code>? But in my case python does not recognize "np". Should I import it? </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload