&[1, 2, 3, 4, 5,6], "2" => &[2, 3, 4, 5, 6, 6]); println!("{}"," /> &[1, 2, 3, 4, 5,6], "2" => &[2, 3, 4, 5, 6, 6]); println!("{}"," /> &[1, 2, 3, 4, 5,6], "2" => &[2, 3, 4, 5, 6, 6]); println!("{}","/>

How to get number of columns in a rust-polars DataFrame

73 Views Asked by At

I have the following dataframe

use polars::prelude::*;

fn main() {
    let df = df!("1" => &[1, 2, 3, 4, 5,6], "2" => &[2, 3, 4, 5, 6, 6]);
    println!("{}", df.unwrap());
}

shape: (6, 2)
┌─────┬─────┐
│ 1   ┆ 2   │
│ --- ┆ --- │
│ i32 ┆ i32 │
╞═════╪═════╡
│ 1   ┆ 2   │
│ 2   ┆ 3   │
│ 3   ┆ 4   │
│ 4   ┆ 5   │
│ 5   ┆ 6   │
│ 6   ┆ 6   │
└─────┴─────┘

How can I retrieve the number of columns in df(In this case it's 2)?

1

There are 1 best solutions below

0
user459872 On BEST ANSWER

There are multiple ways to do this.

  1. The easiest way is to call the .width method which returns the number of columns.
  2. You can call the get_column_names() to get the column names as vector, and then call it's len method.
  3. You can also call the .shape method to get the tuple (no_of_rows, no_of_columns) and access the second element.
use polars::prelude::*;

fn main() {
    let df = df!("1" => &[1, 2, 3, 4, 5,6], "2" => &[2, 3, 4, 5, 6, 6]).unwrap();
    println!("No of columns: {}", df.width());
    println!("No of columns: {}", df.get_column_names().len());
    println!("No of columns: {}", df.shape().1)
    // This will print: 
    // No of columns: 2
    // No of columns: 2
    // No of columns: 2
}