You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Polars中与Pandas .values等价的DataFrame转数组方法是什么?

Polars中实现等价于Pandas .values 的数组转换方法

在Polars中,你可以通过以下两种方式实现和Pandas .values 相同的功能,将DataFrame转换为数组:

1. 直接使用.to_numpy()方法

这是最贴近Pandas .values 的操作,直接返回numpy数组,用法简洁高效:

import polars as pl

# 创建Polars DataFrame(无需依赖Pandas)
df_tests_pl = pl.DataFrame({
    'col_a': [1,2,3],
    'col_b': [4,5,6],
    'col_c': [7,8,9]
})

# 转换为完整数组
print(df_tests_pl.to_numpy())
# 输出结果:
# [[1 4 7]
#  [2 5 8]
#  [3 6 9]]

# 仅转换指定列
selected_array = df_tests_pl.select(['col_a', 'col_b']).to_numpy()
print(selected_array)
# 输出结果:
# [[1 4]
#  [2 5]
#  [3 6]]

2. 基于.rows()转换为数组

如果你已经在使用.rows()获取元组列表,可以通过numpy.array()将其转换为数组:

import polars as pl
import numpy as np

df_tests_pl = pl.DataFrame({
    'col_a': [1,2,3],
    'col_b': [4,5,6],
    'col_c': [7,8,9]
})

# 先获取元组列表,再转换为数组
tuple_list = df_tests_pl.select(['col_a', 'col_b']).rows()
result_array = np.array(tuple_list)
print(result_array)
# 输出结果:
# [[1 4]
#  [2 5]
#  [3 6]]

注:你提到的.to_list()方法确实仅适用于Polars Series,DataFrame没有该方法,因此上述两种方式更适配你的需求。

内容的提问来源于stack exchange,提问作者Tonino Fernandez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 16:25:10