Named lambda function in python to be used in pandas' agg function

Viewed 236

The code below

df = pd.DataFrame({
    'A': ['a', 'b', 'a', 'b', 'b'],
    'B': [1, 2, 3, 4, 8],
    'C': [10, 20, 30, 40, 80]})

df[['B', 'C']].agg([min, lambda x: x.quantile(0.3), max])

returns:

|          | B      C       |
| -------- | -------------- |
| min      | 1.0    10.0    |
| <lambda> | 2.2    22.0    |
| max      | 8.0    80.0    |

Question:*

Is there any way that I can name the lambda function so that the name <lambda> is replaced by sth meaningful?

somehting similar to the code written below (this is pseudo-code and is not working):

df[['B', 'C']].agg([min, def pct30(x): return x.quantile(0.3), max])

instead of:

def pct30(x):
    return x.quantile(0.3)

df[['B', 'C']].agg([min, pct30, max])

to return:

|          | B      C       |
| -------- | -------------- |
| min      | 1.0    10.0    |
| pct30    | 2.2    22.0    |
| max      | 8.0    80.0    |
0 Answers
Related