0

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
3
  • You want the output in string type? Or pandas timedelta? Commented Jun 3, 2019 at 19:34
  • Doesnt matter. String is fine. Commented Jun 3, 2019 at 19:34
  • I would use applymap to apply a function to each individual value (in this case a list) stored in your dataframe. Commented Jun 3, 2019 at 19:36

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.