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

如何将Polars Dataframe转为Python列表及单列转Polars Series

Polars DataFrame Conversion Solutions

Convert Polars DataFrame to Python List

Polars provides native methods to convert a DataFrame to a Python list, with options for row-wise or column-wise output:

  • Row-wise list: Call to_list() directly on the DataFrame. This returns a list of lists, where each inner list represents the values of a single row.

    import polars as pl
    
    df = pl.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
    row_based_list = df.to_list()
    # Result: [[1, 4], [2, 5], [3, 6]]
    
  • Column-wise list: To get each column as a separate list, you can either use to_dict() with as_series=False and extract values, or transpose the DataFrame first before using to_list():

    # Using to_dict
    column_dict = df.to_dict(as_series=False)
    column_based_list = list(column_dict.values())
    # Result: [[1, 2, 3], [4, 5, 6]]
    
    # Using transpose
    column_based_list = df.transpose().to_list()
    # Same result as above
    

Convert Single-Column DataFrame to Polars Series

For a DataFrame with exactly one column, use these Polars-native methods (pandas commands like squeeze() won't work here):

  • Use to_series(): This method directly converts the single-column DataFrame into a Series.

    single_col_df = pl.DataFrame({"a": [1, 2, 3]})
    series = single_col_df.to_series()
    # Output: shape: (3,)
    # Series: 'a' [i64]
    # [
    #  1
    #  2
    #  3
    # ]
    
  • Select the column directly: Accessing the column by name or index returns a Series immediately.

    # By column name
    series = single_col_df["a"]
    
    # By column index (0 for the first column)
    series = single_col_df.to_series(0)
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 15:03:26