Alex Man
Alex Man

Reputation: 477

Using lambda or apply on multiple columns of a dataframe with lists contents

This may be a trivial question. I have the following dataframe that the columns contain lists.

import pandas as pd
df = pd.DataFrame({'time1': [['2000', '2300'], ['1000', '1100']], 'time2': [['2200', '2400'], ['800', '900']]})
print(df)

  time1         time2
0  [2000, 2300]  [2200, 2400]
1  [1000, 1100]    [800, 900]

The values in of the list represent time intervals. I am trying to convert all these elements into a time format.

I am trying to get something like this:

time1         time2
20:00-23:00  22:00-24:00
10:00-11:00  8:00-9:00

Upvotes: 0

Views: 1235

Answers (2)

Erfan
Erfan

Reputation: 42886

We can define our function here to unnest your list and seperate the strings with a : delimiter, then apply it to each column:

functime = lambda x: '-'.join([t[:-2] + ':' + t[-2:] for t in x])

for col in df.columns:
    df[col] = df[col].apply(functime)

print(df)
         time1        time2
0  20:00-23:00  22:00-24:00
1  10:00-11:00    8:00-9:00

Or

Define a regular function:

def functime2(x):
    val = '-'.join([t[:-2] + ':' + t[-2:] for t in x])

    return val

for col in df.columns:
    df[col] = df[col].apply(functime2)

         time1        time2
0  20:00-23:00  22:00-24:00
1  10:00-11:00    8:00-9:00

Upvotes: 1

Sheldore
Sheldore

Reputation: 39042

This is one indirect way to do it based on this unaccepted answer. The idea is to split the string into hours and minutes and then join them using a dash - and :

import pandas as pd
df = pd.DataFrame({'time1': [['2000', '2300'], ['1000', '1100']], 
                   'time2': [['2200', '2400'], ['800', '900']]})


def convert_to_minutes(value):
    tim = []
    for val in value:
        hours, minutes = val[0:-2], val[-2:]
        tim.append(hours + ':' + minutes)

    return '-'.join(tim)

df['time1'] = df['time1'].apply(convert_to_minutes)
df['time2'] = df['time2'].apply(convert_to_minutes)

Output

print (df)

         time1        time2
 0  20:00-23:00  22:00-24:00
 1  10:00-11:00    8:00-9:00

Upvotes: 0

Related Questions