简体   繁体   中英

Getting the difference between Date and Hours for a Data frame for multiple values

I have a DataFrame in which I have multiple names and multiple timestamps associated with them. This is the data of players who have played a game in a month.

在此处输入图像描述

Like shown above. These _ids have duplicates in them as the data is from this month's dates.

I need to know how many hours does a person play per day ?

I have tried to make a sample DataFrame for you guys to make it easier.

> import pandas as pd
> 
> data  = {'ids':['Kelsier', 'Kelsier', 'Saze',
> 'Val','Kelsier','Val','Val','Val','Saze','Saze','Saze','Val']
>         'ts' : ["2022-12-21 18:29:59.141", "2022-12-21 19:02:59.141", '2022-12-21 10:12:23.545', '2022-12-19 11:15:20.612',  "2022-12-22
> 01:29:59.141",  "2022-12-22 05:26:48.151",  "2022-12-22 05:28:09.543"\
>                ,  "2022-12-22 05:30:14.522",  "2022-12-23 15:14:19.231",  "2022-12-24 10:14:39.601",  "2022-12-24 11:44:34.173",
> "2022-12-24 13:12:23.566"]}
>          df = pd.DataFrame(data)
> 
> df['ts'] = pd.to_datetime(df['ts'])

What and How should I do to get the data I desire from the given DataFrame?

I want an output like this:

在此处输入图像描述

Is this possible? If so then how???

This could be a solution. I'm not sure how you want to calculate the days and hours played exactly. However, if you want to get the time between the last and first timestamp you could use the following:

# Calculate timedeltas max - min
time_deltas = df.groupby('ids')['ts'].agg(lambda x: x.max() - x.min()).reset_index()

# Create day and hour column with timedelta column
time_deltas['DaysPlayed'] = time_deltas['ts'].apply(lambda x: x.days)
time_deltas['HoursPlayed'] = time_deltas['ts'].apply(lambda x: round(x.seconds/3600, 0))
time_deltas

    ids     ts                     DaysPlayed   HoursPlayed
0   Kelsier 0 days 07:00:00         0              7.0
1   Saze    3 days 01:32:10.628000  3              2.0
2   Val     5 days 01:57:02.954000  5              2.0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM