From bb1549ae4d8a248d2de472f4d07a12ab60848eff Mon Sep 17 00:00:00 2001 From: Oscar Nydza <33619748+nipsn@users.noreply.github.com> Date: Tue, 13 Feb 2024 08:57:11 +0100 Subject: [PATCH] Add kurt and sem functions (#32) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Added implementation of kurt function (#23) * Added implementation of sem function (#22) * Refactored kurt and sem functions --------- Co-authored-by: Miguel Gómez Co-authored-by: Francisco Tórtola Vivo --- docs/user-guide/advanced/Pandas_API.ipynb | 187 ++++++++++++++++++++++ src/pykx/pandas_api/pandas_meta.py | 47 ++++++ tests/test_pandas_api.py | 153 ++++++++++++++++++ 3 files changed, 387 insertions(+) diff --git a/docs/user-guide/advanced/Pandas_API.ipynb b/docs/user-guide/advanced/Pandas_API.ipynb index a9443bf..ddc3980 100644 --- a/docs/user-guide/advanced/Pandas_API.ipynb +++ b/docs/user-guide/advanced/Pandas_API.ipynb @@ -436,6 +436,91 @@ "tab.mean(axis=1)" ] }, + { + "cell_type": "markdown", + "id": "fe565b65-fbf2-47ba-a26e-791d09fd4f55", + "metadata": {}, + "source": [ + "### Table.kurt()\n", + "\n", + "```\n", + "Table.kurt(axis=0, skipna=True, numeric_only=False)\n", + "```\n", + "\n", + "Return unbiased kurtosis over requested axis. Kurtosis obtained using Fisher’s definition of kurtosis (kurtosis of normal == 0.0). Normalized by N-1.\n", + "\n", + "\n", + "**Parameters:**\n", + "\n", + "| Name | Type | Description | Default |\n", + "| :----------: | :--: | :------------------------------------------------------------------------------- | :-----: |\n", + "| axis | int | Axis for the function to be applied on. 0 is columns, 1 is rows. | 0 |\n", + "| skipna | bool | not yet implemented | True |\n", + "| numeric_only | bool | Only use columns of the table that are of a numeric data type. | False |\n", + "\n", + "**Returns:**\n", + "\n", + "| Type | Description |\n", + "| :--------: | :--------------------------------------------------------------------------------------- |\n", + "| Dictionary | Map of columns and their yielded kurtosis values |" + ] + }, + { + "cell_type": "markdown", + "id": "e6069cac-d260-4f80-9688-3d1ec273cd22", + "metadata": {}, + "source": [ + "**Examples:**\n", + "\n", + "Calculate the kurt across the columns of a table" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "4219c826-a84b-4722-9847-372d3837acdb", + "metadata": {}, + "outputs": [], + "source": [ + "tab = kx.Table(data=\n", + " {\n", + " 'a': [1, 2, 2, 4],\n", + " 'b': [1, 2, 6, 7],\n", + " 'c': [7, 8, 9, 10],\n", + " 'd': [7, 11, 14, 14]\n", + " }\n", + ")\n", + "tab" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "437ab485-bf73-4209-b63e-aa0d1bfa5d58", + "metadata": {}, + "outputs": [], + "source": [ + "tab.kurt()" + ] + }, + { + "cell_type": "markdown", + "id": "ea3e1cf6-2304-4061-a846-1cbc0572ea9d", + "metadata": {}, + "source": [ + "Calculate the kurtosis across the rows of a table" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "63312e8b-76f0-46eb-b4d7-b2213561c86e", + "metadata": {}, + "outputs": [], + "source": [ + "tab.kurt(axis=1)" + ] + }, { "cell_type": "markdown", "id": "7bf853c5", @@ -646,6 +731,108 @@ "tab.mode(dropna=False)" ] }, + { + "cell_type": "markdown", + "id": "b248fef1", + "metadata": {}, + "source": [ + "### Table.sem()\n", + "\n", + "```\n", + "Table.sem(axis=0, skipna=True, numeric_only=False, ddof=0)\n", + "```\n", + "Return unbiased standard error of the mean over requested axis. Normalized by N-1 by default. This can be changed using the ddof argument\n", + "\n", + "**Parameters:**\n", + "\n", + "| Name | Type | Description | Default |\n", + "| :----------: | :--: | :------------------------------------------------------------------------------- | :-----: |\n", + "| axis | int | The axis to calculate the sum across 0 is columns, 1 is rows. | 0 |\n", + "| skipna | bool | not yet implemented | True |\n", + "| numeric_only | bool | Only use columns of the table that are of a numeric data type. | False |\n", + "| ddof | int | Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. | 1 |\n", + "\n", + "**Returns:**\n", + "\n", + "| Type | Description |\n", + "| :----------------: | :------------------------------------------------------------------- |\n", + "| Dictionary | The sem across each row / column with the key corresponding to the row number or column name. |" + ] + }, + { + "cell_type": "markdown", + "id": "71bd1d6f", + "metadata": {}, + "source": [ + "**Examples**\n", + "\n", + "Calculate the sem across the columns of a table" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "350c2b7c", + "metadata": {}, + "outputs": [], + "source": [ + "tab = kx.Table(data=\n", + " {\n", + " 'a': [1, 2, 2, 4],\n", + " 'b': [1, 2, 6, 7],\n", + " 'c': [7, 8, 9, 10],\n", + " 'd': [7, 11, 14, 14],\n", + " }\n", + " )\n", + "tab" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b89307e9", + "metadata": {}, + "outputs": [], + "source": [ + "tab.sem()" + ] + }, + { + "cell_type": "markdown", + "id": "6933f01f", + "metadata": {}, + "source": [ + "Calculate the sem across the rows of a table" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "3edd3feb", + "metadata": {}, + "outputs": [], + "source": [ + "tab.sem(axis=1)" + ] + }, + { + "cell_type": "markdown", + "id": "ae7afe5a", + "metadata": {}, + "source": [ + "Calculate sem accross columns with ddof=0:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "de626961", + "metadata": {}, + "outputs": [], + "source": [ + "tab.sem(ddof=0)" + ] + }, { "cell_type": "markdown", "id": "7e2813b4", diff --git a/src/pykx/pandas_api/pandas_meta.py b/src/pykx/pandas_api/pandas_meta.py index 31bd263..eccd654 100644 --- a/src/pykx/pandas_api/pandas_meta.py +++ b/src/pykx/pandas_api/pandas_meta.py @@ -154,6 +154,32 @@ def mean(self, axis: int = 0, numeric_only: bool = False): tab ) + @api_return + def kurt(self, axis: int = 0, numeric_only: bool = False): + tab = self + if 'Keyed' in str(type(tab)): + tab = q.value(tab) + if numeric_only: + tab = _get_numeric_only_subtable(tab) + + axis_keys = q('{[axis;tab] $[0~axis;cols;`$string til count @] tab}', axis, tab) + + return q( + '''{[tab;axis;axis_keys] + tab:$[0~axis;(::);flip] value flip tab; + kurt:{[x] + res: x - avg x; + n: count x; + m2: sum rsq: res xexp 2; + m4: sum rsq xexp 2; + adj: 3 * xexp[n - 1;2] % (n - 2) * (n - 3); + num: n * (n + 1) * (n - 1) * m4; + den: (n - 2) * (n - 3) * m2 xexp 2; + (num % den) - adj}; + axis_keys!kurt each tab} + ''', tab, axis, axis_keys + ) + @api_return def median(self, axis: int = 0, numeric_only: bool = False): tab = self @@ -203,6 +229,27 @@ def mode(self, axis: int = 0, numeric_only: bool = False, dropna: bool = True): tab ) + @api_return + def sem(self, axis: int = 0, ddof: int = 1, numeric_only: bool = False): + tab = self + if 'Keyed' in str(type(tab)): + tab = q.value(tab) + if numeric_only: + tab = _get_numeric_only_subtable(tab) + + axis_keys = q('{[axis;tab] $[0~axis;cols;`$string til count @] tab}', axis, tab) + + if ddof == len(tab): + return q('{x!count[x]#0n}', axis_keys) + + return q( + '''{[tab;axis;ddof;axis_keys] + tab:$[0~axis;(::);flip] value flip tab; + d:{dev[x] % sqrt count[x] - y}[;ddof]; + axis_keys!d each tab} + ''', tab, axis, ddof, axis_keys + ) + @api_return def abs(self, numeric_only=False): tab = self diff --git a/tests/test_pandas_api.py b/tests/test_pandas_api.py index 467a89c..7b06d65 100644 --- a/tests/test_pandas_api.py +++ b/tests/test_pandas_api.py @@ -1489,6 +1489,86 @@ def test_df_sample(kx, q): t.sample(ignore_index=True) +def test_sem(kx, q): + df = pd.DataFrame( + { + 'a': [1, 2, 2, 4], + 'b': [1, 2, 6, 7], + 'c': [7, 8, 9, 10], + 'd': [7, 11, 14, 14] + } + ) + precision = 1e-16 + tab = kx.toq(df) + p_m = df.sem() + q_m = tab.sem() + assert all([p_m[c] == pytest.approx(q_m[c].py(), precision) + for c in q.key(q_m).py()]) + + p_m = df.sem(axis=1) + q_m = tab.sem(axis=1) + assert all([p_m[c] == pytest.approx(q_m[q('{`$string x}', c)].py(), precision) + for c in range(len(q.cols(tab)))]) + + p_m = df.sem(ddof=0) + q_m = tab.sem(ddof=0) + assert all([p_m[c] == pytest.approx(q_m[c].py(), precision) + for c in q.key(q_m).py()]) + + p_m = df.sem(ddof=4) + q_m = tab.sem(ddof=4) + assert all([np.isnan(p_m[c]) & np.isnan(q_m[c].py()) + for c in q.key(q_m).py()]) + + q['tab'] = kx.toq(df) + tab = q('1!`idx xcols update idx: til count tab from tab') + p_m = df.sem() + q_m = tab.sem() + assert all([p_m[c] == pytest.approx(q_m[c].py(), precision) + for c in q.key(q_m).py()]) + + p_m = df.sem(axis=1) + q_m = tab.sem(axis=1) + assert all([p_m[c] == pytest.approx(q_m[q('{`$string x}', c)].py(), precision) + for c in range(len(q.cols(tab)) - 1)]) + + df = pd.DataFrame( + { + 'a': [1, 2, 2, 4], + 'b': [1, 2, 6, 7], + 'c': [7, 8, 9, 10], + 'd': ['foo', 'bar', 'baz', 'qux'] + } + ) + tab = kx.toq(df) + p_m = df.sem(numeric_only=True) + q_m = tab.sem(numeric_only=True) + assert all([p_m[c] == pytest.approx(q_m[c].py(), precision) + for c in q.key(q_m).py()]) + + p_m = df.sem(axis=1, numeric_only=True) + q_m = tab.sem(axis=1, numeric_only=True) + assert all([p_m[c] == pytest.approx(q_m[q('{`$string x}', c)].py(), precision) + for c in range(len(q.cols(tab)))]) + + with pytest.raises(kx.QError): + q_m = tab.sem() + with pytest.raises(kx.QError): + q_m = tab.sem(axis=1) + + df = pd.DataFrame({'a': [1]}) + tab = kx.toq(df) + p_m = df.sem() + q_m = tab.sem() + assert all([np.isnan(p_m[c]) & np.isnan(q_m[c].py()) + for c in q.key(q_m).py()]) + + p_m = df.sem(ddof=0) + q_m = tab.sem(ddof=0) + assert all([p_m[c] == pytest.approx(q_m[c].py(), precision) + for c in q.key(q_m).py()]) + + def test_mean(kx, q): df = pd.DataFrame( { @@ -1543,6 +1623,79 @@ def test_mean(kx, q): q_m = tab.mean(axis=1) +def test_kurt(kx, q): + df = pd.DataFrame( + { + 'a': [1, 2, 2, 4], + 'b': [1, 2, 6, 7], + 'c': [7, 8, 9, 10], + 'd': [7, 11, 14, 14] + } + ) + tab = kx.toq(df) + p_m = df.kurt() + q_m = tab.kurt() + for c in q.key(q_m).py(): + assert p_m[c] == q_m[c].py() + p_m = df.kurt(axis=1) + q_m = tab.kurt(axis=1) + for c in range(len(q.cols(tab))): + assert p_m[c] == q_m[q('{`$string x}', c)].py() + + q['tab'] = kx.toq(df) + tab = q('1!`idx xcols update idx: til count tab from tab') + p_m = df.kurt() + q_m = tab.kurt() + for c in q.key(q_m).py(): + assert p_m[c] == q_m[c].py() + p_m = df.kurt(axis=1) + q_m = tab.kurt(axis=1) + for c in range(len(q.cols(tab)) - 1): + assert p_m[c] == q_m[q('{`$string x}', c)].py() + + df = pd.DataFrame( + { + 'a': [1, 2, 2, 4], + 'b': [1, 2, 6, 7], + 'c': [7, 8, 9, 10], + 'd': ['foo', 'bar', 'baz', 'qux'] + } + ) + tab = kx.toq(df) + p_m = df.kurt(numeric_only=True) + q_m = tab.kurt(numeric_only=True) + for c in q.key(q_m).py(): + assert p_m[c] == q_m[c].py() + p_m = df.kurt(axis=1, numeric_only=True) + q_m = tab.kurt(axis=1, numeric_only=True) + for c in range(len(q.cols(tab))): + assert np.isnan(p_m[c]) & np.isnan(q_m[q('{`$string x}', c)].py()) + + df = pd.DataFrame( + { + 'a': [1, 2, 2, 4], + 'b': [1, 2, 6, 7], + 'c': [7, 8, 9, 10], + 'd': [11, 12, 13, 14], + 'e': ['foo', 'bar', 'baz', 'qux'] + } + ) + tab = kx.toq(df) + p_m = df.kurt(numeric_only=True) + q_m = tab.kurt(numeric_only=True) + for c in q.key(q_m).py(): + assert p_m[c] == q_m[c].py() + p_m = df.kurt(axis=1, numeric_only=True) + q_m = tab.kurt(axis=1, numeric_only=True) + for c in range(len(q.cols(tab)) - 1): + assert p_m[c] == q_m[q('{`$string x}', c)].py() + + with pytest.raises(kx.QError): + q_m = tab.kurt() + with pytest.raises(kx.QError): + q_m = tab.kurt(axis=1) + + def test_median(kx, q): df = pd.DataFrame( {