Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas: Find the max value in one column containing lists

I have a dataframe like this:

fly_frame:
          day    plcae
0  [1,2,3,4,5]       A
1    [1,2,3,4]       B
2        [1,2]       C
3     [1,2,3,4]      D

If I want to find the max value in each entry in the day column.

For example:

fly_frame:
          day    plcae
0           5       A
1           4       B
2           2       C
3           4       D

What should I do?
Thanks for your help.

like image 999
Sun Hao Lun Avatar asked Dec 08 '18 08:12

Sun Hao Lun


2 Answers

df.day.apply(max)
#0    5
#1    4
#2    2
#3    4
like image 65
DYZ Avatar answered Oct 21 '22 08:10

DYZ


Use apply with max:

#if strings

#import ast

#print (type(df.loc[0, 'day']))
#<class 'str'>

#df['day'] = df['day'].apply(ast.literal_eval)

print (type(df.loc[0, 'day']))
<class 'list'>

df['day'] = df['day'].apply(max)

Or list comprehension:

df['day'] = [max(x) for x in df['day']]

print (df)
   day plcae
0    5     A
1    4     B
2    2     C
3    4     D
like image 29
jezrael Avatar answered Oct 21 '22 08:10

jezrael