Python / Pandas - combining the average and minimum number of groups

What is the syntax for combining meanand a minin a data frame? I want to group by 2 columns, calculate the average value inside the group for col3and save the value min col4. There will be something like

groupeddf = nongrouped.groupby(['col1', 'col2', 'col3'], as_index=False).mean().min('col4')

work? If not, what is the correct syntax? Thank!

EDIT

Good, so the question was not clear without an example. I will update it now. Also changes in the text above.

I have:

ungrouped
col1 col2 col3 col4
1    2    3    4
1    2    4    1
2    4    2    1
2    4    1    3
2    3    1    3

The required output is grouped in columns 1-2, the average for column 3 (and actually several more columns on the data, this is simplified) and a minimum of col4:

grouped
col1 col2 col3 col4
1    2    3.5  1
2    4    1.5  1
2    3    1    3
+4
source share
1 answer

, mean, min col4:

min_val = nongrouped.groupby(['col1', 'col2', 'col3'], as_index=False).mean()['col4'].min()

min Series:

min_val = nongrouped.groupby(['col1', 'col2', 'col3'])['col4'].mean().min()

:

nongrouped = pd.DataFrame({'col1':[1,1,3],
                   'col2':[1,1,6],
                   'col3':[1,1,9],
                   'col4':[1,3,5]})

print (nongrouped)
   col1  col2  col3  col4
0     1     1     1     1
1     1     1     1     3
2     3     6     9     5

print (nongrouped.groupby(['col1', 'col2', 'col3'])['col4'].mean())
1     1     1       2
3     6     9       5
Name: col4, dtype: int64

min_val = nongrouped.groupby(['col1', 'col2', 'col3'])['col4'].mean().min()
print (min_val)
2

EDIT:

aggregate:

groupeddf = nongrouped.groupby(['col1', 'col2'], sort=False)
                      .agg({'col3':'mean','col4':'min'})
                      .reset_index()
                      .reindex(columns=nongrouped.columns)
print (groupeddf)
   col1  col2  col3  col4
0     1     2   3.5     1
1     2     4   1.5     1
2     2     3   1.0     3
+3

Source: https://habr.com/ru/post/1672329/


All Articles