Ruby meets Python
Python has a few libraries that everybody wants to use. The best known is pandas: think of a spreadsheet you drive with code. You put data into a table, and with one line you sort it, add up a column, keep only some of the rows or count things.
The pycall gem by Kenta Murata lets Ruby use Python libraries as if they were Ruby objects. You write Ruby; pycall hands every call to Python and brings the answer back.
Here in the browser, Python runs as Pyodide – CPython in WebAssembly, right next to our Ruby. It starts loading when you open this lesson (once, about 12 MB). A cell you run before it is ready simply waits.
require "pycall"
pd = PyCall.import_module("pandas")
pd.__version__PyCall.import_module("pandas") is Ruby's way of saying Python's import pandas as pd. What comes back, pd, is a Ruby object that stands for the Python module, and you reach everything in it with a dot. pd.__version__ is a Python string, and it arrives as an ordinary Ruby string.
The pandas documentation shows Python code. A handful of rules translate it to Ruby:
| Python | Ruby with pycall |
|---|---|
import pandas as pd | pd = PyCall.import_module("pandas") |
pd.DataFrame(data) | pd.DataFrame.new(data) |
sort_values("x", ascending=False) | sort_values("x", ascending: false) |
True False None | true false nil |
{"a": [1, 2]} | {"a" => [1, 2]} |
df["price"] | df["price"] the same |
Now our first table. In pandas a table is called a DataFrame, and you can build one from a Ruby hash:
breakfast = pd.DataFrame.new({
"food" => ["Bacon", "Eggs", "Toast", "Coffee"],
"price" => [4.5, 2.0, 1.5, 3.0],
"quantity" => [2, 3, 2, 4]
})Every key of the hash becomes a column, and its array fills that column from top to bottom – so all arrays need the same length. The numbers 0 to 3 on the left are the index: pandas numbers the rows for you. What you see below the cell is pandas' own table, just like in a Python notebook.
Square brackets with a column's name give you that one column:
breakfast["price"]A single column is called a Series: the values, with their row numbers next to them. A wrong name such as breakfast["prise"] makes Python raise a KeyError, and it reaches Ruby as a PyCall::PyError.
You compute with a whole Series at once – no loop needed. * multiplies two columns row by row (4.5 × 2, 2.0 × 3, …), and []= stores the result as a new column:
breakfast["total"] = breakfast["price"] * breakfast["quantity"]
breakfast.sort_values("total", ascending: false)In plain Ruby, with an array of hashes, that would be a loop: rows.each { |r| r[:total] = r[:price] * r[:quantity] }. pandas does the whole column in one go.
sort_values("total", ascending: false) sorts by that column, the largest first. Python writes ascending=False; pycall turns Ruby's keyword arguments into Python's.
When the answer is a single value, you get a Ruby value back:
total = breakfast["total"].sum
puts "Total: $#{total}"
total.classsum adds up the column, and the result is a plain Ruby Float – you can round it, format it or compare it like any other number.
Picking rows takes two steps. First, ask every row a question:
pricey = breakfast["price"] > 2The answer is a Series of True and False, one per row: is this price above 2? Put that Series into square brackets, and pandas keeps only the rows marked True:
breakfast[pricey]Bacon and coffee are left. To get back to Ruby, take the column, turn it into a Python list with tolist, and that into a Ruby array with to_a:
breakfast[pricey]["food"].tolist.to_aFrom here on it's all Ruby again: map, join, each – whatever you like.
Where pandas really shines is counting and grouping. Here are the orders of a small diner – which table ordered what:
orders = pd.DataFrame.new({
"table" => [1, 2, 1, 3, 2, 1],
"food" => ["Bacon", "Eggs", "Coffee", "Bacon", "Bacon", "Toast"]
})
orders["food"].value_countsvalue_counts counts how often each value appears, the most frequent first: bacon was ordered three times. Now per table. Read the next line from left to right: groupby("table") puts the rows of each table into a group, ["food"] takes the food column, and count counts within each group:
orders.groupby("table")["food"].countTable 1 ordered three things, table 2 two, table 3 one. In plain Ruby, with an array of hashes, you would write:
orders.group_by { |o| o[:table] }.transform_values(&:size)pandas does it for a whole table, and instead of count you can use sum, mean (the average), max and many more.
You need Python with pandas (pip install pandas) and the gem: gem install pycall. This lesson's code then runs unchanged – pycall loads the Python library into your Ruby program, and the PYTHON environment variable decides which Python it uses. Here in the browser a small bridge plays that part and talks to Pyodide through JavaScript; it cannot pass Ruby blocks to Python as functions.
For small tables, Ruby's own tools – CSV and hashes – go a long way. pycall pays off when Python has something Ruby lacks: pandas, scikit-learn, matplotlib. pandas and numpy come under the BSD licence, Pyodide under the Mozilla Public License 2.0.
groupby to add up price per guest, and turn the result into a Ruby hash spending, such as {"Isi" => …, "Kaz" => …}.require "pycall"
pd = PyCall.import_module("pandas")
bill = pd.DataFrame.new({
"guest" => ["Kaz", "Isi", "Kaz", "Isi", "Kaz"],
"price" => [4.5, 2.0, 3.0, 4.5, 3.5]
})
# spending = ... (a Ruby hash: guest => total)