Reputation: 552
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
min=0
and max=5
, get the aggregated value, so the names value will be ['a','b','d','e','a']
min=5
and max=10
, get the aggregated value, the names value will be ['a','d']
Any help is appreciated.
Upvotes: 2
Views: 337
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