给定一个极坐标数据框,列值中包含空列表。如何用
pl.Null
或 None
替换它们以便将它们计为缺失值?
输入:
df = pl.DataFrame([
pl.Series('contacts', [[], [], ['1081'], ['1313'], ['3657']], dtype=pl.List(pl.String)),
pl.Series('line_items', [[], [], [], [], []], dtype=pl.List(pl.String)),
])
我已经尝试过:
df.with_columns(
pl.when(pl.col(pl.List(pl.Null)))
.then(None)
.otherwise(pl.col(pl.List))
.name.keep()
)
但是
[]
仍然存在于输出中。
相反,我想要这个:
shape: (5, 2)
┌───────────┬────────────┐
│ contacts ┆ line_items │
│ --- ┆ --- │
│ list[str] ┆ list[str] │
╞═══════════╪════════════╡
│ null ┆ null │
│ null ┆ null │
│ ["1081"] ┆ null │
│ ["1313"] ┆ null │
│ ["3657"] ┆ null │
└───────────┴────────────┘
正如 @Dean MacGregor 提到的,你可以用
.list.len()==0
来做到这一点
这是它的代码:
# transformation for 1 column
df.with_columns(
pl.when(pl.col('contacts').list.len() == 0)
.then(None)
.otherwise(pl.col('contacts'))
.name.keep()
)
shape: (5, 2)
┌───────────┬────────────┐
│ contacts ┆ line_items │
│ --- ┆ --- │
│ list[str] ┆ list[str] │
╞═══════════╪════════════╡
│ null ┆ [] │
│ null ┆ [] │
│ ["1081"] ┆ [] │
│ ["1313"] ┆ [] │
│ ["3657"] ┆ [] │
└───────────┴────────────┘
# transformation for all columns of datatype List(Str)
df.with_columns(
pl.when(pl.col(pl.List(pl.String)).list.len() == 0)
.then(None)
.otherwise(pl.col(pl.List(pl.String)))
.name.keep()
)
shape: (5, 2)
┌───────────┬────────────┐
│ contacts ┆ line_items │
│ --- ┆ --- │
│ list[str] ┆ list[str] │
╞═══════════╪════════════╡
│ null ┆ null │
│ null ┆ null │
│ ["1081"] ┆ null │
│ ["1313"] ┆ null │
│ ["3657"] ┆ null │
└───────────┴────────────┘