Mazz
Mazz

Reputation: 820

Max value of a Series in a single Dataframe cell

I have a Dataframe where each row contains a Series in a single column.

             col1    
row1     [34,55,11,8]
row2     [36,76,69,6]
row3     [77,31,40,55]
row4     [51,41,26,30]

I want to get the max of each value in the series and produce that in a new column.

        col1                   max 
row1     [34,55,11,8]          55
row2     [36,76,69,6]          76
row3     [77,31,40,55]         77
row4     [51,41,26,30]         51

My attempt:

df['max'] = df['values'].apply(lambda x:x.max())
df.head()

Error

ValueError: zero-size array to reduction operation maximum which has no identity

Upvotes: 1

Views: 560

Answers (3)

Wojciech Moszczyński
Wojciech Moszczyński

Reputation: 3187

I have easy method for this:

import pandas as pd
df = pd.DataFrame({'A':[34,36,77,51],'B':[55,76,31,41],'C':[11,69,40,26],'D':[8,6,55,30]})
df

enter image description here

df['MMax'] = df.max(axis=1)
df.MMax

enter image description here

Upvotes: 0

Loochie
Loochie

Reputation: 2472

A small mistake in your code. The same could be achieved by the following:

df['max']= df['values'].apply(lambda x: max(x))

Upvotes: 0

BENY
BENY

Reputation: 323236

Using dataframe constructor re-create your list type columns

df['Max']=pd.DataFrame(df['values'].tolist(),index=df.index).max(1)

Upvotes: 3

Related Questions