Skip to content

Commit

Permalink
add round implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
Miguel Gómez Cofrades committed Dec 4, 2023
1 parent 7de2b7c commit b0d0214
Show file tree
Hide file tree
Showing 3 changed files with 105 additions and 2 deletions.
69 changes: 67 additions & 2 deletions docs/user-guide/advanced/Pandas_API.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -2259,6 +2259,71 @@
"tab.abs(numeric_only=True)"
]
},
{
"cell_type": "markdown",
"id": "499cac52",
"metadata": {},
"source": [
"### Table.round()\n",
"\n",
"```\n",
"Table.round(self, decimals: Union[int, Dict[str, int]] = 0)\n",
"```\n",
"\n",
"Round a Table to a variable number of decimal places.\n",
"\n",
"\n",
"**Parameters:**\n",
"\n",
"| Name | Type | Description | Default |\n",
"| :--------------: | :-----------------: | :------------------------------------------------------------ | :-----: |\n",
"| decimals | int or Dict or list | Number of decimal places to round each column to. If an int is given, round each column to the same number of places. Otherwise dict and list round to variable numbers of places. Column names should be in the keys if decimals is a dict-like, or in the index if decimals is a list. Any columns not included in decimals will be left as is. Elements of decimals which are not columns of the input will be ignored.| 0 |\n",
"\n",
"**Note: functionality for list nyi**\n",
"\n",
"**Returns:**\n",
"\n",
"| Type | Description |\n",
"| :--------: | :--------------------------------------------------------------------------------------- |\n",
"| Table | A Table with the affected columns rounded to the specified number of decimal places. |\n"
]
},
{
"cell_type": "markdown",
"id": "1b629def",
"metadata": {},
"source": [
"If an integer is provided it rounds every float column to set decimals."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "08c182c9",
"metadata": {},
"outputs": [],
"source": [
"tab.round(1)"
]
},
{
"cell_type": "markdown",
"id": "28853fc0",
"metadata": {},
"source": [
"If a dict whose keys are the column names and its values are the decimals to round set column is provided, it will round them accordingly.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "7640df4c",
"metadata": {},
"outputs": [],
"source": [
"tab.round({\"price\": 1, \"traded\": 0})"
]
},
{
"cell_type": "markdown",
"id": "ad57d9cf",
Expand Down Expand Up @@ -2975,7 +3040,7 @@
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
Expand All @@ -2989,7 +3054,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.3"
"version": "3.8.10"
}
},
"nbformat": 4,
Expand Down
22 changes: 22 additions & 0 deletions src/pykx/pandas_api/pandas_meta.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from pykx.pandas_api import api_return
from typing import Union, Dict


def _init(_q):
Expand Down Expand Up @@ -209,6 +210,27 @@ def abs(self, numeric_only=False):
tab = _get_numeric_only_subtable(self)
return q.abs(tab)

@api_return
def round(self, decimals: Union[int, Dict[str, int]] = 0):
tab = self
if 'Keyed' in str(type(tab)):
tab = q('{(keys x) _ 0!x}', tab)

return q("""{[t;d]
generate_ops:{[vdic]
tuples:{flip(2;count[x])#key[x],value[x]}[vdic];
key[vdic]!({(({"F"$.Q.f[y]x}[;x[1]])';x[0])}')tuples};
get_float_cols:{(key[ct]@where 9=value[ct:abs type each first x])};
fcols:get_float_cols[t];
ops:$[-7h=type d;
[$[0=d;
fcols!({(_:';x)}')fcols;
[vdic:fcols!count[fcols]#d;
generate_ops vdic]]];
[vdic:(key[d]i)!value[d]i:where key[d] in fcols;
generate_ops vdic]];
![t;();0b;ops]}""", tab, decimals)

@convert_result
def all(self, axis=0, bool_only=False, skipna=True):
res, cols = preparse_computations(self, axis, skipna, bool_only=bool_only)
Expand Down
16 changes: 16 additions & 0 deletions tests/test_pandas_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -1774,6 +1774,22 @@ def test_pandas_abs(kx, q):
with pytest.raises(kx.QError):
tab.abs()

def test_pandas_round(kx, q):
q_tab = q('([]c1:1.0 .1 .01 .001 .0001 .00001;'
'c2:1.0 1.2 1.02 1.002 1.0002 1.00002;'
'c3:til 6;'
'c4:`a`b`c`d`e`f)')
pd_tab = q_tab.pd()
round_dict = {'c1': 0, 'c2': 2}

assert all(pd_tab.round() == q_tab.round().pd())
assert all(q_tab.round(0).pd() == q_tab.round().pd())
assert all(pd_tab.round(2) == q_tab.round(2).pd())
assert all(pd_tab.round(round_dict) == q_tab.round(round_dict).pd())

round_dict_non_numerical = {'c1': 0, 'c3': 2, 'c4': 2}
assert all(pd_tab.round(round_dict_non_numerical) == q_tab.round(round_dict_non_numerical).pd())


def test_pandas_min(q):
tab = q('([] sym: 100?`foo`bar`baz`qux; price: 250.0f - 100?500.0f; ints: 100 - 100?200)')
Expand Down

0 comments on commit b0d0214

Please sign in to comment.