如何将Polars Dataframe转为Python列表及单列转Polars Series
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()withas_series=Falseand extract values, or transpose the DataFrame first before usingto_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

