Pandas에서 타임스탬프를 문자열로 변환

Vaibhhav Khetarpal 2023년6월21일
  1. dt.stfrtime() 함수를 사용하여 Pandas 타임스탬프 시리즈를 문자열로 변환
  2. astype() 함수를 사용하여 Pandas 타임스탬프 시리즈를 문자열로 변환
Pandas에서 타임스탬프를 문자열로 변환

Pandas는 데이터 분석 및 조작에 사용되는 공식적으로 인정된 Python 라이브러리이며 일반적으로 Pandas DataFrame이라는 값을 저장하기 위해 변경 가능한 데이터 구조를 사용합니다. 일반 데이터와 별도로 Pandas DataFrame은 날짜/시간 값을 저장하는 훌륭한 옵션입니다.

Pandas DataFrame에 저장된 타임스탬프 시리즈를 Python의 문자열로 변환하는 방법에는 두 가지가 있으며, 둘 다 이 문서의 아래에 자세히 설명되어 있습니다.

dt.stfrtime() 함수를 사용하여 Pandas 타임스탬프 시리즈를 문자열로 변환

strftime() 함수는 datetime 객체를 문자열로 변환합니다. 단순히 주어진 datetime 객체의 문자열 표현입니다.

Python에서 접두사로 dt 접근자와 결합하면 dt.strftime() 함수는 일련의 타임스탬프 또는 날짜 시간 개체에서 문자열을 변환한 후 일련의 문자열을 반환할 수 있습니다. 다음 코드는 dt.stfrtime() 함수를 사용하여 Python의 pandas 타임스탬프 시리즈를 문자열로 변환합니다.

암호:

import pandas as pd

dfx = pd.DataFrame(
    {
        "date": pd.to_datetime(
            pd.Series(["20210101", "20210105", "20210106", "20210109"])
        ),
        "tickets sold": [1080, 1574, 2279, 1910],
    }
)
dfx["date"] = dfx["date"].dt.strftime("%Y-%m-%d")
print(dfx)
print(dfx.dtypes)

출력:

         date  tickets sold
0  2021-01-01          1080
1  2021-01-05          1574
2  2021-01-06          2279
3  2021-01-09          1910
date            object
tickets sold     int64
dtype: object

astype() 함수를 사용하여 Pandas 타임스탬프 시리즈를 문자열로 변환

astype() 함수는 Pandas DataFrame 열의 데이터 유형을 변환합니다. astype() 함수는 단일 열 또는 열 집합 모두의 경우에 동일하게 작동합니다.

통사론:

df.astype(dtype, copy=True, errors="raise")

위에서 언급한 기능에 대한 매개변수는 아래에서 자세히 설명합니다.

  1. dtype - 주어진 타임스탬프 시리즈를 변환하려는 데이터 유형을 지정합니다.
  2. copy - True로 설정하면 내용의 복사본을 생성한 다음 필요에 따라 변경합니다.
  3. 오류 - 예외 발생을 허용할지 여부를 지정합니다. 값은 raise 또는 ignore일 수 있습니다.

다음 예제에서는 astype() 함수를 사용하여 Python의 pandas 타임스탬프 시리즈를 문자열로 변환합니다.

암호:

import pandas as pd

dfx = pd.DataFrame(
    {
        "date": pd.to_datetime(
            pd.Series(["20210101", "20210105", "20210106", "20210109"])
        ),
        "tickets sold": [1080, 1574, 2279, 1910],
    }
)
dfx["date"] = dfx["date"].astype(str)
print(dfx)
print(dfx.dtypes)

출력:

         date  tickets sold
0  2021-01-01          1080
1  2021-01-05          1574
2  2021-01-06          2279
3  2021-01-09          1910
date            object
tickets sold     int64
dtype: object
Vaibhhav Khetarpal avatar Vaibhhav Khetarpal avatar

Vaibhhav is an IT professional who has a strong-hold in Python programming and various projects under his belt. He has an eagerness to discover new things and is a quick learner.

LinkedIn

관련 문장 - Pandas String