Home > Enterprise >  keep only last item separated by comma in pandas data frame
keep only last item separated by comma in pandas data frame

Time:02-23

I've a pandas data frame like the below table. in "Hours" column I need to keep only the last item for each record like what we've in the "Last" column. how can I do it?

Name Team Hours Last
Alex SC 00:10,01:30,02:45 02:45
Fred FR 04:30,05:10 05:10
Joe CE 04:10,05:40,06:10,04:40 04:40
Lee FR 00:30 00:30

I used many functions like split(',').explode() to separate them by "," but have no idea how can I keep only the last one.

CodePudding user response:

Use Series.str.split and then get last splitted value by indexing:

df['Last'] = df['Hours'].str.split(',').str[-1]
print (df)
   Name Team                    Hours   Last
0  Alex   SC        00:10,01:30,02:45  02:45
1  Fred   FR              04:30,05:10  05:10
2   Joe   CE  04:10,05:40,06:10,04:40  04:40
3   Lee   FR                    00:30  00:30
  • Related