WeniVooks

검색

Right Now, Polars

Polars 설치 및 기본 사용법

1. Polars 설치

Polars는 Python의 패키지 관리 시스템인 pip를 사용하여 쉽게 설치할 수 있습니다. 설치를 위해 터미널이나 명령 프롬프트에서 다음과 같은 명령어를 실행합니다.

$ pip install polars
$ pip install polars

외부 종속성이 없기 때문에 추가적인 라이브러리 설치할 필요가 없습니다. 또한, 설치 공간을 최소화하기 위해 선택적으로 의존성을 설치할 수 있습니다.

$ pip install polars[numpy, fsspec]
$ pip install polars[numpy, fsspec]
태그설명
all모든 선택적 의존성 설치 (아래 모두 포함)
pandasDataframe/Series로 데이터 변환을 위해 Panda와 함께 설치
numpy데이터를 numpy 배열로 변환하기 위해 numpy를 사용하여 설치
pyarrowPyArrow를 사용한 데이터 형식 읽기
fsspec원격 파일 시스템에서 읽기 지원
connectorxSQL 데이터베이스에서 읽기 지원
xlsx2csvExcel 파일에서 읽기 지원
deltalakeDelta Lake 테이블에서 읽기 지원
plot시각화 지원
timezone시간대 지원. Python < 3.9 사용 중이거나 Windows 사용 중인 경우에만 필요. 그렇지 않으면 의존성이 설치되지 않음
1.1 Windows
  1. 먼저, Python을 설치합니다. Python 3.x 버전을 사용하시는 것을 권장합니다.

  2. 명령 프롬프트(cmd)를 열고, 다음 명령어를 입력합니다.

    $ pip install polars
    $ pip install polars
  3. 설치가 완료되면, 다음과 같이 Polars 버전을 확인할 수 있습니다.

    $ python -c "import polars as pl; print(pl.__version__)"
    $ python -c "import polars as pl; print(pl.__version__)"
1.2 MacOS
  1. 먼저, Homebrew를 설치합니다. 다음 명령어를 터미널에서 실행합니다.

    $ /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
    $ /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
  2. 다음으로, Python을 설치합니다.

    $ brew install python
    $ brew install python
  3. 이제, 다음 명령어를 터미널에서 실행하여 Polars를 설치합니다.

    $ pip install polars
    $ pip install polars
  4. 설치가 완료되면, 다음과 같이 Polars 버전을 확인할 수 있습니다.

    $ python -c "import polars as pl; print(pl.__version__)"
    $ python -c "import polars as pl; print(pl.__version__)"
1.3 Linux
  1. 먼저, Linux 배포판의 패키지 관리자를 이용하여 Python을 설치합니다.

    • Debian/Ubuntu:
      $ sudo apt-get update
      $ sudo apt-get install python3
      $ sudo apt-get update
      $ sudo apt-get install python3
    • Fedora:
      $ sudo dnf update
      $ sudo dnf install python3
      $ sudo dnf update
      $ sudo dnf install python3
    • CentOS/RHEL:
      $ sudo yum update
      $ sudo yum install python3
      $ sudo yum update
      $ sudo yum install python3
  2. 다음 명령어를 실행하여 Polars를 설치합니다.

    $ pip install polars
    $ pip install polars
  3. 설치가 완료되면, 다음과 같이 Polars 버전을 확인할 수 있습니다.

    $ python -c "import polars as pl; print(pl.__version__)"
    $ python -c "import polars as pl; print(pl.__version__)"

위의 방법들은 각 운영체제에 기본적으로 설치된 Python 버전을 이용하여 Polars를 설치합니다. Python 버전이 충돌이나 다른 문제로 인해 원하는 결과를 얻을 수 없을 경우, 가상환경(virtual environment)을 이용하여 Python 및 Polars를 설치하는 것을 권장합니다.

1.4 Google Colab

Colab에는 기본적으로 Polars가 설치되어 있어 따로 설치하지 않으셔도 됩니다.

$ !pip install polars
$ !pip install polars

라이브러리를 사용하기 위해 import를 합니다.

import polars as pl
import polars as pl

2. 기본 사용법 예시

