Built with Tutify.io

    AIStudyLabs

    How to Select First Column of Polars DataFrame

    How to Select First Column of Polars DataFrame

    In Polars, selecting the first column refers to extracting the column located at position 0 in the DataFrame. This can be done using either the column’s name or by indexing based on its position. The first column typically represents the leftmost column in the table. You can retrieve it as a Series, which is a one-dimensional structure, or as a DataFrame, which retains a two-dimensional format even for a single column. The choice between the two depends on how you intend to use the data. In this article, I will demonstrate how to select first column of polars DataFrame.

    Key Points–

    <a id="h-usage-of-select-first-column-of-polars-dataframe"></a>

    Usage of Select First Column of Polars DataFrame

    Selecting the first column as a DataFrame in Polars means extracting only that column from the original DataFrame while retaining its 2-dimensional structure. Instead of converting it to a 1-dimensional Series, you get a new DataFrame containing just the first column, preserving the tabular format.

    To run some examples of how to select the first column of a Polars DataFrame, let’s create a Polars DataFrame.

    
    import polars as pl
    
    technologies= {
        'Courses':["Spark","PySpark","Hadoop","Python","Pandas"],
        'Fees' :[22000,25000,23000,24000,26000],
        'Duration':['30days','50days','35days', '40days','55days'],
        'Discount':[1000,2300,1000,1200,2500]
              }
    df = pl.DataFrame(technologies)
    print("Original DataFrame:\n", df)
    

    Yields below output.

    To select the first column as a DataFrame in Polars, use the select() method with the column's name. You can dynamically specify the first column by combining df.columns[0] with the pl.col() function.

    
    # Using select() with the first column name
    df2 = df.select(df.columns[0])
    print("First column as DataFrame:\n", df2)
    
    # Using select() with the first column name
    df2 = df.select(pl.col(df.columns[0]))
    print("First column as DataFrame:\n", df2)
    

    Here,

    <a id="h-using-df-columns-0-with-square-brackets"></a>

    Using df.columns[0] with Square Brackets

    If you want to select the first column as a Polars DataFrame, use df.select(df.columns[0]) with square brackets. To choose the first column as a Series, use df[df.columns[0]] with square brackets.

    
    # Using df.columns[0] with square brackets
    df2 = df[df.columns[0]]
    print("First column as DataFrame:\n", df2)
    
    # Output:
    # First column as DataFrame:
    # shape: (5,)
    # Series: 'Courses' [str]
    # [
    #	"Spark"
    #	"PySpark"
    #	"Hadoop"
    #	"Python"
    #	"Pandas"
    # ]
    

    Here,

    <a id="h-using-df-0-position-based-selection"></a>

    Using df[:, 0] (Position-Based Selection)

    You can use NumPy-style position-based slicing to select the first column by its position and retrieve it as a Series.

    
    # Select first column as Series 
    # Using position
    df2 = df[:, 0]
    print(df2)
    
    # Output:
    # shape: (5,)
    # Series: 'Courses' [str]
    # [
    #	"Spark"
    #	"PySpark"
    #	"Hadoop"
    #	"Python"
    #	"Pandas"
    # ]
    

    Here,

    <a id="h-using-select-with-integer-slicing"></a>

    Using select() with Integer Slicing

    You might expect to use select() with integer slicing to get the first column as a polars DataFrame; however, select() does not support position-based indexing like iloc in pandas. Instead, it requires column names or expressions, not integer positions.

    
    # Select first column using slicing
    df2 = df.select(df.columns[:1])
    print(df2)
    
    # Select first column using integer slicing
    df2 = df.select(df.columns[0:1])
    print(df2)
    
    # Output:
    # shape: (5, 1)
    ┌─────────┐
    │ Courses │
    │ ---     │
    │ str     │
    ╞═════════╡
    │ Spark   │
    │ PySpark │
    │ Hadoop  │
    │ Python  │
    │ Pandas  │
    └─────────┘
    

    Here,

    <a id="h-using-get-column-with-column-name"></a>

    Using get_column() with Column Name

    You can use the get_column() method with the column name to select a single column as a polars Series. This is a straightforward way to retrieve a column when you want it in 1D format.

    
    # Get first column as Series using .get_column()
    df2 = df.get_column(df.columns[0])
    print(df2)
    
    # Output:
    # shape: (5,)
    # Series: 'Courses' [str]
    # [
    #	"Spark"
    #	"PySpark"
    #	"Hadoop"
    #	"Python"
    #	"Pandas"
    # ]
    

    Here,

    <a id="h-conclusion"></a>

    Conclusion

    In summary, when selecting the first column in Polars, it's important to choose the right method based on your desired output format. To get a Series, you can use position-based indexing like df[:, 0]. To get a DataFrame, use the select() method with the column name or a column expression. Unlike pandas, Polars does not support integer-based slicing directly in select(), so column names or expressions are required to maintain clarity and consistency.

    Happy Learning!!

    <a id="h-related-articles"></a>

    Related Articles

    <a id="h-references"></a>

    References