beam-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From GitBox <...@apache.org>
Subject [GitHub] [beam] TheNeuralBit commented on a change in pull request #10757: Starting implementation of dataframes for Beam
Date Fri, 06 Mar 2020 20:43:43 GMT
TheNeuralBit commented on a change in pull request #10757: Starting implementation of dataframes
for Beam
URL: https://github.com/apache/beam/pull/10757#discussion_r383553704
 
 

 ##########
 File path: sdks/python/apache_beam/dataframe/frames.py
 ##########
 @@ -0,0 +1,208 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import pandas as pd
+
+from apache_beam.dataframe import expressions
+from apache_beam.dataframe import frame_base
+
+
+@frame_base.DeferredFrame._register_for(pd.Series)
+class DeferredSeries(frame_base.DeferredFrame):
+  pass
+
+
+for base in ['add', 'sub', 'mul', 'div', 'truediv', 'floordiv', 'mod', 'pow']:
+  for p in ['%s', 'r%s', '__%s__', '__r%s__']:
+    # TODO: non-trivial level?
+    name = p % base
+    setattr(
+        DeferredSeries,
+        name,
+        frame_base._elementwise_method(name, restrictions={'level': None}))
+  setattr(
+      DeferredSeries,
+      '__i%s__' % base,
+      frame_base._elementwise_method('__i%s__' % base, inplace=True))
+for name in ['__lt__', '__le__', '__gt__', '__ge__', '__eq__', '__ne__']:
+  setattr(DeferredSeries, name, frame_base._elementwise_method(name))
+for name in ['apply', 'map', 'transform']:
+  setattr(DeferredSeries, name, frame_base._elementwise_method(name))
+
+
+@frame_base.DeferredFrame._register_for(pd.DataFrame)
+class DeferredDataFrame(frame_base.DeferredFrame):
+  def groupby(self, cols):
+    # TODO: what happens to the existing index?
+    # We set the columns to index as we have a notion of being partitioned by
+    # index, but not partitioned by an arbitrary subset of columns.
+    return DeferredGroupBy(
+        expressions.ComputedExpression(
+            'groupbyindex',
+            lambda df: df.groupby(level=list(range(df.index.nlevels))),
+            [self.set_index(cols)._expr],
+            requires_partition_by_index=True,
+            preserves_partition_by_index=True))
+
+  def __getattr__(self, name):
+    # Column attribute access.
+    if name in self._expr.proxy().columns:
+      return self[name]
+    else:
+      return super(DeferredDataFrame, self).__getattr__(name)
+
+  def __getitem__(self, key):
+    if key in self._expr.proxy().columns:
+      return self._elementwise(lambda df: df[key], 'get_column')
+    else:
+      raise NotImplementedError(key)
+
+  def __setitem__(self, key, value):
+    if isinstance(key, str):
+      # yapf: disable
+      return self._elementwise(
+          lambda df, key, value: df.__setitem__(key, value),
+          'set_column',
+          (key, value),
+          inplace=True)
+    else:
+      raise NotImplementedError(key)
+
+  def set_index(self, keys, **kwargs):
+    if isinstance(keys, str):
+      keys = [keys]
+    else:
+      keys = keys
+    if not set(keys).issubset(self._expr.proxy().columns):
+      raise NotImplementedError(keys)
+    return self._elementwise(
+        lambda df: df.set_index(keys, **kwargs),
+        'set_index',
+        inplace=kwargs.get('inplace', False))
+
+  def at(self, *args, **kwargs):
+    raise NotImplementedError()
+
+  @property
+  def loc(self):
+    return _DeferredLoc(self)
+
+
+class DeferredGroupBy(frame_base.DeferredFrame):
+  def agg(self, fn):
+    if not callable(fn):
+      raise NotImplementedError(fn)
+    return DeferredDataFrame(
+        expressions.ComputedExpression(
+            'agg',
+            lambda df: df.agg(fn), [self._expr],
+            requires_partition_by_index=True,
+            preserves_partition_by_index=True))
+
+
+def _liftable_agg(meth):
+  name, func = frame_base.name_and_func(meth)
+
+  def wrapper(self, *args, **kargs):
+    assert isinstance(self, DeferredGroupBy)
+    ungrouped = self._expr.args()[0]
+    pre_agg = expressions.ComputedExpression(
+        'pre_combine_' + name,
+        lambda df: func(df.groupby(level=list(range(df.index.nlevels)))),
+        [ungrouped],
+        requires_partition_by_index=False,
+        preserves_partition_by_index=True)
+    post_agg = expressions.ComputedExpression(
+        'post_combine_' + name,
+        lambda df: func(df.groupby(level=list(range(df.index.nlevels)))),
+        [pre_agg],
+        requires_partition_by_index=True,
+        preserves_partition_by_index=True)
+    return frame_base.DeferredFrame.wrap(post_agg)
+
+  return wrapper
+
+
+def _unliftable_agg(meth):
+  name, func = frame_base.name_and_func(meth)
+
+  def wrapper(self, *args, **kargs):
+    assert isinstance(self, DeferredGroupBy)
+    ungrouped = self._expr.args()[0]
+    post_agg = expressions.ComputedExpression(
+        name,
+        lambda df: func(df.groupby(level=list(range(df.index.nlevels)))),
+        [ungrouped],
+        requires_partition_by_index=True,
+        preserves_partition_by_index=True)
+    return frame_base.DeferredFrame.wrap(post_agg)
+
+  return wrapper
+
+
+for meth in ['all', 'any', 'max', 'min', 'prod', 'size', 'sum']:
+  setattr(DeferredGroupBy, meth, _liftable_agg(meth))
+for meth in ['mean', 'median', 'std', 'var']:
+  setattr(DeferredGroupBy, meth, _unliftable_agg(meth))
 
 Review comment:
   These lists could be constants like `UNLIFTABLE_AGGREGATIONS` and `LIFTABLE_AGGREGATIONS`
(similar for series operations above), to make this more self-documenting.

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

Mime
View raw message