programing

Pandas 데이터 프레임의 문자열을 '날짜' 데이터 유형으로 변환하려면 어떻게 해야 합니까?

iphone6s 2023. 7. 21. 21:26
반응형

Pandas 데이터 프레임의 문자열을 '날짜' 데이터 유형으로 변환하려면 어떻게 해야 합니까?

Pandas 데이터 프레임이 있는데, 열 중 하나에 날짜 문자열이 형식으로 포함되어 있습니다.YYYY-MM-DD

예를 들어.'2013-10-28'

그 순간에.dtype열의 하나는object.

열 값을 Pandas 날짜 형식으로 변환하려면 어떻게 해야 합니까?

본질적으로 @waitingkuo와 동일하지만, 저는 사용할 것입니다.pd.to_datetime여기에 (조금 더 깨끗해 보이고, 몇 가지 추가 기능을 제공합니다. 예를 예로 들 수 있습니다.dayfirst):

In [11]: df
Out[11]:
   a        time
0  1  2013-01-01
1  2  2013-01-02
2  3  2013-01-03

In [12]: pd.to_datetime(df['time'])
Out[12]:
0   2013-01-01 00:00:00
1   2013-01-02 00:00:00
2   2013-01-03 00:00:00
Name: time, dtype: datetime64[ns]

In [13]: df['time'] = pd.to_datetime(df['time'])

In [14]: df
Out[14]:
   a                time
0  1 2013-01-01 00:00:00
1  2 2013-01-02 00:00:00
2  3 2013-01-03 00:00:00

처리ValueErrors
만약 당신이 하는 상황에 부딪히면.

df['time'] = pd.to_datetime(df['time'])

를 던집니다.

ValueError: Unknown string format

즉, 유효하지 않은(강제되지 않은) 값이 있습니다.만약 당신이 그것들을 변환하는 것이 괜찮다면.pd.NaT추가할 수 있습니다.errors='coerce'에 대한 주장.to_datetime:

df['time'] = pd.to_datetime(df['time'], errors='coerce')

유형 사용

In [31]: df
Out[31]: 
   a        time
0  1  2013-01-01
1  2  2013-01-02
2  3  2013-01-03

In [32]: df['time'] = df['time'].astype('datetime64[ns]')

In [33]: df
Out[33]: 
   a                time
0  1 2013-01-01 00:00:00
1  2 2013-01-02 00:00:00
2  3 2013-01-03 00:00:00

CSV 파일에서 Panda로 대량의 데이터가 유입될 것으로 예상됩니다. 이 경우 초기 CSV 읽기 중에 간단히 날짜를 변환할 수 있습니다.

dfcsv = pd.read_csv('xyz.csv', parse_dates=[0])여기서 0은 날짜가 있는 열을 나타냅니다.
추가할 수도 있습니다., index_col=0날짜를 인덱스로 지정하려면 여기에 있습니다.

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html 을 참조하십시오.

위치가 아닌 이름으로 구문 분석할 열을 선택할 수도 있습니다.parse_dates=['thedate']

이제 할 수 있습니다.df['column'].dt.date

날짜/시간 개체의 경우 시간이 모두 00:00:00인 경우 판다가 아닙니다.그것은 아이파이톤 노트북입니다. 사물을 예쁘게 보이려고 노력하는 것입니다.

DATTIME 형식이 아닌 DATE 형식을 가져오려면 다음을 수행합니다.

df["id_date"] = pd.to_datetime(df["id_date"]).dt.date

날짜 시간으로 변환할 열이 여러 개 있는 경우 이 방법과 이 방법이 잘 작동합니다.

cols = ['date1','date2']
df[cols] = df[cols].apply(pd.to_datetime)

날짜를 다른 빈도로 변환해야 하는 경우가 있을 수 있습니다.이 경우 날짜별로 인덱스를 설정하는 것이 좋습니다.

#set an index by dates
df.set_index(['time'], drop=True, inplace=True)

그런 다음 가장 필요한 날짜 형식으로 쉽게 변환할 수 있습니다.아래에서는 여러 날짜 형식으로 순차적으로 변환하여 최종적으로 월초에 일련의 일별 날짜를 지정합니다.

#Convert to daily dates
df.index = pd.DatetimeIndex(data=df.index)

#Convert to monthly dates
df.index = df.index.to_period(freq='M')

#Convert to strings
df.index = df.index.strftime('%Y-%m')

#Convert to daily dates
df.index = pd.DatetimeIndex(data=df.index)

간략하게 설명하기 위해 위의 각 줄 뒤에 다음 코드를 실행하지 않습니다.

print(df.index)
print(df.index.dtype)
print(type(df.index))

그러면 다음과 같은 출력이 표시됩니다.

Index(['2013-01-01', '2013-01-02', '2013-01-03'], dtype='object', name='time')
object
<class 'pandas.core.indexes.base.Index'>

DatetimeIndex(['2013-01-01', '2013-01-02', '2013-01-03'], dtype='datetime64[ns]', name='time', freq=None)
datetime64[ns]
<class 'pandas.core.indexes.datetimes.DatetimeIndex'>

PeriodIndex(['2013-01', '2013-01', '2013-01'], dtype='period[M]', name='time', freq='M')
period[M]
<class 'pandas.core.indexes.period.PeriodIndex'>

Index(['2013-01', '2013-01', '2013-01'], dtype='object')
object
<class 'pandas.core.indexes.base.Index'>

DatetimeIndex(['2013-01-01', '2013-01-01', '2013-01-01'], dtype='datetime64[ns]', freq=None)
datetime64[ns]
<class 'pandas.core.indexes.datetimes.DatetimeIndex'>

완전성을 위해 @SSS에서 제안한 옵션과 약간 유사하지만 datetime 라이브러리를 사용하는 다른 옵션은 다음과 같습니다.

import datetime
df["Date"] = df["Date"].apply(lambda x: datetime.datetime.strptime(x, '%Y-%d-%m').date())
 #   Column          Non-Null Count   Dtype         
---  ------          --------------   -----         
 0   startDay        110526 non-null  object
 1   endDay          110526 non-null  object

import pandas as pd

df['startDay'] = pd.to_datetime(df.startDay)

df['endDay'] = pd.to_datetime(df.endDay)

 #   Column          Non-Null Count   Dtype         
---  ------          --------------   -----         
 0   startDay        110526 non-null  datetime64[ns]
 1   endDay          110526 non-null  datetime64[ns]

당신은 판다를 사용할 수 있습니다.to_datetime()

pd.to _datetime 함수를 사용하여 행 중 하나를 타임스탬프로 변환한 다음 .map을 사용하여 공식을 전체 열에 매핑합니다.

언급URL : https://stackoverflow.com/questions/16852911/how-do-i-convert-strings-in-a-pandas-data-frame-to-a-date-data-type

반응형