Skip to content

Instantly share code, notes, and snippets.

@RutgerK
Created June 23, 2014 09:37
Show Gist options
  • Save RutgerK/69b60da73f464900310a to your computer and use it in GitHub Desktop.
Save RutgerK/69b60da73f464900310a to your computer and use it in GitHub Desktop.
Numpy average
{
"metadata": {
"name": "",
"signature": "sha256:9a6d28783b094aa4e16922511a41be446d3492debc80d94c9eb804de6d92c4d8"
},
"nbformat": 3,
"nbformat_minor": 0,
"worksheets": [
{
"cells": [
{
"cell_type": "code",
"collapsed": false,
"input": [
"import numpy as np\n",
"np.version.full_version"
],
"language": "python",
"metadata": {},
"outputs": [
{
"metadata": {},
"output_type": "pyout",
"prompt_number": 1,
"text": [
"'1.8.1'"
]
}
],
"prompt_number": 1
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"a = np.ones(1000000, dtype=np.int16) * 500\n",
"\n",
"mask = np.random.randint(0, 2, a.size)\n",
"b = np.ma.masked_array(a, mask=mask)\n",
"\n",
"np.average(b), np.mean(b), np.ma.average(b), np.ma.mean(b)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"metadata": {},
"output_type": "pyout",
"prompt_number": 2,
"text": [
"(500.0, 500.0, 500.0, 500.0)"
]
}
],
"prompt_number": 2
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"a = np.ones(10000000, dtype=np.int16) * 500\n",
"\n",
"mask = np.random.randint(0, 2, a.size)\n",
"b = np.ma.masked_array(a, mask=mask)\n",
"\n",
"np.average(b), np.mean(b), np.ma.average(b), np.ma.mean(b)\n"
],
"language": "python",
"metadata": {},
"outputs": [
{
"metadata": {},
"output_type": "pyout",
"prompt_number": 3,
"text": [
"(500.0, -359.51019673027423, -359.51019673027423, -359.51019673027423)"
]
}
],
"prompt_number": 3
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"b = b.astype(np.float64)\n",
"np.average(b), np.mean(b), np.ma.average(b), np.ma.mean(b)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"metadata": {},
"output_type": "pyout",
"prompt_number": 4,
"text": [
"(500.0, 500.0, 500.0, 500.0)"
]
}
],
"prompt_number": 4
}
],
"metadata": {}
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment