Skip to content
Advertisement

How to group similar numbers with ranges/conditions and merge IDs using dataframes?

Please, I have a dataframe that is listed in ascending order. My goal is to average similar numbers (numbers that are within 10% of each other in ‘both directions’) and concate their ‘Bell’ name together. For example, the image shows the input and output dataframe. I tried coding it but I stuck on how to progress.

dataframe

JavaScript

Advertisement

Answer

Assuming you really want to check in both directions that the consecutive values are within 10%, you need to compute two Series with pct_change. Then use it to groupby.agg:

JavaScript

NB. If you want to group non-consecutive values, you first need to sort them: sort_values(by='Size')

Output:

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement