How to apply Max function between rows on 2D list in pandas grouped dataframe

Viewed 104

I have a dataframe similar to the following where "data" is a 2D array:

id grouping_val data
1  a            [[0, 1], [1, 0]]
2  a            [[1, 0], [0, 1]]
3  b            [[2, 0], [3, 0]]
4  b            [[0, 4], [4, 5]]

How can I group them by "grouping_val" and taking the max value at each index in the "data" column across all the rows. Resulting in the following dataframe:

id grouping_val data
1  a            [[1, 1], [1, 1]]
2  b            [[2, 4], [4, 5]]
2 Answers

You can np.stack() the grouped arrays and take their max() along axis=0:

df = (df.groupby('grouping_val').data
        .apply(lambda x: np.stack(x).max(axis=0))
        .reset_index())

#   grouping_val              data
# 0            a  [[1, 1], [1, 1]]
# 1            b  [[2, 4], [4, 5]]
df = (
    df.groupby("grouping_val")["data"]
    .apply(lambda x: [[*map(max, zip(*subl))] for subl in zip(*x)])
    .reset_index()
)
print(df)

Prints:

  grouping_val               data
0            a   [[1, 1], [1, 1]]
1            b   [[2, 4], [4, 5]]
Related