如何在现有的 Polars 数据帧上重新推断数据类型?

问题描述 投票:0回答:1

我有以下问题:

我有一个 csv 文件,其中某些行包含错误值(字符串而不是整数)。为了解决这个问题,我将其读入极坐标并过滤数据帧。

为了能够读取它,我必须设置

infer_schema_length = 0
,否则读取将会失败。不过,这会将每一列读取为字符串。我将如何重新推断更正数据帧的数据类型/架构?我想尽量避免单独设置每一列,因为有很多列。

不幸的是我无法编辑 csv 本身。

ids_df = pl.read_csv(dataset_path, infer_schema_length=0)

filtered_df = ids_df.filter(~(pl.col("Label") == "Label"))

filtered_df.dtypes

[Utf8,
 Utf8,
 Utf8,
 Utf8,
 Utf8,
 Utf8,
 Utf8,
 Utf8,
 Utf8,
 Utf8,
 ...

感谢您的帮助。

python csv schema python-polars
1个回答
0
投票

我认为 Polars 还没有这个功能,但我想我找到了解决您问题的有效方法:

from io import BytesIO
import polars as pl
dataset_path = "./test_data.csv"
ids_df = pl.read_csv(dataset_path, infer_schema_length=0)
print("ids_df",ids_df)

filtered_df = ids_df.filter(~(pl.col("Label") == "Label"))
print("filtered_df", filtered_df)

# Save data to memory as a IO stream
bytes_io = BytesIO()
filtered_df.write_csv(bytes_io)

# Read from IO stream with infer_schema_lenth != 0
new_df = pl.read_csv(bytes_io)
print("new_df", new_df)
bytes_io.close()

© www.soinside.com 2019 - 2024. All rights reserved.