Pandas: 연도, 월, 일로 날짜 열 만들기


다음 기본 구문을 사용하여 Pandas DataFrame의 연도, 월, 일 열에서 날짜 열을 만들 수 있습니다.

 df[' date '] = pd. to_datetime (dict(year=df. year , month=df. month , day=df. day ))

다음 예에서는 실제로 이 구문을 사용하는 방법을 보여줍니다.

예: Pandas에서 연도, 월, 일로 날짜 열 만들기

다양한 날짜에 회사의 매출을 보여주는 다음과 같은 pandas DataFrame이 있다고 가정해 보겠습니다.

 import pandas as pd

#createDataFrame
df = pd. DataFrame ({' year ': [2021, 2022, 2022, 2022, 2022, 2022, 2022, 2022],
                   ' month ': [7, 1, 1, 2, 5, 10, 11, 12],
                   ' day ': [4, 15, 25, 27, 27, 24, 10, 18],
                   ' sales ': [140, 200, 250, 180, 130, 87, 90, 95]})

#view DataFrame
print (df)

   year month day sales
0 2021 7 4 140
1 2022 1 15 200
2 2022 1 25 250
3 2022 2 27 180
4 2022 5 27 130
5 2022 10 24 87
6 2022 11 10 90
7 2022 12 18 95

다음 구문을 사용하여 DataFrame의 year , Monthday 열 값을 결합하여 각 행에 대한 날짜를 생성하는 date 라는 새 열을 생성할 수 있습니다.

 #create date columns from year, month, and day columns
df[' date '] = pd. to_datetime (dict(year=df. year , month=df. month , day=df. day ))

#view updated DataFrame
print (df)

   year month day sales date
0 2021 7 4 140 2021-07-04
1 2022 1 15 200 2022-01-15
2 2022 1 25 250 2022-01-25
3 2022 2 27 180 2022-02-27
4 2022 5 27 130 2022-05-27
5 2022 10 24 87 2022-10-24
6 2022 11 10 90 2022-11-10
7 2022 12 18 95 2022-12-18

날짜 열에는 각 행의 연도 , , 열의 값을 기준으로 날짜 값이 포함되어 있습니다.

df.info()를 사용하여 DataFrame의 각 열에 대한 정보를 가져오면 새 날짜 열에 datetime64 데이터 유형이 있음을 알 수 있습니다.

 #display information about each column in DataFrame
df. info ()

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 8 entries, 0 to 7
Data columns (total 5 columns):
 # Column Non-Null Count Dtype         
--- ------ -------------- -----         
 0 year 8 non-null int64         
 1 month 8 non-null int64         
 2 day 8 non-null int64         
 3 dirty 8 non-null int64         
 4 date 8 non-null datetime64[ns]
dtypes: datetime64[ns](1), int64(4)
memory usage: 388.0 bytes

추가 리소스

다음 튜토리얼에서는 Pandas에서 다른 일반적인 작업을 수행하는 방법을 설명합니다.

Pandas에서 날짜에 일수를 더하고 빼는 방법
Pandas에서 두 날짜 사이의 행을 선택하는 방법
팬더에서 두 날짜의 차이를 계산하는 방법

의견을 추가하다

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다