Sid
Sid

Reputation: 552

Aggregate contents of a column based on the range of values in another column in Pandas

I am working on aggregating the contents of a dataframe based on the range of values in a given column. My df looks like given below:

min max names
1   5   ['a','b']
0   5   ['d']
6   8   ['a','c']
3   4   ['e','a']

The output expected is

Any help is appreciated.

Upvotes: 2

Views: 337

Answers (1)

filiphl
filiphl

Reputation: 991

The most intuitive approach would be to filter and then aggregate. To solve your specific problem, I would do this:

>> df = pd.DataFrame({"min": [1, 0, 6, 3],
   "max": [5, 5, 8, 4],
   "value": [['a','b'], ['d'], ['a','c'], ['e','a']]})

>> print(df)
   min  max   value
0    1    5  [a, b]
1    0    5     [d]
2    6    8  [a, c]
3    3    4  [e, a]

>> sum_filtered_values = df[(df["max"]<=5) & (df["min"]>=0)].value.sum()
>> print(sum_filtered_values)
['a', 'b', 'd', 'e', 'a']

>> sum_filtered_values = df[(df["max"]<=10) & (df["min"]>=5)].value.sum()
>> print(sum_filtered_values)
['a', 'c']

Upvotes: 4

Related Questions