How to get maximum and minimum of a list in column?
You can create DataFrame
, then minimal and maximal values by DataFrame.agg
, convert to lists and assign back if requirement is no loops (Apply
are loops under the hood):
df = pd.DataFrame(dt.A.tolist())
dt['B'] = df.agg(['min','max'], axis=1).astype(int).values.tolist()
print (dt)
A B
0 [1, 2, 3, 4] [1, 4]
1 [3] [3, 3]
2 [2, 8, 4] [2, 8]
3 [5, 8] [5, 8]
If no problem with loops another solution with list comprehension
, it should be faster like apply
, depends of real data:
dt['B'] = [[min(x), max(x)] for x in dt.A]
Just an alternative with explode
:
dt['B'] = (dt['A'].explode().astype(int).groupby(level=0).agg(['min','max'])
.to_numpy().tolist())
print(dt)
A B
0 [1, 2, 3, 4] [1, 4]
1 [3] [3, 3]
2 [2, 8, 4] [2, 8]
3 [5, 8] [5, 8]
Like this:
In [1592]: dt['B'] = dt.A.apply(lambda x: [min(x), max(x)])
In [1593]: dt
Out[1593]:
A B
0 [1, 2, 3, 4] [1, 4]
1 [3] [3, 3]
2 [2, 8, 4] [2, 8]
3 [5, 8] [5, 8]
As suggested by @Ch3steR, using map
since it's faster:
dt['B'] = dt.A.map(lambda x: [min(x), max(x)])