2017-11-12 1 views
2

저는 현재 Google 뉴스 헤드 라인을 긁어서 만든 데이터 프레임을 가지고 있습니다. 내 칼럼 중 하나는 기사 발행 시간을 나타내는 "시간"입니다.팬더 데이터 프레임의 실제 날짜로 상대 시간 변경

불행하게도, 최근 기사, 구글 뉴스는 정말 될이 상대 날짜를 변환하고자하는 "상대"날짜, 예를 들면, 1 시간 전, 또는 1 일 전 대신 십일 1 2017

를 사용 다른 항목과 일치합니다 (예를 들어 2017 년 11 월 12 일이라고도 말합니다). 그러나이 부분부터 시작 해야할지 전혀 모르겠습니다.

내 생각에 오늘 날짜를 나타내는 변수를 만든 다음 내 형식과 일치하지 않는 항목에 대해 데이터 프레임을 통해 일종의 검색을 수행 한 다음 현재 날짜로 상대 시간을 뺍니다. 나는 또한 "시간 전"이 있고 그 동등한 현재 날짜가있는 재료에 대해 일종의 필터를 만들어야 할 것입니다.

나는 해결책을 찾지 않고 오히려 이것을 해결하기 위해 무엇을 읽을 것인지에 대한 일반적인 생각을 갖고 있습니다. numpy를 사용해 보겠나요? 일부 행의

예 :

 Publication Time Headline 
0 The San Diego Union-Tribune  6 hours ago  I am not opposed to new therapeutic modalities... 
1 Devon Live 13 hours ago If you're looking for a bargain this Christmas... 
15 ABS-CBN News 1 day ago Now, Thirdy has a chance to do something that ... 
26 New York Times Nov 2, 2017  Shepherds lead their sheep through the centre ... 
+0

샘플 dataframe – Dark

+0

는 죄송가하십시오 추가 - 방금 편집을! –

+0

어제로 돌아 가면 "시간 전"을 현재 날짜와 같게 만드는 것이 문제가 될 것입니다. 모든 경우에 대해 설명한 방법을 사용하여 datetime 형식으로 변환하는 것이 좋습니다. –

답변

2

당신의 접근 방식이 작동합니다. Pandas Timedelta을 사용하여 현재 날짜의 상대 날짜를 뺍니다. (그냥 쉽게 read_csv() 또는 다른 파일 형식으로 대체 할 수있다) 클립 보드에서 데이터

Publication;Time;Headline 
The San Diego Union-Tribune;6 hours ago;I am not opposed to new therapeutic modalities 
Devon Live;13 hours ago;If you're looking for a bargain this Christmas 
ABS-CBN News;1 day ago;Now, Thirdy has a chance to do something that 
New York Times;Nov 2, 2017;Shepherds lead their sheep through the centre 

읽기 : 귀하의 샘플 데이터를 주어진 예를 들어

,

import pandas as pd 
from datetime import datetime 

df = pd.read_clipboard(sep=";") 

날짜 형식으로되어있는 날짜의 경우 팬더는 to_datetime()으로 변환 할 수있을만큼 똑똑합니다.

absolute_date = pd.to_datetime(df.Time, errors="coerce") 

absolute_date 
0   NaT 
1   NaT 
2   NaT 
3 2017-11-02 
Name: Time, dtype: datetime64[ns] 
우리는 "전"부분을 삭제하면 상대적 날짜 617,451,515,

, 그들이 pd.Timedelta로 변환하는 올바른 형식 기본적으로 위치 :

relative_date = (datetime.today() - 
       df.Time.str.extract("(.*) ago", expand=False).apply(pd.Timedelta)) 

relative_date 
0 2017-11-11 17:05:54.143548 
1 2017-11-11 10:05:54.143548 
2 2017-11-10 23:05:54.143548 
3       NaT 
Name: Time, dtype: datetime64[ns] 

지금 각 세트에서 각각의 NaN 값을 입력, 절대 및 상대는 (Jezrael의 대답을 통해, combine_first()을 사용하도록 업데이트) :

,528,717,246,291 :

date = relative_date.combine_first(absolute_date) 

relative_date 
0 2017-11-11 17:06:29.658925 
1 2017-11-11 10:06:29.658925 
2 2017-11-10 23:06:29.658925 
3 2017-11-02 00:00:00.000000 
Name: Time, dtype: datetime64[ns] 

는 마지막으로, 날짜로부터 단지 날짜를 당겨

+0

정말 고마워요! 그게 믿기지 않을 정도로 간단했습니다. 팬더가 이미이 기능을 가지고 있다는 것을 몰랐습니다. –

+0

당신을 진심으로 환영합니다! –

3

당신은 floorcombine_first을 사용하여 다음 to_timedelta 처음으로 to_datetime을 사용할 수 있습니다 :

#create dates 
dates = pd.to_datetime(df['Time'], errors='coerce') 
#create times 
times = pd.to_timedelta(df['Time'].str.extract('(.*)\s+ago', expand=False)) 
#combine final datetimes 
df['Time'] = (pd.datetime.now() - times).combine_first(dates).dt.floor('D') 

print (df) 
        Publication  Time \ 
0 The San Diego Union-Tribune 2017-11-12 
1     Devon Live 2017-11-11 
2     ABS-CBN News 2017-11-11 
3    New York Times 2017-11-02 

             Headline 
0 I am not opposed to new therapeutic modalities 
1 If you're looking for a bargain this Christmas 
2 Now, Thirdy has a chance to do something that 
3 Shepherds lead their sheep through the centre 

print (df['Time']) 
0 2017-11-12 
1 2017-11-11 
2 2017-11-11 
3 2017-11-02 
Name: Time, dtype: datetime64[ns] 
+0

'combine_first()'는 제게 새로운 것입니다. –

+1

답장을 보내 주셔서 감사합니다. 이것은 아주 잘 작동합니다! –

관련 문제