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

How to re-infer datatypes on existing polars dataframe?

提问人:yarvis 提问时间:11/15/2023 更新时间:11/16/2023 访问量:85

问:

我有以下问题:

我有一个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 架构 python-polars

评论

0赞 jqurious 11/15/2023
你能检查一下吗?例如scan_csvpl.scan_csv(dataset_path).schema
0赞 yarvis 11/15/2023
@jqurious这最初有效,但一旦我获取所有内容,仍然会失败。
0赞 jqurious 11/15/2023
我的意思是: - 但我不确定我是否正确理解了这个问题。filtered_df.cast( pl.scan_csv(..).schema )
1赞 jqurious 11/20/2023
澄清一下,我完全误解了这个问题。感谢@SenseiH的解释。

答:

3赞 SenseiH 11/16/2023 #1

我不认为 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()

output

评论

3赞 jqurious 11/16/2023
我认为您也可以不必手动使用。pl.read_csv(pl.read_csv().filter().write_csv().encode())io.BytesIO
0赞 yarvis 11/20/2023
@jqurious感谢您的输入,它们都完美运行!