Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pandas ValueError: transforms cannot produce aggregated results

I have the following df,

type      id      date         code
exact    9720    2017-10-01    515
exact    9720    2017-10-01    515
fuzzy    8242    2017-11-01    122
fuzzy    8242    2017-11-01    122

I was trying

exact_rows = df['type'] != 'fuzzy'
grouped = df.loc[~exact_rows].groupby('id').apply(
            lambda g: g.sort_values('date', ascending=True))

a = np.where(grouped['code'].transform('nunique') == 1, 20, 0)

but I got an error,

ValueError: transforms cannot produce aggregated results

I am wondering how to resolve the issue.

like image 627
daiyue Avatar asked Aug 09 '18 13:08

daiyue


People also ask

What is the difference in output when using AGG () vs transform ()?

Transform 🐣 Compared with Aggregation, transform takes an additional step called “Broadcasting”. It broadcasts the results from sub dataframes to the original full dataframe. You could view it as left merge the results to original full dataframe.

What the difference between pandas apply and transform?

transform() can take a function, a string function, a list of functions, and a dict. However, apply() is only allowed a function. apply() works with multiple Series at a time. But, transform() is only allowed to work with a single Series at a time.

How do you transform in pandas?

Pandas Series: transform() functionThe transform() function is used to call function on self producing a Series with transformed values and that has the same axis length as self. Function to use for transforming the data. If a function, must either work when passed a Series or when passed to Series. apply.

What is the use of group by function in pandas?

What is the GroupBy function? Pandas' GroupBy is a powerful and versatile function in Python. It allows you to split your data into separate groups to perform computations for better analysis.


1 Answers

IIUC, you have to use transform in a groupby object, so just regroup with the existing whatever index

grouped.groupby(grouped.index)['code'].transform('nunique')
like image 150
rafaelc Avatar answered Sep 23 '22 14:09

rafaelc