Programing

Pandas 데이터 프레임의 날짜를 '날짜'데이터 유형으로 어떻게 변환합니까?

lottogame 2020. 10. 9. 08:42
반응형

Pandas 데이터 프레임의 날짜를 '날짜'데이터 유형으로 어떻게 변환합니까?


팬더 데이터 프레임이 있는데 그 열 중 하나에 'YYYY-MM-DD'형식의 날짜 문자열 (예 : '2013-10-28')이 포함되어 있습니다.

현재 컬럼의 dtype은 'object'입니다.

열 값을 Pandas 날짜 형식으로 어떻게 변환합니까?


astype 사용

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

기본적으로 @waitingkuo와 동일하지만 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')

CSV 파일에서 많은 데이터가 Pandas로 들어 온다고 생각합니다.이 경우 처음 CSV를 읽는 동안 날짜를 간단히 변환 할 수 있습니다.

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

http://pandas.pydata.org/pandas-docs/stable/generated/pandas.io.parsers.read_csv.html 참조


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

datetime 객체의 경우 모두 00:00:00 인 시간이 표시되지 않으면 판다가 아닙니다. 그것은 사물을 예쁘게 보이게하려는 iPython 노트북입니다.


이를 수행하는 또 다른 방법은 datetime으로 변환 할 여러 열이있는 경우 잘 작동합니다.

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

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

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

After this, you can more easily convert to the type of date format you will need most. Below, I sequentially convert to a number of date formats, ultimately ending up with a set of daily dates at the beginning of the month.

#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)

For brevity, I don't show that I run the following code after each line above:

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

This gives me the following output:

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'>

참고URL : https://stackoverflow.com/questions/16852911/how-do-i-convert-dates-in-a-pandas-data-frame-to-a-date-data-type

반응형