[python] 시간과 분 단위로 두 열 간의 Pandas DataFrame 시간 차이 계산

나는 두 개의 열을 가지고, fromdate그리고 todatedataframe에.

import pandas as pd

data = {'todate': [pd.Timestamp('2014-01-24 13:03:12.050000'), pd.Timestamp('2014-01-27 11:57:18.240000'), pd.Timestamp('2014-01-23 10:07:47.660000')],
        'fromdate': [pd.Timestamp('2014-01-26 23:41:21.870000'), pd.Timestamp('2014-01-27 15:38:22.540000'), pd.Timestamp('2014-01-23 18:50:41.420000')]}

df = pd.DataFrame(data)

다음을 diff사용하여 두 날짜의 차이를 찾기 위해 새 열을 추가합니다.

df['diff'] = df['fromdate'] - df['todate']

내가 얻을 diff열을, 그러나 그것은 포함 days24 시간 이상이있을 때.

                   todate                fromdate                   diff
0 2014-01-24 13:03:12.050 2014-01-26 23:41:21.870 2 days 10:38:09.820000
1 2014-01-27 11:57:18.240 2014-01-27 15:38:22.540 0 days 03:41:04.300000
2 2014-01-23 10:07:47.660 2014-01-23 18:50:41.420 0 days 08:42:53.760000

결과를 시간과 분으로 만 변환하려면 어떻게합니까 (예 : 일이 시간으로 변환 됨)?



답변

Pandas 타임 스탬프 차이는 datetime.timedelta 객체를 반환합니다. * as_type * 메소드를 사용하여 쉽게 시간으로 변환 할 수 있습니다.

import pandas
df = pandas.DataFrame(columns=['to','fr','ans'])
df.to = [pandas.Timestamp('2014-01-24 13:03:12.050000'), pandas.Timestamp('2014-01-27 11:57:18.240000'), pandas.Timestamp('2014-01-23 10:07:47.660000')]
df.fr = [pandas.Timestamp('2014-01-26 23:41:21.870000'), pandas.Timestamp('2014-01-27 15:38:22.540000'), pandas.Timestamp('2014-01-23 18:50:41.420000')]
(df.fr-df.to).astype('timedelta64[h]')

수득,

0    58
1     3
2     8
dtype: float64


답변

.astype()위 의 솔루션이 나를 위해 작동하지 않았기 때문에 이것은 나를 괴롭 히고있었습니다 . 하지만 다른 방법을 찾았습니다. 시간을 설정하지 않았거나 다른 사람들을 위해 일할 수 있습니다.

t1 = pd.to_datetime('1/1/2015 01:00')
t2 = pd.to_datetime('1/1/2015 03:30')

print pd.Timedelta(t2 - t1).seconds / 3600.0

… 시간을 원한다면. 또는:

print pd.Timedelta(t2 - t1).seconds / 60.0

… 분을 원한다면.


답변

  • 결과를 시간과 분으로 만 변환하려면 어떻게합니까
    • 수락 된 답변은 반환 days + hours됩니다. 분은 포함되지 않습니다.
  • 시간과 분이있는 열을 hh:mm또는 x hours y minutes로 제공하려면 추가 계산 및 문자열 형식화가 필요합니다.
  • 이 답변은 timedelta수학을 사용하여 총 시간 또는 총 분을 부동 소수점으로 얻는 방법을 보여 주며 사용하는 것보다 빠릅니다..astype('timedelta64[h]')
  • Pandas Time Deltas 사용자 가이드
  • Pandas 시계열 / 날짜 기능 사용자 가이드
  • python timedelta객체 : 지원되는 작업을 참조하세요.
import pandas as pd

# test data from OP, with values already in a datetime format
data = {'to_date': [pd.Timestamp('2014-01-24 13:03:12.050000'), pd.Timestamp('2014-01-27 11:57:18.240000'), pd.Timestamp('2014-01-23 10:07:47.660000')],
        'from_date': [pd.Timestamp('2014-01-26 23:41:21.870000'), pd.Timestamp('2014-01-27 15:38:22.540000'), pd.Timestamp('2014-01-23 18:50:41.420000')]}

# test dataframe; the columns must be in a datetime format; use pandas.to_datetime if needed
df = pd.DataFrame(data)

# add a timedelta column if wanted. It's added here for information only
# df['time_delta_with_sub'] = df.from_date.sub(df.to_date)  # also works
df['time_delta'] = (df.from_date - df.to_date)

# create a column with timedelta as total hours, as a float type
df['tot_hour_diff'] = (df.from_date - df.to_date) / pd.Timedelta(hours=1)

# create a colume with timedelta as total minutes, as a float type
df['tot_mins_diff'] = (df.from_date - df.to_date) / pd.Timedelta(minutes=1)

# display(df)
                  to_date               from_date             time_delta  tot_hour_diff  tot_mins_diff
0 2014-01-24 13:03:12.050 2014-01-26 23:41:21.870 2 days 10:38:09.820000      58.636061    3518.163667
1 2014-01-27 11:57:18.240 2014-01-27 15:38:22.540 0 days 03:41:04.300000       3.684528     221.071667
2 2014-01-23 10:07:47.660 2014-01-23 18:50:41.420 0 days 08:42:53.760000       8.714933     522.896000

기타 방법

  • 기타 리소스의 팟 캐스트에있는 메모 항목이 .total_seconds()핵심 개발자가 휴가 중일 때 추가 및 병합되었으며 승인되지 않았을 것입니다.
    • 이것이 다른 .total_xx방법 이없는 이유이기도 합니다.
# convert the entire timedelta to seconds
# this is the same as td / timedelta(seconds=1)
(df.from_date - df.to_date).dt.total_seconds()
[out]:
0    211089.82
1     13264.30
2     31373.76
dtype: float64

# get the number of days
(df.from_date - df.to_date).dt.days
[out]:
0    2
1    0
2    0
dtype: int64

# get the seconds for hours + minutes + seconds, but not days
# note the difference from total_seconds
(df.from_date - df.to_date).dt.seconds
[out]:
0    38289
1    13264
2    31373
dtype: int64

기타 리소스

%%timeit 테스트

import pandas as pd

# dataframe with 2M rows
data = {'to_date': [pd.Timestamp('2014-01-24 13:03:12.050000'), pd.Timestamp('2014-01-27 11:57:18.240000')], 'from_date': [pd.Timestamp('2014-01-26 23:41:21.870000'), pd.Timestamp('2014-01-27 15:38:22.540000')]}
df = pd.DataFrame(data)
df = pd.concat([df] * 1000000).reset_index(drop=True)

%%timeit
(df.from_date - df.to_date) / pd.Timedelta(hours=1)
[out]:
43.1 ms ± 1.05 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

%%timeit
(df.from_date - df.to_date).astype('timedelta64[h]')
[out]:
59.8 ms ± 1.29 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)


답변