Python Connector와 함께 pandas DataFrames 사용하기

pandas is a library for data analysis. With pandas, you use a data structure called a DataFrame to analyze and manipulate two-dimensional data (such as data from a database table).

Snowflake 데이터베이스의 데이터를 pandas DataFrame으로 가져오려면 Python용 Snowflake 커넥터에서 제공되는 API 메서드를 사용할 수 있습니다. 이 커넥터는 pandas DataFrame에서 Snowflake 데이터베이스로 데이터를 쓰기 위한 API 메서드로 제공합니다.

참고

Some of these API methods require a specific version of the PyArrow library. See Requirements for details.

이 항목의 내용:

요구 사항

현재, Python 커넥터 API의 pandas 지향 API 메서드는 다음에서 동작합니다.

  • Python용 Snowflake 커넥터 2.1.2 이상.

  • PyArrow library version 3.0.x.

    PyArrow를 설치하지 않은 경우에는 PyArrow를 설치할 필요가 없습니다. 아래의 설명과 같이 Python Connector를 설치하면 PyArrow의 적절한 버전이 자동으로 설치됩니다.

    조심

    위의 권장 버전이 아닌 PyArrow 라이브러리 버전을 이미 설치한 경우에는 PyArrow의 설치를 제거한 후 Python용 Snowflake 커넥터를 설치하십시오. Python용 Snowflake 커넥터를 설치한 후에 다른 PyArrow 버전을 다시 설치하지 마십시오.

  • pandas 0.25.2 이상. 이전 버전은 동작할 수 있지만, 테스트가 수행되지 않았습니다.

설치

Python용 Snowflake 커넥터의 pandas 호환 버전을 설치하려면 다음 명령을 실행합니다.

pip install "snowflake-connector-python[pandas]"
Copy

You must enter the square brackets ([ and ]) as shown in the command. The square brackets specify the extra part of the package that should be installed.

예에서와 같이 패키지 이름 주위에 따옴표를 사용하여 대괄호가 와일드카드로 해석되지 않도록 합니다.

다른 추가 항목(예: 브라우저 기반SSO를 사용한 연결 캐싱 또는 MFA 토큰 캐싱을 위한 secure-local-storage)을 설치해야 하는 경우에는 추가 항목 사이에 쉼표를 사용합니다.

pip install "snowflake-connector-python[secure-local-storage,pandas]"
Copy

Snowflake 데이터베이스에서 pandas DataFrame으로 데이터 읽기

pandas DataFrame로 데이터를 읽으려면, Cursor 를 사용하여 데이터를 검색한 후 이러한 Cursor 메서드 중 하나를 호출하여 데이터를 pandas DataFrame에 추가합니다.

pandas DataFrame에서 Snowflake 데이터베이스로 데이터 쓰기

pandas DataFrame에서 Snowflake 데이터베이스로 데이터를 쓰려면, 다음 중 1개 를 수행합니다.

Snowflake에서 pandas로 데이터 매핑

아래 테이블은 Snowflake 데이터 타입에서 pandas 데이터 타입으로의 매핑을 보여줍니다.

Snowflake 데이터 타입

pandas 데이터 타입

FIXED NUMERIC 타입(소수 자릿수 = 0), DECIMAL 제외

(u)int{8,16,32,64} 또는 float64 (NULL의 경우)

FIXED NUMERIC 타입(소수 자릿수 > 0), DECIMAL 제외

float64

FIXED NUMERIC 타입 DECIMAL

decimal

FLOAT/DOUBLE

float64

VARCHAR

str

BINARY

str

VARIANT

str

DATE

object (datetime.date 오브젝트 포함)

TIME

pandas.Timestamp(np.datetime64[ns])

TIMESTAMP_NTZ, TIMESTAMP_LTZ, TIMESTAMP_TZ

pandas.Timestamp(np.datetime64[ns])

참고:

  • Snowflake 데이터 타입이 FIXED NUMERIC이고 소수 자릿수가 0이며 값이 NULL인 경우, 값은 정수 타입이 아닌 float64 로 변환됩니다.

  • 변환에서 오버플로가 발생하는 경우 Python 커넥터에서 예외가 throw됩니다.

pandas 가져오기

관례적으로 pandas는 다음 문을 통해 가져옵니다.

import pandas as pd
Copy

pandas 오브젝트에 대한 참조는 pandas.object 또는 pd.object 로 확인할 수 있습니다.

pandas DataFrames로 마이그레이션하기

이 섹션의 주 대상은 이전에 pandas(및 아마도 SQLAlchemy)를 사용한 경험이 있는 사용자입니다.

이전 pandas 사용자는 다음 중 하나와 유사한 코드를 사용했을 것입니다.

  • 이 예에서는 Python 커넥터에서 pandas DataFrame을 생성하기 위한 원래 방법을 보여줍니다.

    import pandas as pd
    
    def fetch_pandas_old(cur, sql):
        cur.execute(sql)
        rows = 0
        while True:
            dat = cur.fetchmany(50000)
            if not dat:
                break
            df = pd.DataFrame(dat, columns=cur.description)
            rows += df.shape[0]
        print(rows)
    
    Copy
  • 이 예에서는 SQLAlchemy를 사용하여 pandas DataFrame을 생성하는 방법을 보여줍니다.

    import pandas as pd
    
    def fetch_pandas_sqlalchemy(sql):
        rows = 0
        for chunk in pd.read_sql_query(sql, engine, chunksize=50000):
            rows += chunk.shape[0]
        print(rows)
    
    Copy

앞의 예시 중 1개와 유사한 코드는 이 항목의 Snowflake 데이터베이스에서 pandas DataFrame으로 데이터 읽기 에서 제공되는 Python 커넥터 pandas API 호출을 사용하도록 변환할 수 있습니다.

참고

Python 커넥터에서 pandas가 지원됨으로써, 더 이상 SQLAlchemy가 커서의 데이터를 DataFrame으로 변환할 필요가 없습니다.

그러나 원하면 SQLAlchemy를 계속해서 사용할 수 있으며, Python 커넥터는 SQLAlchemy와 계속해서 호환됩니다.