Skip to content
This repository was archived by the owner on Feb 2, 2024. It is now read-only.
39 changes: 39 additions & 0 deletions examples/dataframe/dataframe_at.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# *****************************************************************************
# Copyright (c) 2020, Intel Corporation All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# *****************************************************************************


import pandas as pd
from numba import njit


@njit
def dataframe_at():
df = pd.DataFrame({'A': [1.0, 2.0, 3.0, 1.0], 'B': [4, 5, 6, 7], 'C': ['a', 'b', 'c', 'd']})

return df.at[1, 'C'] # ['b']


print(dataframe_at())
113 changes: 112 additions & 1 deletion sdc/datatypes/hpat_pandas_dataframe_functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@

from pandas.core.indexing import IndexingError

from numba import types
from numba import types, prange
from numba.special import literally
from numba.typed import List, Dict
from numba.errors import TypingError
Expand Down Expand Up @@ -1759,13 +1759,73 @@ def _df_getitem_unicode_idx_impl(self, idx):
ty_checker.raise_exc(idx, expected_types, 'idx')


def df_getitem_tuple_at_codegen(self, row, col):
"""
Example of generated implementation:
def _df_getitem_tuple_at_impl(self, idx):
row, _ = idx
check_row = False
for i in prange(len(self._dataframe.index)):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we actually need this? Wouldn't it be checked in Series.at?

if self._dataframe.index[i] == row:
check_row = True
if check_row:
data = self._dataframe._data[2]
res_data = pandas.Series(data, index=self._dataframe.index)
return res_data.at[row]
raise IndexingError('Index is out of bounds for axis')

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For which axis?

"""
func_lines = ['def _df_getitem_tuple_at_impl(self, idx):']
for i in range(len(self.columns)):
if self.columns[i] == col:
func_lines += [
' row, _ = idx',
' check_row = False',
' for i in prange(len(self._dataframe.index)):',
' if self._dataframe.index[i] == row:',
' check_row = True',
' if check_row:',
f' data = self._dataframe._data[{i}]',
' res_data = pandas.Series(data, index=self._dataframe.index)',
' return res_data.at[row]',
' raise IndexingError("Index is out of bounds for axis")'
]
break
else:
raise IndexingError('Index is out of bounds for axis')

func_text = '\n'.join(func_lines)

global_vars = {'pandas': pandas,
'prange': prange,
'IndexingError': IndexingError}

return func_text, global_vars


def gen_df_getitem_tuple_at_impl(self, row, col):
func_text, global_vars = df_getitem_tuple_at_codegen(self, row, col)
loc_vars = {}
exec(func_text, global_vars, loc_vars)
_reduce_impl = loc_vars['_df_getitem_tuple_at_impl']

return _reduce_impl


@sdc_overload(operator.getitem)
def sdc_pandas_dataframe_accessor_getitem(self, idx):
if not isinstance(self, DataFrameGetitemAccessorType):
return None

accessor = self.accessor.literal_value

if accessor == 'at':
if isinstance(idx, types.Tuple) and isinstance(idx[1], types.Literal):
row = idx[0]

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Need to check that first item in idx is of the same type as index and second item is string

col = idx[1].literal_value

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't we add limitation about column supported only to be literal?

return gen_df_getitem_tuple_at_impl(self.dataframe, row, col)

raise TypingError('Operator getitem(). The index must be a row and literal column. Given: {}'.format(idx))

if accessor == 'iat':
if isinstance(idx, types.Tuple) and isinstance(idx[1], types.Literal):
col = idx[1].literal_value
Expand Down Expand Up @@ -1836,6 +1896,57 @@ def sdc_pandas_dataframe_iat_impl(self):
return sdc_pandas_dataframe_iat_impl


@sdc_overload_attribute(DataFrameType, 'at')
def sdc_pandas_dataframe_at(self):
"""
Intel Scalable Dataframe Compiler User Guide
********************************************

Limitations
-----------
- Parameter ``column`` in ``idx`` must be a literal value.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add limitation, that at always returns Series


Pandas API: pandas.DataFrame.at

Examples
--------
.. literalinclude:: ../../../examples/dataframe/dataframe_at.py
:language: python
:lines: 28-
:caption: Access a single value for a row/column label pair.
:name: ex_dataframe_at

.. command-output:: python ./dataframe/dataframe_at.py
:cwd: ../../../examples

.. seealso::

:ref:`DataFrame.iat <pandas.DataFrame.iat>`
Access a single value for a row/column pair by integer position.

:ref:`DataFrame.loc <pandas.DataFrame.loc>`
Access a group of rows and columns by label(s).

:ref:`Series.at <pandas.Series.at>`
Access a single value using a label.

Intel Scalable Dataframe Compiler Developer Guide
*************************************************
Pandas DataFrame method :meth:`pandas.DataFrame.at` implementation.

.. only:: developer
Test: python -m sdc.runtests -k sdc.tests.test_dataframe.TestDataFrame.test_df_at*
"""

ty_checker = TypeChecker('Attribute at().')
ty_checker.check(self, DataFrameType)

def sdc_pandas_dataframe_at_impl(self):
return dataframe_getitem_accessor_init(self, 'at')

return sdc_pandas_dataframe_at_impl


@sdc_overload_method(DataFrameType, 'pct_change')
def pct_change_overload(df, periods=1, fill_method='pad', limit=None, freq=None):
"""
Expand Down
27 changes: 27 additions & 0 deletions sdc/tests/test_dataframe.py
Original file line number Diff line number Diff line change
Expand Up @@ -1100,6 +1100,33 @@ def test_impl(df):
msg = 'Index is out of bounds for axis'
self.assertIn(msg, str(raises.exception))

def test_df_at(self):
def test_impl(df, n):
return df.at[n, 'C']

sdc_func = sdc.jit(test_impl)
idx = [3, 4, 1, 2, 0]
n_cases = [0, 2]
df = pd.DataFrame({"A": [3.2, 4.4, 7.0, 3.3, 1.0],
"B": [3, 4, 1, 0, 222],
"C": ['a', 'dd', 'c', '12', 'ddf']}, index=idx)
for n in n_cases:
self.assertEqual(sdc_func(df, n), test_impl(df, n))

def test_df_at_value_error(self):
def test_impl(df):
return df.at[1, 'D']
sdc_func = sdc.jit(test_impl)
idx = [3, 4, 1, 2, 0]
df = pd.DataFrame({"A": [3.2, 4.4, 7.0, 3.3, 1.0],
"B": [3, 4, 1, 0, 222],
"C": [3, 4, 2, 6, 1]}, index=idx)

with self.assertRaises(TypingError) as raises:
sdc_func(df)
msg = 'Index is out of bounds for axis'
self.assertIn(msg, str(raises.exception))

def test_df_head(self):
def get_func(n):
def impl(a):
Expand Down