Custom bin and sum in pandas?

Viewed 330

I have a dataframe that looks like:

Len | Count
-----------
100 | 5
105 | 10
3   | 2
1000| 21
...

I'd like to bin with Len but use a custom bin, something like bins = [100, 200, 300, ...] to mark the endpoints. However, after binning, I'd like to sum the Count values for all the rows that fall into each bin. Is there a clean way to do this in Pandas?

2 Answers

You can try:

df['Count'].groupby(pd.cut(df['Len'], bins=bins) ).sum()

You can create a column with the bins and then apply groupby to get the count:

bins = [100, 200,300, 400,500, 600,..]
labels = ['{}-{}'.format(i, j) for i, j in zip(bins[:-1], bins[1:])] 

df['bin_column'] = pd.cut(df['existing_column'], bins=bins, labels=labels)

grouped_df = df.groupby('bin_column').sum()
Related