파이썬(Python)&판다스(Pandas)&Polars

[polars] 데이터프레임의 특정 컬럼 또는 모든 컬럼의 데이터 타입 변경하기(cast)

송채채 2023. 11. 21. 12:53

공식홈페이지 기본 문법

df.cast({"foo": pl.Float32, "bar": pl.UInt8})

 

  • 모든 데이터의 형식을 str(문자열)로 바꾸기 -> utf8
df = df.with_columns(pl.all().cast(pl.Utf8, strict=False))

 

with_columns로 모든 컬럼(pl.all())을 불러오고, 모든 컬럼의 데이터 타입을 cast로 지정해 변환함

strict는 예외발생시 강제로 수행할 것인가를 지정함

 

df.with_columns(pl.col("foo").cast(pl.List(pl.Utf8)))
shape: (1, 2)
┌─────────────────┬─────────────┐
│ foo             | bar         │
│ ---             | ---         │
│ list[str]       | str         │
╞═════════════════╪═════════════╡
│ ["1", "2", "3"] | Hello World │
└─────────────────┴─────────────┘
반응형