3

Perhaps a dumb question but..

In R data.table, if I want to get the mean of a column, I can reference a column vector like foo$x and calculate its mean with something like mean(foo$x).

I can't figure out how to do this operation with Python datatable. For example,

# imports
import numpy as np
import datatable as dt
from datatable import f

# make datatable
np.random.seed(1)
foo = dt.Frame({'x': np.random.randn(10)})

# calculate mean
dt.mean(foo.x)  # error
dt.mean(foo[:, f.x])  # Expr:mean(<Frame [10 rows x 1 col]>) ???
foo[:, dt.mean(f.x)][0, 0]  # -0.0971

While the last statement technically works, it seems overly cumbersome as it first returns a 1x1 datatable from which I extract the only value. The fundamental issue I'm struggling with is, I don't understand if column vectors exists in python datatable and/or how to reference them.

In short, is there a simpler way to calculate the mean of a column with python datable?

Pasha
  • 6,298
  • 2
  • 22
  • 34
Ben
  • 20,038
  • 30
  • 112
  • 189

1 Answers1

4

Generalizing slightly, let's start with a Frame that has several columns:

>>> import numpy as np
>>> from datatable import f, dt
>>> np.random.seed(1)
>>> foo = dt.Frame(x=np.random.randn(10), y=np.random.randn(10))
>>> foo
            x           y
--  ---------  ----------
 0   1.62435    1.46211  
 1  -0.611756  -2.06014  
 2  -0.528172  -0.322417 
 3  -1.07297   -0.384054 
 4   0.865408   1.13377  
 5  -2.30154   -1.09989  
 6   1.74481   -0.172428 
 7  -0.761207  -0.877858 
 8   0.319039   0.0422137
 9  -0.24937    0.582815 

[10 rows x 2 columns]

First, the simple .mean() method will return a 1x2 Frame with per-column means:

>>> foo.mean()
             x          y
--  ----------  ---------
 0  -0.0971409  -0.169588

[1 row x 2 columns]

If you want the mean of a single column you have to select that column from foo first: foo[:, f.y], or foo[:, 'y'], or simply foo['y']:

>>> foo['y'].mean()
            y
--  ---------
 0  -0.169588

[1 row x 1 column]

Now, if you want to have a number instead of a 1x1 frame, you can either use the [0, 0] selector, or call function .mean1() instead:

>>> foo['y'].mean()[0, 0]
-0.1695883821153589

>>> foo['y'].mean1()
-0.1695883821153589
Pasha
  • 6,298
  • 2
  • 22
  • 34