Skip to content
Advertisement

Tag: pandas-groupby

Pandas: add column with progressive count of elements meeting a condition

Given the following dataframe df: I want to add another column that counts, progressively, the elements with df[‘B’]=’yes’: How can I do this? Answer You can use numpy.where with cumsum of boolean mask: Another solution is count boolean mask created by filtering and then add 0 values by reindex: Performance (in real data should be different, best check it first):

How to loop over grouped Pandas dataframe?

DataFrame: Code: I’m trying to just loop over the aggregated data, but I get the error: ValueError: too many values to unpack @EdChum, here’s the expected output: The output is not the problem, I wish to loop over every group. Answer df.groupby(‘l_customer_id_i’).agg(lambda x: ‘,’.join(x)) does already return a dataframe, so you cannot loop over the groups anymore. In general: df.groupby(…)

Advertisement