Polars를 사용하여 간단한 데이터 분석을 작업을 수행하는 기본적인 예시를 살펴봅시다. 먼저, Polars를 임포트하고, 간단한 데이터프레임을 생성합니다.

import polars as pl
import time
 
start_time = time.time()
# 간단한 데이터프레임 생성
df = pl.DataFrame({
    "name": ["Alice", "Bob", "Charlie"],
    "age": [25, 26, 27],
    "city": ["New York", "Paris", "London"]
})
 
print(df)
end_time = time.time()
print(end_time-start_time) # 0.0006868839263916016
import polars as pl
import time
 
start_time = time.time()
# 간단한 데이터프레임 생성
df = pl.DataFrame({
    "name": ["Alice", "Bob", "Charlie"],
    "age": [25, 26, 27],
    "city": ["New York", "Paris", "London"]
})
 
print(df)
end_time = time.time()
print(end_time-start_time) # 0.0006868839263916016
  • pl.DataFrame : 데이터프레임을 생성하는 메서드
shape: (3, 3)
┌─────────┬─────┬──────────┐
│ name    ┆ age ┆ city     │
│ ---     ┆ --- ┆ ---      │
│ str     ┆ i64 ┆ str      │
╞═════════╪═════╪══════════╡
│ Alice   ┆ 25  ┆ New York │
│ Bob     ┆ 26  ┆ Paris    │
│ Charlie ┆ 27  ┆ London   │
└─────────┴─────┴──────────┘
0.0006868839263916016
shape: (3, 3)
┌─────────┬─────┬──────────┐
│ name    ┆ age ┆ city     │
│ ---     ┆ --- ┆ ---      │
│ str     ┆ i64 ┆ str      │
╞═════════╪═════╪══════════╡
│ Alice   ┆ 25  ┆ New York │
│ Bob     ┆ 26  ┆ Paris    │
│ Charlie ┆ 27  ┆ London   │
└─────────┴─────┴──────────┘
0.0006868839263916016

이름, 나이, 도시 정보를 가진 간단한 데이터프레임을 생성하고 출력합니다. Polars를 사용하여 데이터를 쉽게 조작하고, 분석할 수 있는 다양한 기능을 제공합니다.

예를 들어, 나이가 25세 이상인 사람들만 선택하거나, 특정 컬럼 기준으로 정렬하는 것과 같은 작업을 손쉽게 수행할 수 있습니다.

이번에는 Pandas를 사용하여 간단한 데이터 분석 작업을 수행해보겠습니다. 먼저, Pandas를 임포트하고 간단한 데이터프레임을 생성합니다.

import pandas as pd
 
start_time = time.time()
# 간단한 데이터프레임 생성
data = {
    "Name": ["John", "Anna", "Peter", "Linda"],
    "Age": [28, 34, 29, 32],
    "City": ["New York", "Paris", "Berlin", "London"]
}
 
df = pd.DataFrame(data)
 
print(df)
end_time = time.time()
print(end_time-start_time) # 0.0025756359100341797
import pandas as pd
 
start_time = time.time()
# 간단한 데이터프레임 생성
data = {
    "Name": ["John", "Anna", "Peter", "Linda"],
    "Age": [28, 34, 29, 32],
    "City": ["New York", "Paris", "Berlin", "London"]
}
 
df = pd.DataFrame(data)
 
print(df)
end_time = time.time()
print(end_time-start_time) # 0.0025756359100341797
    Name  Age      City
0   John   28  New York
1   Anna   34     Paris
2  Peter   29    Berlin
3  Linda   32    London
0.0025756359100341797
    Name  Age      City
0   John   28  New York
1   Anna   34     Paris
2  Peter   29    Berlin
3  Linda   32    London
0.0025756359100341797

코드를 보시면 위의 Polars와 거의 차이가 없는 것을 확인할 수 있습니다. 이처럼 Polars는 Pandas와 비슷한 코드 구조를 가지면서도 성능이 빠르다는 장점이 있기 때문에 서로 유연하게 활용할 수 있습니다.

{"packages":["numpy","pandas","matplotlib","lxml"]}
2.1 Polars란?2.3 데이터 분석 라이브러리 소개 및 비교