[PYTHON] Python Pandas DataFrame에서 timedelta64 [ns] 열을 초로 변환하십시오.
PYTHONPython Pandas DataFrame에서 timedelta64 [ns] 열을 초로 변환하십시오.
pandas DataFrame 열 기간에는 표시된대로 timedelta64 [ns]가 포함됩니다. 어떻게 초로 변환 할 수 있습니까?
0 00:20:32
1 00:23:10
2 00:24:55
3 00:13:17
4 00:18:52
Name: duration, dtype: timedelta64[ns]
나는 다음을 시도했다.
print df[:5]['duration'] / np.timedelta64(1, 's')
오류가 발생했습니다.
Traceback (most recent call last):
File "test.py", line 16, in <module>
print df[0:5]['duration'] / np.timedelta64(1, 's')
File "C:\Python27\lib\site-packages\pandas\core\series.py", line 130, in wrapper
"addition and subtraction, but the operator [%s] was passed" % name)
TypeError: can only operate on a timedeltas for addition and subtraction, but the operator [__div__] was passed
또한 시도했다.
print df[:5]['duration'].astype('timedelta64[s]')
오류가 발생했습니다.
Traceback (most recent call last):
File "test.py", line 17, in <module>
print df[:5]['duration'].astype('timedelta64[s]')
File "C:\Python27\lib\site-packages\pandas\core\series.py", line 934, in astype
values = com._astype_nansafe(self.values, dtype)
File "C:\Python27\lib\site-packages\pandas\core\common.py", line 1653, in _astype_nansafe
raise TypeError("cannot astype a timedelta from [%s] to [%s]" % (arr.dtype,dtype))
TypeError: cannot astype a timedelta from [timedelta64[ns]] to [timedelta64[s]]
해결법
-
==============================
1.Pandas (버전 0.14)의 현재 버전에서 제대로 작동합니다.
Pandas (버전 0.14)의 현재 버전에서 제대로 작동합니다.
In [132]: df[:5]['duration'] / np.timedelta64(1, 's') Out[132]: 0 1232 1 1390 2 1495 3 797 4 1132 Name: duration, dtype: float64
이전 버전의 Pandas / NumPy에 대한 해결 방법은 다음과 같습니다.
In [131]: df[:5]['duration'].values.view('<i8')/10**9 Out[131]: array([1232, 1390, 1495, 797, 1132], dtype=int64)
timedelta64 및 datetime64 데이터는 내부적으로 8 바이트 int (dtype '
datetime64 / timedelta64s를 사용하려면 NumPy 버전 1.7 이상이 필요합니다.
-
==============================
2.유형이 올바른지 확인하십시오.
유형이 올바른지 확인하십시오.
linear_df [ 'duration'] .dt.hour * 3600 + linear_df [ 'duration'] .dt.minute * 60 + linear_df [ 'duration'] .dt.second
linear_df의 [5]. [ '시간'] astype (timedelta64 [P])
나는 이것을 다음과 같이 작동시킨다 :
start_dt 및 end_dt 열의 형식은 다음과 같습니다.
import datetime linear_df[:5]['start_dt'] 0 1970-02-22 21:32:48.000 1 2016-12-30 17:47:33.216 2 2016-12-31 09:33:27.931 3 2016-12-31 09:52:53.486 4 2016-12-31 10:29:44.611 Name: start_dt, dtype: datetime64[ns]
timedelta64 [ns] 형식으로 내 지속 시간을 가졌습니다.이 형식은 시작 및 종료 날짜 시간 값을 뺍니다.
linear_df['duration'] = linear_df['end_dt'] - linear_df['start_dt']
결과 기간 열은 다음과 같습니다.
linear_df[:5]['duration'] 0 0 days 00:00:14 1 2 days 17:44:50.558000 2 0 days 15:37:28.418000 3 0 days 18:45:45.727000 4 0 days 19:21:27.159000 Name: duration, dtype: timedelta64[ns]
팬더를 사용하여 플로트에서 두 날짜 사이에 내 지속 시간 초를 가졌습니다. 이후에 기간을 쉽게 비교하거나 필터링 할 수 있습니다.
linear_df[:5]['duration'].astype('timedelta64[s]') 0 14.0 1 236690.0 2 56248.0 3 67545.0 4 69687.0 Name: duration, dtype: float64
내 경우에는 1 초 이상 지속되는 모든 시간을 얻고 싶습니다.
희망이 도움이됩니다.
-
==============================
3.Series dt 접근자를 사용하여 datetime (timedelta) 계열의 메서드 및 특성에 액세스합니다.
Series dt 접근자를 사용하여 datetime (timedelta) 계열의 메서드 및 특성에 액세스합니다.
>>> s 0 -1 days +23:45:14.304000 1 -1 days +23:46:57.132000 2 -1 days +23:49:25.913000 3 -1 days +23:59:48.913000 4 00:00:00.820000 dtype: timedelta64[ns] >>> >>> s.dt.total_seconds() 0 -885.696 1 -782.868 2 -634.087 3 -11.087 4 0.820 dtype: float64
Datetimelike 속성
-
==============================
4.우리는 간단하게 pandas apply () 함수를 사용할 수 있습니다.
우리는 간단하게 pandas apply () 함수를 사용할 수 있습니다.
def get_seconds(time_delta): return time_delta.seconds def get_microseconds(time_delta): return time_delta.micro_seconds time_delta_series = df['duration'] converted_series = time_delta_series.apply(get_seconds) print(converted_series)
from https://stackoverflow.com/questions/26456825/convert-timedelta64ns-column-to-seconds-in-python-pandas-dataframe by cc-by-sa and MIT license
'PYTHON' 카테고리의 다른 글
[PYTHON] 인덱스없이 json으로 팬더 데이터 프레임 (0) | 2018.10.27 |
---|---|
[PYTHON] 선택한 행과 열의 팬더 분 () (0) | 2018.10.27 |
[PYTHON] Java : 자리 표시 자로 문자열 서식 지정 (0) | 2018.10.26 |
[PYTHON] 파이썬에서 "If if from ipython"테스트를 어떻게 할 수 있습니까? (0) | 2018.10.26 |
[PYTHON] 수입이있는 전역 변수 (0) | 2018.10.26 |