Skip to content
This repository has been archived by the owner on Nov 29, 2023. It is now read-only.

Commit

Permalink
[DataFrame] Implemented __getattr__ (ray-project#1753)
Browse files Browse the repository at this point in the history
* __getattr__ accesses columns

* Added test
  • Loading branch information
pschafhalter authored and devin-petersohn committed Apr 10, 2018
1 parent e82bea4 commit 405b05d
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
16 changes: 16 additions & 0 deletions python/ray/dataframe/dataframe.py
Original file line number Diff line number Diff line change
Expand Up @@ -2992,6 +2992,22 @@ def _getitem_indiv_col(self, key, part):
lambda df: df.__getitem__(index),
self._col_partitions[part])

def __getattr__(self, key):
"""After regular attribute access, looks up the name in the columns
Args:
key (str): Attribute name.
Returns:
The value of the attribute.
"""
try:
return object.__getattribute__(self, key)
except AttributeError as e:
if key in self.columns:
return self[key]
raise e

def __setitem__(self, key, value):
raise NotImplementedError(
"To contribute to Pandas on Ray, please visit "
Expand Down
17 changes: 17 additions & 0 deletions python/ray/dataframe/test/test_dataframe.py
Original file line number Diff line number Diff line change
Expand Up @@ -2763,6 +2763,23 @@ def test___getitem__(ray_df, pd_df):
assert pd_col.equals(ray_col)


def test___getattr__():
df = create_test_dataframe()

col = df.__getattr__("col1")
assert isinstance(col, pd.Series)

col = getattr(df, "col1")
assert isinstance(col, pd.Series)

col = df.col1
assert isinstance(col, pd.Series)

# Check that lookup in column doesn't override other attributes
df2 = df.rename(index=str, columns={"col5": "columns"})
assert isinstance(df2.columns, pd.Index)


def test___setitem__():
ray_df = create_test_dataframe()

Expand Down

0 comments on commit 405b05d

Please sign in to comment.