github.com/apache/beam/sdks/v2@v2.48.2/python/apache_beam/examples/snippets/transforms/aggregation/mean.py (about)

     1  # coding=utf-8
     2  #
     3  # Licensed to the Apache Software Foundation (ASF) under one or more
     4  # contributor license agreements.  See the NOTICE file distributed with
     5  # this work for additional information regarding copyright ownership.
     6  # The ASF licenses this file to You under the Apache License, Version 2.0
     7  # (the "License"); you may not use this file except in compliance with
     8  # the License.  You may obtain a copy of the License at
     9  #
    10  #    http://www.apache.org/licenses/LICENSE-2.0
    11  #
    12  # Unless required by applicable law or agreed to in writing, software
    13  # distributed under the License is distributed on an "AS IS" BASIS,
    14  # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    15  # See the License for the specific language governing permissions and
    16  # limitations under the License.
    17  #
    18  
    19  # pytype: skip-file
    20  
    21  
    22  def mean_globally(test=None):
    23    # [START mean_globally]
    24    import apache_beam as beam
    25  
    26    with beam.Pipeline() as pipeline:
    27      mean_element = (
    28          pipeline
    29          | 'Create numbers' >> beam.Create([3, 4, 1, 2])
    30          | 'Get mean value' >> beam.combiners.Mean.Globally()
    31          | beam.Map(print))
    32      # [END mean_globally]
    33      if test:
    34        test(mean_element)
    35  
    36  
    37  def mean_per_key(test=None):
    38    # [START mean_per_key]
    39    import apache_beam as beam
    40  
    41    with beam.Pipeline() as pipeline:
    42      elements_with_mean_value_per_key = (
    43          pipeline
    44          | 'Create produce' >> beam.Create([
    45              ('🥕', 3),
    46              ('🥕', 2),
    47              ('🍆', 1),
    48              ('🍅', 4),
    49              ('🍅', 5),
    50              ('🍅', 3),
    51          ])
    52          | 'Get mean value per key' >> beam.combiners.Mean.PerKey()
    53          | beam.Map(print))
    54      # [END mean_per_key]
    55      if test:
    56        test(elements_with_mean_value_per_key)