
本文详细介绍了如何在polars中高效地重塑包含列表数据的dataframe。通过组合运用`unpivot`、`list.to_struct`和`unnest`等核心操作,教程演示了如何将原始列名转换为新的标识列,并将嵌套的列表元素展开成独立的宽格式列,最终实现数据结构的灵活转换,满足特定的分析需求。
在数据处理和分析中,我们经常需要对DataFrame的结构进行重塑,尤其当数据以列表形式存储在列中时。Polars作为一种高性能的DataFrame库,提供了强大且表达力丰富的API来处理这类复杂的数据转换。本教程将指导您如何将一个包含列表列的Polars DataFrame转换为一种更宽、更扁平的格式,其中原始列名变为新的标识列,而列表中的元素则被展开为独立的数值列。
假设我们有一个Polars DataFrame,其中包含多个列,每列都存储着一个整数列表。例如:
import polars as pl
df = pl.DataFrame({
"foo": [[1, 2, 3], [7, 8, 9]],
"bar": [[4, 5, 6], [1, 0, 1]]
})
print("原始DataFrame:")
print(df)输出:
原始DataFrame: shape: (2, 2) ┌───────────┬───────────┐ │ foo ┆ bar │ │ --- ┆ --- │ │ list[i64] ┆ list[i64] │ ╞═══════════╪═══════════╡ │ [1, 2, 3] ┆ [4, 5, 6] │ │ [7, 8, 9] ┆ [1, 0, 1] │ └───────────┴───────────┘
我们的目标是将其转换为以下结构:
shape: (4, 4) ┌──────┬────────┬────────┬────────┐ │ Name ┆ Value0 ┆ Value1 ┆ Value2 │ │ --- ┆ --- ┆ --- ┆ --- │ │ str ┆ i64 ┆ i64 ┆ i64 │ ╞══════╪════════╪════════╪════════╡ │ foo ┆ 1 ┆ 2 ┆ 3 │ │ foo ┆ 7 ┆ 8 ┆ 9 │ │ bar ┆ 4 ┆ 5 ┆ 6 │ │ bar ┆ 1 ┆ 0 ┆ 1 │ └──────┴────────┴────────┴────────┘
这要求我们将原始列名("foo", "bar")作为新列("Name")的值,并将每个列表的元素展开成多列("Value0", "Value1", "Value2")。
要达到上述目标,我们需要执行一系列链式操作。Polars的表达式系统使得这种复杂转换变得非常直观和高效。
首先,我们需要将原始DataFrame的列名转换为一个新列的值。这可以通过unpivot方法实现,它通常用于将宽格式数据转换为长格式。
# 假设 df 是原始 DataFrame
df_unpivoted = df.unpivot(variable_name="Name")
print("unpivot后的DataFrame:")
print(df_unpivoted)输出:
unpivot后的DataFrame: shape: (4, 2) ┌──────┬───────────┐ │ Name ┆ value │ │ --- ┆ --- │ │ str ┆ list[i64] │ ╞══════╪═══════════╡ │ foo ┆ [1, 2, 3] │ │ foo ┆ [7, 8, 9] │ │ bar ┆ [4, 5, 6] │ │ bar ┆ [1, 0, 1] │ └──────┴───────────┘
现在,我们有了一个Name列,其中包含了原始列名,以及一个value列,其中包含了对应的列表数据。
value列现在包含的是列表。为了将这些列表的每个元素展开为独立的列,我们需要先将每个列表转换为一个结构体(Struct)。结构体是一种复合数据类型,可以包含多个命名字段。
pl.col("value").list.to_struct()方法用于将列表列转换为结构体列。
# 承接 df_unpivoted
df_struct = df_unpivoted.with_columns(
pl.col("value").list.to_struct(fields=lambda x: f"Value{x}")
)
print("list.to_struct后的DataFrame:")
print(df_struct)输出:
list.to_struct后的DataFrame:
shape: (4, 2)
┌──────┬───────────────────┐
│ Name ┆ value │
│ --- ┆ --- │
│ str ┆ struct[i64, i64, … │
╞══════╪═══════════════════╡
│ foo ┆ {1,2,3} │
│ foo ┆ {7,8,9} │
│ bar ┆ {4,5,6} │
│ bar ┆ {1,0,1} │
└──────┴───────────────────┘现在value列的类型变成了struct,其内部包含了我们希望的Value0、Value1、Value2字段。
最后一步是将这个结构体列“展开”,使其内部的字段成为DataFrame的顶级列。这正是unnest方法的作用。
# 承接 df_struct
df_final = df_struct.unnest("value")
print("unnest后的最终DataFrame:")
print(df_final)输出:
unnest后的最终DataFrame: shape: (4, 4) ┌──────┬────────┬────────┬────────┐ │ Name ┆ Value0 ┆ Value1 ┆ Value2 │ │ --- ┆ --- ┆ --- │ --- │ │ str ┆ i64 ┆ i64 ┆ i64 │ ╞══════╪════════╪════════╪════════╡ │ foo ┆ 1 ┆ 2 ┆ 3 │ │ foo ┆ 7 ┆ 8 ┆ 9 │ │ bar ┆ 4 ┆ 5 ┆ 6 │ │ bar ┆ 1 ┆ 0 ┆ 1 │ └──────┴────────┴────────┴────────┘
至此,我们已经成功地将原始DataFrame重塑成了目标格式。
将上述所有步骤组合成一个链式操作,可以得到一个简洁高效的解决方案:
import polars as pl
df = pl.DataFrame({
"foo": [[1, 2, 3], [7, 8, 9]],
"bar": [[4, 5, 6], [1, 0, 1]]
})
output_df = (
df
.unpivot(variable_name="Name")
.with_columns(pl.col("value").list.to_struct(fields=lambda x: f"Value{x}"))
.unnest("value")
)
print("最终输出DataFrame:")
print(output_df)通过掌握这些Polars的核心转换技巧,您可以高效地处理各种复杂的数据重塑任务,从而更好地准备数据以进行进一步的分析或建模。
以上就是Polars DataFrame列的复杂重塑:从列表到宽格式的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号