Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
133 views
in Technique[技术] by (71.8m points)

python - Convert string to timestamp and split the data

I have a dataset like this:

data = pd.DataFrame({'time':['13:30', '9:20', '18:12', '19:00', '8:20']})

I split the time to get the hour part only and add it to the table.

data['hour'] = data.Time.apply(lambda x: int(x.split(':')[0]))

Now I want to split the time into 3 parts of the day and 3 meal times, assume the hour interval (6,11] is for breakfast, (11,15] for lunch, and (15,20] for dinner.

I tried this code but seems to not working.

def time_period(hour):
    if hour >= 6 and hour < 11:
        return 'breakfast'
    elif hour >= 11 and hour < 15:
        return 'lunch'
    else:
        return 'dinner'
time = [time_period(y) for y in hours]
date['meal'] = time
question from:https://stackoverflow.com/questions/65907592/convert-string-to-timestamp-and-split-the-data

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

use pandas.apply()

data = pd.DataFrame({'time':['13:30', '9:20', '18:12', '19:00', '8:20']})
data['hour'] = data['time'].apply(lambda x: int(x.split(':')[0]))

def time_period(hour):
    if hour >= 6 and hour < 11:
        return 'breakfast'
    elif hour >= 11 and hour < 15:
        return 'lunch'
    else:
        return 'dinner'

data['meal'] = data['hour'].apply(lambda x: time_period(x))

output

time    hour    meal
13:30   13  lunch
9:20    9   breakfast
18:12   18  dinner
19:00   19  dinner
8:20    8   breakfast

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...