我想读取CSV文件,其中一些列是这种类型的字符串:"[1.0, 0.0, -2.3]".

因此,我希望将该字符串解析为一个浮点数列表,为此,我使用了以下代码.

import polars as pl

df = pl.scan_csv(
    "foo.csv",
).with_columns(
    pl.col("^list.*$").str.strip("[ ]").str.split(",").cast(pl.List(pl.Float64)),
).collect()

其中一些字符串是空列表:"[]";当我解析它们时,我得到了一个类似以下的列表:[null].

我想删除其中有包含空元素的列表的所有行.

这是我试着使用的代码

df.filter(
    pl.all_horizontal(
        ~pl.col("^list.*$").list.contains(None)
    )
)

但它给了我这个错误

InvalidOperationError: `is_in` operation not supported for dtype `list[f64]`

我提供了一个小示例文件来自己测试代码:

list1,list2,list3
"[]","[0.0, 1.2]","[3.4]"
"[102, 506]","[12, 5.2]","[2.3]"
"[15]","[0.5, 8.2]","[]"

在本例中,我只希望将第二行保留在DataFrame中.

推荐答案

在选角前做判断可能会更简单.

我认为您希望替换(或替换_all)空格,因为您当前的代码丢失了506.

nums = pl.col("^list.*$").str.replace(" ", "").str.strip("[]")

df.with_columns(
   pl.when(nums != "")
     .then(nums.str.split(",").cast(pl.List(pl.Float64)))
).collect()
shape: (3, 3)
┌────────────────┬─────────────┬───────────┐
│ list1          ┆ list2       ┆ list3     │
│ ---            ┆ ---         ┆ ---       │
│ list[f64]      ┆ list[f64]   ┆ list[f64] │
╞════════════════╪═════════════╪═══════════╡
│ null           ┆ [0.0, 1.2]  ┆ [3.4]     │
│ [102.0, 506.0] ┆ [12.0, 5.2] ┆ [2.3]     │
│ [15.0]         ┆ [0.5, 8.2]  ┆ null      │
└────────────────┴─────────────┴───────────┘

我们使用.when().then()来判断替换/剥离的结果是否为空字符串.

默认的.otherwise(None)分支意味着我们将有null个值用于空列表.

然后,您只需在COLLECT前使用.drop_nulls()即可删除任何包含空列的行.

df.with_columns(
   pl.when(nums != "")
     .then(nums.str.split(",").cast(pl.List(pl.Float64)))
).drop_nulls().collect()
shape: (1, 3)
┌────────────────┬─────────────┬───────────┐
│ list1          ┆ list2       ┆ list3     │
│ ---            ┆ ---         ┆ ---       │
│ list[f64]      ┆ list[f64]   ┆ list[f64] │
╞════════════════╪═════════════╪═══════════╡
│ [102.0, 506.0] ┆ [12.0, 5.2] ┆ [2.3]     │
└────────────────┴─────────────┴───────────┘

或者更好的做法是先过滤,然后再转换剩余部分:

(df.filter(pl.all_horizontal(pl.all() != "[]"))
   .with_columns(
      pl.all().str.replace(" ", "")
        .str.strip("[]")
        .str.split(",")
        .cast(pl.List(pl.Float64))
   )
).collect()

Python相关问答推荐

将两个收件箱相连导致索引的列标题消失

单击cookie按钮,但结果不一致

Pandas 按照特殊规则保留每n行

保留包含pandas pandras中文本的列

如果我已经使用了time,如何要求Python在12秒后执行另一个操作.sleep

绘制系列时如何反转轴?

当值是一个integer时,在Python中使用JMESPath来验证字典中的值(例如:1)

Python中MongoDB的BSON时间戳

返回nxon矩阵的diag元素,而不使用for循环

如果条件为真,则Groupby.mean()

点到面的Y距离

ModuleNotFound错误:没有名为Crypto Windows 11、Python 3.11.6的模块

如何制作10,000年及以后的日期时间对象?

大小为M的第N位_计数(或人口计数)的公式

当从Docker的--env-file参数读取Python中的环境变量时,每个\n都会添加一个\'.如何没有额外的?

Python解析整数格式说明符的规则?

为什么NumPy的向量化计算在将向量存储为类属性时较慢?'

如何在Python中使用另一个数据框更改列值(列表)

如何在Python中使用Pandas将R s Tukey s HSD表转换为相关矩阵''

在极中解析带有数字和SI前缀的字符串