ankane/ruby-polars

(Question) Good way to create a hash from two columns?

Closed this issue · 2 comments

kojix2 commented

Thank you for providing the Polars library for Ruby.

This is a simple question, and I know it is the kind of question you would ask in a forum, but I have no other place to ask it, so let me ask it here.

For example, when you get the following data frame,

shape: (5, 2)
┌────────┬────────┐
│ name   ┆ food   │
│ ---    ┆ ---    │
│ str    ┆ str    │
╞════════╪════════╡
│ monkey ┆ banana │
│ horse  ┆ carrot │
│ cat    ┆ milk   │
│ rabbit ┆ carrot │
│ cow    ┆ grass  │
└────────┴────────┘
require 'polars'

animal_food = Polars::DataFrame.new(
  {
    name: %w[monkey horse cat rabbit cow],
    food: %w[banana carrot milk carrot grass]
  }
)

often want to convert it into a hash.

{"monkey" => "banana",
 "horse"  => "carrot",
 "cat"    => "milk",
 "rabbit" => "carrot",
 "cow"    => "grass"}

I wrote this snippet like this,

pp animal_food['name'].to_a.zip(animal_food['food'].to_a).to_h

but I think it doesn't look very cool. If anyone has a better way to write it, could you please let me know?

3.2.0 :001 > animal_food = Polars::DataFrame.new(
3.2.0 :002 >   {
3.2.0 :003 >     name: %w[monkey horse cat rabbit cow],
3.2.0 :004 >     food: %w[banana carrot milk carrot grass]
3.2.0 :005 >   }
3.2.0 :006 > )
 => 
shape: (5, 2)
... 
3.2.0 :007 > animal_food.rows.to_h
 => {"monkey"=>"banana", "horse"=>"carrot", "cat"=>"milk", "rabbit"=>"carrot", "cow"=>"grass"} 
3.2.0 :008 > 
kojix2 commented

@topofocus Perfect. Thanks! 💯