Program Club

DataFrame pandas에서 날짜 사이의 일 수가있는 열 추가

proclub 2020. 10. 31. 10:18
반응형

DataFrame pandas에서 날짜 사이의 일 수가있는 열 추가


'B'의 날짜에서 'A'의 날짜를 빼고 차이가있는 새 열을 추가하고 싶습니다.

df
          A        B
one 2014-01-01  2014-02-28 
two 2014-02-03  2014-03-01

다음을 시도했지만 for 루프에 포함하려고하면 오류가 발생합니다.

import datetime
date1=df['A'][0]
date2=df['B'][0]
mdate1 = datetime.datetime.strptime(date1, "%Y-%m-%d").date()
rdate1 = datetime.datetime.strptime(date2, "%Y-%m-%d").date()
delta =  (mdate1 - rdate1).days
print delta

어떻게해야합니까?


이것이 datetime 열이라고 가정하면 (적용되지 않는 경우 to_datetime) 빼면됩니다.

df['A'] = pd.to_datetime(df['A'])
df['B'] = pd.to_datetime(df['B'])

In [11]: df.dtypes  # if already datetime64 you don't need to use to_datetime
Out[11]:
A    datetime64[ns]
B    datetime64[ns]
dtype: object

In [12]: df['A'] - df['B']
Out[12]:
one   -58 days
two   -26 days
dtype: timedelta64[ns]

In [13]: df['C'] = df['A'] - df['B']

In [14]: df
Out[14]:
             A          B        C
one 2014-01-01 2014-02-28 -58 days
two 2014-02-03 2014-03-01 -26 days

참고 : 새로운 pandas (예 : 0.13.1)를 사용하고 있는지 확인하세요. 이전 버전에서는 작동하지 않을 수 있습니다.


'days'텍스트 요소를 제거하려면 시리즈에 대한 dt () 접근자를 사용할 수도 있습니다. https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.html

그래서,

df['A'] = pd.to_datetime(df['A'])
df['B'] = pd.to_datetime(df['B'])

df['C'] = (df['B'] - df['A']).dt.days

다음을 반환합니다.

             A          B   C
one 2014-01-01 2014-02-03  33
two 2014-02-03 2014-03-01  26

목록 이해는이를 수행하는 가장 Pythonic (그리고 가장 빠른) 방법에 대한 최선의 선택입니다.

[int(i.days) for i in (df.B - df.A)]
  1. timedelta (예 : '-58 일')를 반환합니다.
  2. i.days will return this value as a long integer value(e.g. -58L)
  3. int(i.days) will give you the -58 you seek.

If your columns aren't in datetime format. The shorter syntax would be: df.A = pd.to_datetime(df.A)


How about this:

times['days_since'] = max(list(df.index.values))  
times['days_since'] = times['days_since'] - times['months']  
times

참고URL : https://stackoverflow.com/questions/22132525/add-column-with-number-of-days-between-dates-in-dataframe-pandas

반응형