partition stringclasses 3 values | func_name stringlengths 1 134 | docstring stringlengths 1 46.9k | path stringlengths 4 223 | original_string stringlengths 75 104k | code stringlengths 75 104k | docstring_tokens listlengths 1 1.97k | repo stringlengths 7 55 | language stringclasses 1 value | url stringlengths 87 315 | code_tokens listlengths 19 28.4k | sha stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|
train | _check_dataframe_localize_timestamps | Convert timezone aware timestamps to timezone-naive in the specified timezone or local timezone
:param pdf: pandas.DataFrame
:param timezone: the timezone to convert. if None then use local timezone
:return pandas.DataFrame where any timezone aware columns have been converted to tz-naive | python/pyspark/sql/types.py | def _check_dataframe_localize_timestamps(pdf, timezone):
"""
Convert timezone aware timestamps to timezone-naive in the specified timezone or local timezone
:param pdf: pandas.DataFrame
:param timezone: the timezone to convert. if None then use local timezone
:return pandas.DataFrame where any timezone aware columns have been converted to tz-naive
"""
from pyspark.sql.utils import require_minimum_pandas_version
require_minimum_pandas_version()
for column, series in pdf.iteritems():
pdf[column] = _check_series_localize_timestamps(series, timezone)
return pdf | def _check_dataframe_localize_timestamps(pdf, timezone):
"""
Convert timezone aware timestamps to timezone-naive in the specified timezone or local timezone
:param pdf: pandas.DataFrame
:param timezone: the timezone to convert. if None then use local timezone
:return pandas.DataFrame where any timezone aware columns have been converted to tz-naive
"""
from pyspark.sql.utils import require_minimum_pandas_version
require_minimum_pandas_version()
for column, series in pdf.iteritems():
pdf[column] = _check_series_localize_timestamps(series, timezone)
return pdf | [
"Convert",
"timezone",
"aware",
"timestamps",
"to",
"timezone",
"-",
"naive",
"in",
"the",
"specified",
"timezone",
"or",
"local",
"timezone"
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/sql/types.py#L1723-L1736 | [
"def",
"_check_dataframe_localize_timestamps",
"(",
"pdf",
",",
"timezone",
")",
":",
"from",
"pyspark",
".",
"sql",
".",
"utils",
"import",
"require_minimum_pandas_version",
"require_minimum_pandas_version",
"(",
")",
"for",
"column",
",",
"series",
"in",
"pdf",
".",
"iteritems",
"(",
")",
":",
"pdf",
"[",
"column",
"]",
"=",
"_check_series_localize_timestamps",
"(",
"series",
",",
"timezone",
")",
"return",
"pdf"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | _check_series_convert_timestamps_internal | Convert a tz-naive timestamp in the specified timezone or local timezone to UTC normalized for
Spark internal storage
:param s: a pandas.Series
:param timezone: the timezone to convert. if None then use local timezone
:return pandas.Series where if it is a timestamp, has been UTC normalized without a time zone | python/pyspark/sql/types.py | def _check_series_convert_timestamps_internal(s, timezone):
"""
Convert a tz-naive timestamp in the specified timezone or local timezone to UTC normalized for
Spark internal storage
:param s: a pandas.Series
:param timezone: the timezone to convert. if None then use local timezone
:return pandas.Series where if it is a timestamp, has been UTC normalized without a time zone
"""
from pyspark.sql.utils import require_minimum_pandas_version
require_minimum_pandas_version()
from pandas.api.types import is_datetime64_dtype, is_datetime64tz_dtype
# TODO: handle nested timestamps, such as ArrayType(TimestampType())?
if is_datetime64_dtype(s.dtype):
# When tz_localize a tz-naive timestamp, the result is ambiguous if the tz-naive
# timestamp is during the hour when the clock is adjusted backward during due to
# daylight saving time (dst).
# E.g., for America/New_York, the clock is adjusted backward on 2015-11-01 2:00 to
# 2015-11-01 1:00 from dst-time to standard time, and therefore, when tz_localize
# a tz-naive timestamp 2015-11-01 1:30 with America/New_York timezone, it can be either
# dst time (2015-01-01 1:30-0400) or standard time (2015-11-01 1:30-0500).
#
# Here we explicit choose to use standard time. This matches the default behavior of
# pytz.
#
# Here are some code to help understand this behavior:
# >>> import datetime
# >>> import pandas as pd
# >>> import pytz
# >>>
# >>> t = datetime.datetime(2015, 11, 1, 1, 30)
# >>> ts = pd.Series([t])
# >>> tz = pytz.timezone('America/New_York')
# >>>
# >>> ts.dt.tz_localize(tz, ambiguous=True)
# 0 2015-11-01 01:30:00-04:00
# dtype: datetime64[ns, America/New_York]
# >>>
# >>> ts.dt.tz_localize(tz, ambiguous=False)
# 0 2015-11-01 01:30:00-05:00
# dtype: datetime64[ns, America/New_York]
# >>>
# >>> str(tz.localize(t))
# '2015-11-01 01:30:00-05:00'
tz = timezone or _get_local_timezone()
return s.dt.tz_localize(tz, ambiguous=False).dt.tz_convert('UTC')
elif is_datetime64tz_dtype(s.dtype):
return s.dt.tz_convert('UTC')
else:
return s | def _check_series_convert_timestamps_internal(s, timezone):
"""
Convert a tz-naive timestamp in the specified timezone or local timezone to UTC normalized for
Spark internal storage
:param s: a pandas.Series
:param timezone: the timezone to convert. if None then use local timezone
:return pandas.Series where if it is a timestamp, has been UTC normalized without a time zone
"""
from pyspark.sql.utils import require_minimum_pandas_version
require_minimum_pandas_version()
from pandas.api.types import is_datetime64_dtype, is_datetime64tz_dtype
# TODO: handle nested timestamps, such as ArrayType(TimestampType())?
if is_datetime64_dtype(s.dtype):
# When tz_localize a tz-naive timestamp, the result is ambiguous if the tz-naive
# timestamp is during the hour when the clock is adjusted backward during due to
# daylight saving time (dst).
# E.g., for America/New_York, the clock is adjusted backward on 2015-11-01 2:00 to
# 2015-11-01 1:00 from dst-time to standard time, and therefore, when tz_localize
# a tz-naive timestamp 2015-11-01 1:30 with America/New_York timezone, it can be either
# dst time (2015-01-01 1:30-0400) or standard time (2015-11-01 1:30-0500).
#
# Here we explicit choose to use standard time. This matches the default behavior of
# pytz.
#
# Here are some code to help understand this behavior:
# >>> import datetime
# >>> import pandas as pd
# >>> import pytz
# >>>
# >>> t = datetime.datetime(2015, 11, 1, 1, 30)
# >>> ts = pd.Series([t])
# >>> tz = pytz.timezone('America/New_York')
# >>>
# >>> ts.dt.tz_localize(tz, ambiguous=True)
# 0 2015-11-01 01:30:00-04:00
# dtype: datetime64[ns, America/New_York]
# >>>
# >>> ts.dt.tz_localize(tz, ambiguous=False)
# 0 2015-11-01 01:30:00-05:00
# dtype: datetime64[ns, America/New_York]
# >>>
# >>> str(tz.localize(t))
# '2015-11-01 01:30:00-05:00'
tz = timezone or _get_local_timezone()
return s.dt.tz_localize(tz, ambiguous=False).dt.tz_convert('UTC')
elif is_datetime64tz_dtype(s.dtype):
return s.dt.tz_convert('UTC')
else:
return s | [
"Convert",
"a",
"tz",
"-",
"naive",
"timestamp",
"in",
"the",
"specified",
"timezone",
"or",
"local",
"timezone",
"to",
"UTC",
"normalized",
"for",
"Spark",
"internal",
"storage"
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/sql/types.py#L1739-L1789 | [
"def",
"_check_series_convert_timestamps_internal",
"(",
"s",
",",
"timezone",
")",
":",
"from",
"pyspark",
".",
"sql",
".",
"utils",
"import",
"require_minimum_pandas_version",
"require_minimum_pandas_version",
"(",
")",
"from",
"pandas",
".",
"api",
".",
"types",
"import",
"is_datetime64_dtype",
",",
"is_datetime64tz_dtype",
"# TODO: handle nested timestamps, such as ArrayType(TimestampType())?",
"if",
"is_datetime64_dtype",
"(",
"s",
".",
"dtype",
")",
":",
"# When tz_localize a tz-naive timestamp, the result is ambiguous if the tz-naive",
"# timestamp is during the hour when the clock is adjusted backward during due to",
"# daylight saving time (dst).",
"# E.g., for America/New_York, the clock is adjusted backward on 2015-11-01 2:00 to",
"# 2015-11-01 1:00 from dst-time to standard time, and therefore, when tz_localize",
"# a tz-naive timestamp 2015-11-01 1:30 with America/New_York timezone, it can be either",
"# dst time (2015-01-01 1:30-0400) or standard time (2015-11-01 1:30-0500).",
"#",
"# Here we explicit choose to use standard time. This matches the default behavior of",
"# pytz.",
"#",
"# Here are some code to help understand this behavior:",
"# >>> import datetime",
"# >>> import pandas as pd",
"# >>> import pytz",
"# >>>",
"# >>> t = datetime.datetime(2015, 11, 1, 1, 30)",
"# >>> ts = pd.Series([t])",
"# >>> tz = pytz.timezone('America/New_York')",
"# >>>",
"# >>> ts.dt.tz_localize(tz, ambiguous=True)",
"# 0 2015-11-01 01:30:00-04:00",
"# dtype: datetime64[ns, America/New_York]",
"# >>>",
"# >>> ts.dt.tz_localize(tz, ambiguous=False)",
"# 0 2015-11-01 01:30:00-05:00",
"# dtype: datetime64[ns, America/New_York]",
"# >>>",
"# >>> str(tz.localize(t))",
"# '2015-11-01 01:30:00-05:00'",
"tz",
"=",
"timezone",
"or",
"_get_local_timezone",
"(",
")",
"return",
"s",
".",
"dt",
".",
"tz_localize",
"(",
"tz",
",",
"ambiguous",
"=",
"False",
")",
".",
"dt",
".",
"tz_convert",
"(",
"'UTC'",
")",
"elif",
"is_datetime64tz_dtype",
"(",
"s",
".",
"dtype",
")",
":",
"return",
"s",
".",
"dt",
".",
"tz_convert",
"(",
"'UTC'",
")",
"else",
":",
"return",
"s"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | _check_series_convert_timestamps_localize | Convert timestamp to timezone-naive in the specified timezone or local timezone
:param s: a pandas.Series
:param from_timezone: the timezone to convert from. if None then use local timezone
:param to_timezone: the timezone to convert to. if None then use local timezone
:return pandas.Series where if it is a timestamp, has been converted to tz-naive | python/pyspark/sql/types.py | def _check_series_convert_timestamps_localize(s, from_timezone, to_timezone):
"""
Convert timestamp to timezone-naive in the specified timezone or local timezone
:param s: a pandas.Series
:param from_timezone: the timezone to convert from. if None then use local timezone
:param to_timezone: the timezone to convert to. if None then use local timezone
:return pandas.Series where if it is a timestamp, has been converted to tz-naive
"""
from pyspark.sql.utils import require_minimum_pandas_version
require_minimum_pandas_version()
import pandas as pd
from pandas.api.types import is_datetime64tz_dtype, is_datetime64_dtype
from_tz = from_timezone or _get_local_timezone()
to_tz = to_timezone or _get_local_timezone()
# TODO: handle nested timestamps, such as ArrayType(TimestampType())?
if is_datetime64tz_dtype(s.dtype):
return s.dt.tz_convert(to_tz).dt.tz_localize(None)
elif is_datetime64_dtype(s.dtype) and from_tz != to_tz:
# `s.dt.tz_localize('tzlocal()')` doesn't work properly when including NaT.
return s.apply(
lambda ts: ts.tz_localize(from_tz, ambiguous=False).tz_convert(to_tz).tz_localize(None)
if ts is not pd.NaT else pd.NaT)
else:
return s | def _check_series_convert_timestamps_localize(s, from_timezone, to_timezone):
"""
Convert timestamp to timezone-naive in the specified timezone or local timezone
:param s: a pandas.Series
:param from_timezone: the timezone to convert from. if None then use local timezone
:param to_timezone: the timezone to convert to. if None then use local timezone
:return pandas.Series where if it is a timestamp, has been converted to tz-naive
"""
from pyspark.sql.utils import require_minimum_pandas_version
require_minimum_pandas_version()
import pandas as pd
from pandas.api.types import is_datetime64tz_dtype, is_datetime64_dtype
from_tz = from_timezone or _get_local_timezone()
to_tz = to_timezone or _get_local_timezone()
# TODO: handle nested timestamps, such as ArrayType(TimestampType())?
if is_datetime64tz_dtype(s.dtype):
return s.dt.tz_convert(to_tz).dt.tz_localize(None)
elif is_datetime64_dtype(s.dtype) and from_tz != to_tz:
# `s.dt.tz_localize('tzlocal()')` doesn't work properly when including NaT.
return s.apply(
lambda ts: ts.tz_localize(from_tz, ambiguous=False).tz_convert(to_tz).tz_localize(None)
if ts is not pd.NaT else pd.NaT)
else:
return s | [
"Convert",
"timestamp",
"to",
"timezone",
"-",
"naive",
"in",
"the",
"specified",
"timezone",
"or",
"local",
"timezone"
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/sql/types.py#L1792-L1817 | [
"def",
"_check_series_convert_timestamps_localize",
"(",
"s",
",",
"from_timezone",
",",
"to_timezone",
")",
":",
"from",
"pyspark",
".",
"sql",
".",
"utils",
"import",
"require_minimum_pandas_version",
"require_minimum_pandas_version",
"(",
")",
"import",
"pandas",
"as",
"pd",
"from",
"pandas",
".",
"api",
".",
"types",
"import",
"is_datetime64tz_dtype",
",",
"is_datetime64_dtype",
"from_tz",
"=",
"from_timezone",
"or",
"_get_local_timezone",
"(",
")",
"to_tz",
"=",
"to_timezone",
"or",
"_get_local_timezone",
"(",
")",
"# TODO: handle nested timestamps, such as ArrayType(TimestampType())?",
"if",
"is_datetime64tz_dtype",
"(",
"s",
".",
"dtype",
")",
":",
"return",
"s",
".",
"dt",
".",
"tz_convert",
"(",
"to_tz",
")",
".",
"dt",
".",
"tz_localize",
"(",
"None",
")",
"elif",
"is_datetime64_dtype",
"(",
"s",
".",
"dtype",
")",
"and",
"from_tz",
"!=",
"to_tz",
":",
"# `s.dt.tz_localize('tzlocal()')` doesn't work properly when including NaT.",
"return",
"s",
".",
"apply",
"(",
"lambda",
"ts",
":",
"ts",
".",
"tz_localize",
"(",
"from_tz",
",",
"ambiguous",
"=",
"False",
")",
".",
"tz_convert",
"(",
"to_tz",
")",
".",
"tz_localize",
"(",
"None",
")",
"if",
"ts",
"is",
"not",
"pd",
".",
"NaT",
"else",
"pd",
".",
"NaT",
")",
"else",
":",
"return",
"s"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | StructType.add | Construct a StructType by adding new elements to it to define the schema. The method accepts
either:
a) A single parameter which is a StructField object.
b) Between 2 and 4 parameters as (name, data_type, nullable (optional),
metadata(optional). The data_type parameter may be either a String or a
DataType object.
>>> struct1 = StructType().add("f1", StringType(), True).add("f2", StringType(), True, None)
>>> struct2 = StructType([StructField("f1", StringType(), True), \\
... StructField("f2", StringType(), True, None)])
>>> struct1 == struct2
True
>>> struct1 = StructType().add(StructField("f1", StringType(), True))
>>> struct2 = StructType([StructField("f1", StringType(), True)])
>>> struct1 == struct2
True
>>> struct1 = StructType().add("f1", "string", True)
>>> struct2 = StructType([StructField("f1", StringType(), True)])
>>> struct1 == struct2
True
:param field: Either the name of the field or a StructField object
:param data_type: If present, the DataType of the StructField to create
:param nullable: Whether the field to add should be nullable (default True)
:param metadata: Any additional metadata (default None)
:return: a new updated StructType | python/pyspark/sql/types.py | def add(self, field, data_type=None, nullable=True, metadata=None):
"""
Construct a StructType by adding new elements to it to define the schema. The method accepts
either:
a) A single parameter which is a StructField object.
b) Between 2 and 4 parameters as (name, data_type, nullable (optional),
metadata(optional). The data_type parameter may be either a String or a
DataType object.
>>> struct1 = StructType().add("f1", StringType(), True).add("f2", StringType(), True, None)
>>> struct2 = StructType([StructField("f1", StringType(), True), \\
... StructField("f2", StringType(), True, None)])
>>> struct1 == struct2
True
>>> struct1 = StructType().add(StructField("f1", StringType(), True))
>>> struct2 = StructType([StructField("f1", StringType(), True)])
>>> struct1 == struct2
True
>>> struct1 = StructType().add("f1", "string", True)
>>> struct2 = StructType([StructField("f1", StringType(), True)])
>>> struct1 == struct2
True
:param field: Either the name of the field or a StructField object
:param data_type: If present, the DataType of the StructField to create
:param nullable: Whether the field to add should be nullable (default True)
:param metadata: Any additional metadata (default None)
:return: a new updated StructType
"""
if isinstance(field, StructField):
self.fields.append(field)
self.names.append(field.name)
else:
if isinstance(field, str) and data_type is None:
raise ValueError("Must specify DataType if passing name of struct_field to create.")
if isinstance(data_type, str):
data_type_f = _parse_datatype_json_value(data_type)
else:
data_type_f = data_type
self.fields.append(StructField(field, data_type_f, nullable, metadata))
self.names.append(field)
# Precalculated list of fields that need conversion with fromInternal/toInternal functions
self._needConversion = [f.needConversion() for f in self]
self._needSerializeAnyField = any(self._needConversion)
return self | def add(self, field, data_type=None, nullable=True, metadata=None):
"""
Construct a StructType by adding new elements to it to define the schema. The method accepts
either:
a) A single parameter which is a StructField object.
b) Between 2 and 4 parameters as (name, data_type, nullable (optional),
metadata(optional). The data_type parameter may be either a String or a
DataType object.
>>> struct1 = StructType().add("f1", StringType(), True).add("f2", StringType(), True, None)
>>> struct2 = StructType([StructField("f1", StringType(), True), \\
... StructField("f2", StringType(), True, None)])
>>> struct1 == struct2
True
>>> struct1 = StructType().add(StructField("f1", StringType(), True))
>>> struct2 = StructType([StructField("f1", StringType(), True)])
>>> struct1 == struct2
True
>>> struct1 = StructType().add("f1", "string", True)
>>> struct2 = StructType([StructField("f1", StringType(), True)])
>>> struct1 == struct2
True
:param field: Either the name of the field or a StructField object
:param data_type: If present, the DataType of the StructField to create
:param nullable: Whether the field to add should be nullable (default True)
:param metadata: Any additional metadata (default None)
:return: a new updated StructType
"""
if isinstance(field, StructField):
self.fields.append(field)
self.names.append(field.name)
else:
if isinstance(field, str) and data_type is None:
raise ValueError("Must specify DataType if passing name of struct_field to create.")
if isinstance(data_type, str):
data_type_f = _parse_datatype_json_value(data_type)
else:
data_type_f = data_type
self.fields.append(StructField(field, data_type_f, nullable, metadata))
self.names.append(field)
# Precalculated list of fields that need conversion with fromInternal/toInternal functions
self._needConversion = [f.needConversion() for f in self]
self._needSerializeAnyField = any(self._needConversion)
return self | [
"Construct",
"a",
"StructType",
"by",
"adding",
"new",
"elements",
"to",
"it",
"to",
"define",
"the",
"schema",
".",
"The",
"method",
"accepts",
"either",
":"
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/sql/types.py#L491-L537 | [
"def",
"add",
"(",
"self",
",",
"field",
",",
"data_type",
"=",
"None",
",",
"nullable",
"=",
"True",
",",
"metadata",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"field",
",",
"StructField",
")",
":",
"self",
".",
"fields",
".",
"append",
"(",
"field",
")",
"self",
".",
"names",
".",
"append",
"(",
"field",
".",
"name",
")",
"else",
":",
"if",
"isinstance",
"(",
"field",
",",
"str",
")",
"and",
"data_type",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Must specify DataType if passing name of struct_field to create.\"",
")",
"if",
"isinstance",
"(",
"data_type",
",",
"str",
")",
":",
"data_type_f",
"=",
"_parse_datatype_json_value",
"(",
"data_type",
")",
"else",
":",
"data_type_f",
"=",
"data_type",
"self",
".",
"fields",
".",
"append",
"(",
"StructField",
"(",
"field",
",",
"data_type_f",
",",
"nullable",
",",
"metadata",
")",
")",
"self",
".",
"names",
".",
"append",
"(",
"field",
")",
"# Precalculated list of fields that need conversion with fromInternal/toInternal functions",
"self",
".",
"_needConversion",
"=",
"[",
"f",
".",
"needConversion",
"(",
")",
"for",
"f",
"in",
"self",
"]",
"self",
".",
"_needSerializeAnyField",
"=",
"any",
"(",
"self",
".",
"_needConversion",
")",
"return",
"self"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | UserDefinedType._cachedSqlType | Cache the sqlType() into class, because it's heavy used in `toInternal`. | python/pyspark/sql/types.py | def _cachedSqlType(cls):
"""
Cache the sqlType() into class, because it's heavy used in `toInternal`.
"""
if not hasattr(cls, "_cached_sql_type"):
cls._cached_sql_type = cls.sqlType()
return cls._cached_sql_type | def _cachedSqlType(cls):
"""
Cache the sqlType() into class, because it's heavy used in `toInternal`.
"""
if not hasattr(cls, "_cached_sql_type"):
cls._cached_sql_type = cls.sqlType()
return cls._cached_sql_type | [
"Cache",
"the",
"sqlType",
"()",
"into",
"class",
"because",
"it",
"s",
"heavy",
"used",
"in",
"toInternal",
"."
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/sql/types.py#L675-L681 | [
"def",
"_cachedSqlType",
"(",
"cls",
")",
":",
"if",
"not",
"hasattr",
"(",
"cls",
",",
"\"_cached_sql_type\"",
")",
":",
"cls",
".",
"_cached_sql_type",
"=",
"cls",
".",
"sqlType",
"(",
")",
"return",
"cls",
".",
"_cached_sql_type"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | Row.asDict | Return as an dict
:param recursive: turns the nested Row as dict (default: False).
>>> Row(name="Alice", age=11).asDict() == {'name': 'Alice', 'age': 11}
True
>>> row = Row(key=1, value=Row(name='a', age=2))
>>> row.asDict() == {'key': 1, 'value': Row(age=2, name='a')}
True
>>> row.asDict(True) == {'key': 1, 'value': {'name': 'a', 'age': 2}}
True | python/pyspark/sql/types.py | def asDict(self, recursive=False):
"""
Return as an dict
:param recursive: turns the nested Row as dict (default: False).
>>> Row(name="Alice", age=11).asDict() == {'name': 'Alice', 'age': 11}
True
>>> row = Row(key=1, value=Row(name='a', age=2))
>>> row.asDict() == {'key': 1, 'value': Row(age=2, name='a')}
True
>>> row.asDict(True) == {'key': 1, 'value': {'name': 'a', 'age': 2}}
True
"""
if not hasattr(self, "__fields__"):
raise TypeError("Cannot convert a Row class into dict")
if recursive:
def conv(obj):
if isinstance(obj, Row):
return obj.asDict(True)
elif isinstance(obj, list):
return [conv(o) for o in obj]
elif isinstance(obj, dict):
return dict((k, conv(v)) for k, v in obj.items())
else:
return obj
return dict(zip(self.__fields__, (conv(o) for o in self)))
else:
return dict(zip(self.__fields__, self)) | def asDict(self, recursive=False):
"""
Return as an dict
:param recursive: turns the nested Row as dict (default: False).
>>> Row(name="Alice", age=11).asDict() == {'name': 'Alice', 'age': 11}
True
>>> row = Row(key=1, value=Row(name='a', age=2))
>>> row.asDict() == {'key': 1, 'value': Row(age=2, name='a')}
True
>>> row.asDict(True) == {'key': 1, 'value': {'name': 'a', 'age': 2}}
True
"""
if not hasattr(self, "__fields__"):
raise TypeError("Cannot convert a Row class into dict")
if recursive:
def conv(obj):
if isinstance(obj, Row):
return obj.asDict(True)
elif isinstance(obj, list):
return [conv(o) for o in obj]
elif isinstance(obj, dict):
return dict((k, conv(v)) for k, v in obj.items())
else:
return obj
return dict(zip(self.__fields__, (conv(o) for o in self)))
else:
return dict(zip(self.__fields__, self)) | [
"Return",
"as",
"an",
"dict"
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/sql/types.py#L1463-L1492 | [
"def",
"asDict",
"(",
"self",
",",
"recursive",
"=",
"False",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"\"__fields__\"",
")",
":",
"raise",
"TypeError",
"(",
"\"Cannot convert a Row class into dict\"",
")",
"if",
"recursive",
":",
"def",
"conv",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"Row",
")",
":",
"return",
"obj",
".",
"asDict",
"(",
"True",
")",
"elif",
"isinstance",
"(",
"obj",
",",
"list",
")",
":",
"return",
"[",
"conv",
"(",
"o",
")",
"for",
"o",
"in",
"obj",
"]",
"elif",
"isinstance",
"(",
"obj",
",",
"dict",
")",
":",
"return",
"dict",
"(",
"(",
"k",
",",
"conv",
"(",
"v",
")",
")",
"for",
"k",
",",
"v",
"in",
"obj",
".",
"items",
"(",
")",
")",
"else",
":",
"return",
"obj",
"return",
"dict",
"(",
"zip",
"(",
"self",
".",
"__fields__",
",",
"(",
"conv",
"(",
"o",
")",
"for",
"o",
"in",
"self",
")",
")",
")",
"else",
":",
"return",
"dict",
"(",
"zip",
"(",
"self",
".",
"__fields__",
",",
"self",
")",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | LinearRegressionModel.summary | Gets summary (e.g. residuals, mse, r-squared ) of model on
training set. An exception is thrown if
`trainingSummary is None`. | python/pyspark/ml/regression.py | def summary(self):
"""
Gets summary (e.g. residuals, mse, r-squared ) of model on
training set. An exception is thrown if
`trainingSummary is None`.
"""
if self.hasSummary:
return LinearRegressionTrainingSummary(super(LinearRegressionModel, self).summary)
else:
raise RuntimeError("No training summary available for this %s" %
self.__class__.__name__) | def summary(self):
"""
Gets summary (e.g. residuals, mse, r-squared ) of model on
training set. An exception is thrown if
`trainingSummary is None`.
"""
if self.hasSummary:
return LinearRegressionTrainingSummary(super(LinearRegressionModel, self).summary)
else:
raise RuntimeError("No training summary available for this %s" %
self.__class__.__name__) | [
"Gets",
"summary",
"(",
"e",
".",
"g",
".",
"residuals",
"mse",
"r",
"-",
"squared",
")",
"of",
"model",
"on",
"training",
"set",
".",
"An",
"exception",
"is",
"thrown",
"if",
"trainingSummary",
"is",
"None",
"."
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/ml/regression.py#L198-L208 | [
"def",
"summary",
"(",
"self",
")",
":",
"if",
"self",
".",
"hasSummary",
":",
"return",
"LinearRegressionTrainingSummary",
"(",
"super",
"(",
"LinearRegressionModel",
",",
"self",
")",
".",
"summary",
")",
"else",
":",
"raise",
"RuntimeError",
"(",
"\"No training summary available for this %s\"",
"%",
"self",
".",
"__class__",
".",
"__name__",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | LinearRegressionModel.evaluate | Evaluates the model on a test dataset.
:param dataset:
Test dataset to evaluate model on, where dataset is an
instance of :py:class:`pyspark.sql.DataFrame` | python/pyspark/ml/regression.py | def evaluate(self, dataset):
"""
Evaluates the model on a test dataset.
:param dataset:
Test dataset to evaluate model on, where dataset is an
instance of :py:class:`pyspark.sql.DataFrame`
"""
if not isinstance(dataset, DataFrame):
raise ValueError("dataset must be a DataFrame but got %s." % type(dataset))
java_lr_summary = self._call_java("evaluate", dataset)
return LinearRegressionSummary(java_lr_summary) | def evaluate(self, dataset):
"""
Evaluates the model on a test dataset.
:param dataset:
Test dataset to evaluate model on, where dataset is an
instance of :py:class:`pyspark.sql.DataFrame`
"""
if not isinstance(dataset, DataFrame):
raise ValueError("dataset must be a DataFrame but got %s." % type(dataset))
java_lr_summary = self._call_java("evaluate", dataset)
return LinearRegressionSummary(java_lr_summary) | [
"Evaluates",
"the",
"model",
"on",
"a",
"test",
"dataset",
"."
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/ml/regression.py#L211-L222 | [
"def",
"evaluate",
"(",
"self",
",",
"dataset",
")",
":",
"if",
"not",
"isinstance",
"(",
"dataset",
",",
"DataFrame",
")",
":",
"raise",
"ValueError",
"(",
"\"dataset must be a DataFrame but got %s.\"",
"%",
"type",
"(",
"dataset",
")",
")",
"java_lr_summary",
"=",
"self",
".",
"_call_java",
"(",
"\"evaluate\"",
",",
"dataset",
")",
"return",
"LinearRegressionSummary",
"(",
"java_lr_summary",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | GeneralizedLinearRegressionModel.summary | Gets summary (e.g. residuals, deviance, pValues) of model on
training set. An exception is thrown if
`trainingSummary is None`. | python/pyspark/ml/regression.py | def summary(self):
"""
Gets summary (e.g. residuals, deviance, pValues) of model on
training set. An exception is thrown if
`trainingSummary is None`.
"""
if self.hasSummary:
return GeneralizedLinearRegressionTrainingSummary(
super(GeneralizedLinearRegressionModel, self).summary)
else:
raise RuntimeError("No training summary available for this %s" %
self.__class__.__name__) | def summary(self):
"""
Gets summary (e.g. residuals, deviance, pValues) of model on
training set. An exception is thrown if
`trainingSummary is None`.
"""
if self.hasSummary:
return GeneralizedLinearRegressionTrainingSummary(
super(GeneralizedLinearRegressionModel, self).summary)
else:
raise RuntimeError("No training summary available for this %s" %
self.__class__.__name__) | [
"Gets",
"summary",
"(",
"e",
".",
"g",
".",
"residuals",
"deviance",
"pValues",
")",
"of",
"model",
"on",
"training",
"set",
".",
"An",
"exception",
"is",
"thrown",
"if",
"trainingSummary",
"is",
"None",
"."
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/ml/regression.py#L1679-L1690 | [
"def",
"summary",
"(",
"self",
")",
":",
"if",
"self",
".",
"hasSummary",
":",
"return",
"GeneralizedLinearRegressionTrainingSummary",
"(",
"super",
"(",
"GeneralizedLinearRegressionModel",
",",
"self",
")",
".",
"summary",
")",
"else",
":",
"raise",
"RuntimeError",
"(",
"\"No training summary available for this %s\"",
"%",
"self",
".",
"__class__",
".",
"__name__",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | GeneralizedLinearRegressionModel.evaluate | Evaluates the model on a test dataset.
:param dataset:
Test dataset to evaluate model on, where dataset is an
instance of :py:class:`pyspark.sql.DataFrame` | python/pyspark/ml/regression.py | def evaluate(self, dataset):
"""
Evaluates the model on a test dataset.
:param dataset:
Test dataset to evaluate model on, where dataset is an
instance of :py:class:`pyspark.sql.DataFrame`
"""
if not isinstance(dataset, DataFrame):
raise ValueError("dataset must be a DataFrame but got %s." % type(dataset))
java_glr_summary = self._call_java("evaluate", dataset)
return GeneralizedLinearRegressionSummary(java_glr_summary) | def evaluate(self, dataset):
"""
Evaluates the model on a test dataset.
:param dataset:
Test dataset to evaluate model on, where dataset is an
instance of :py:class:`pyspark.sql.DataFrame`
"""
if not isinstance(dataset, DataFrame):
raise ValueError("dataset must be a DataFrame but got %s." % type(dataset))
java_glr_summary = self._call_java("evaluate", dataset)
return GeneralizedLinearRegressionSummary(java_glr_summary) | [
"Evaluates",
"the",
"model",
"on",
"a",
"test",
"dataset",
"."
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/ml/regression.py#L1693-L1704 | [
"def",
"evaluate",
"(",
"self",
",",
"dataset",
")",
":",
"if",
"not",
"isinstance",
"(",
"dataset",
",",
"DataFrame",
")",
":",
"raise",
"ValueError",
"(",
"\"dataset must be a DataFrame but got %s.\"",
"%",
"type",
"(",
"dataset",
")",
")",
"java_glr_summary",
"=",
"self",
".",
"_call_java",
"(",
"\"evaluate\"",
",",
"dataset",
")",
"return",
"GeneralizedLinearRegressionSummary",
"(",
"java_glr_summary",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | _get_local_dirs | Get all the directories | python/pyspark/shuffle.py | def _get_local_dirs(sub):
""" Get all the directories """
path = os.environ.get("SPARK_LOCAL_DIRS", "/tmp")
dirs = path.split(",")
if len(dirs) > 1:
# different order in different processes and instances
rnd = random.Random(os.getpid() + id(dirs))
random.shuffle(dirs, rnd.random)
return [os.path.join(d, "python", str(os.getpid()), sub) for d in dirs] | def _get_local_dirs(sub):
""" Get all the directories """
path = os.environ.get("SPARK_LOCAL_DIRS", "/tmp")
dirs = path.split(",")
if len(dirs) > 1:
# different order in different processes and instances
rnd = random.Random(os.getpid() + id(dirs))
random.shuffle(dirs, rnd.random)
return [os.path.join(d, "python", str(os.getpid()), sub) for d in dirs] | [
"Get",
"all",
"the",
"directories"
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/shuffle.py#L71-L79 | [
"def",
"_get_local_dirs",
"(",
"sub",
")",
":",
"path",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"\"SPARK_LOCAL_DIRS\"",
",",
"\"/tmp\"",
")",
"dirs",
"=",
"path",
".",
"split",
"(",
"\",\"",
")",
"if",
"len",
"(",
"dirs",
")",
">",
"1",
":",
"# different order in different processes and instances",
"rnd",
"=",
"random",
".",
"Random",
"(",
"os",
".",
"getpid",
"(",
")",
"+",
"id",
"(",
"dirs",
")",
")",
"random",
".",
"shuffle",
"(",
"dirs",
",",
"rnd",
".",
"random",
")",
"return",
"[",
"os",
".",
"path",
".",
"join",
"(",
"d",
",",
"\"python\"",
",",
"str",
"(",
"os",
".",
"getpid",
"(",
")",
")",
",",
"sub",
")",
"for",
"d",
"in",
"dirs",
"]"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | ExternalMerger._get_spill_dir | Choose one directory for spill by number n | python/pyspark/shuffle.py | def _get_spill_dir(self, n):
""" Choose one directory for spill by number n """
return os.path.join(self.localdirs[n % len(self.localdirs)], str(n)) | def _get_spill_dir(self, n):
""" Choose one directory for spill by number n """
return os.path.join(self.localdirs[n % len(self.localdirs)], str(n)) | [
"Choose",
"one",
"directory",
"for",
"spill",
"by",
"number",
"n"
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/shuffle.py#L219-L221 | [
"def",
"_get_spill_dir",
"(",
"self",
",",
"n",
")",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"localdirs",
"[",
"n",
"%",
"len",
"(",
"self",
".",
"localdirs",
")",
"]",
",",
"str",
"(",
"n",
")",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | ExternalMerger.mergeValues | Combine the items by creator and combiner | python/pyspark/shuffle.py | def mergeValues(self, iterator):
""" Combine the items by creator and combiner """
# speedup attribute lookup
creator, comb = self.agg.createCombiner, self.agg.mergeValue
c, data, pdata, hfun, batch = 0, self.data, self.pdata, self._partition, self.batch
limit = self.memory_limit
for k, v in iterator:
d = pdata[hfun(k)] if pdata else data
d[k] = comb(d[k], v) if k in d else creator(v)
c += 1
if c >= batch:
if get_used_memory() >= limit:
self._spill()
limit = self._next_limit()
batch /= 2
c = 0
else:
batch *= 1.5
if get_used_memory() >= limit:
self._spill() | def mergeValues(self, iterator):
""" Combine the items by creator and combiner """
# speedup attribute lookup
creator, comb = self.agg.createCombiner, self.agg.mergeValue
c, data, pdata, hfun, batch = 0, self.data, self.pdata, self._partition, self.batch
limit = self.memory_limit
for k, v in iterator:
d = pdata[hfun(k)] if pdata else data
d[k] = comb(d[k], v) if k in d else creator(v)
c += 1
if c >= batch:
if get_used_memory() >= limit:
self._spill()
limit = self._next_limit()
batch /= 2
c = 0
else:
batch *= 1.5
if get_used_memory() >= limit:
self._spill() | [
"Combine",
"the",
"items",
"by",
"creator",
"and",
"combiner"
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/shuffle.py#L231-L253 | [
"def",
"mergeValues",
"(",
"self",
",",
"iterator",
")",
":",
"# speedup attribute lookup",
"creator",
",",
"comb",
"=",
"self",
".",
"agg",
".",
"createCombiner",
",",
"self",
".",
"agg",
".",
"mergeValue",
"c",
",",
"data",
",",
"pdata",
",",
"hfun",
",",
"batch",
"=",
"0",
",",
"self",
".",
"data",
",",
"self",
".",
"pdata",
",",
"self",
".",
"_partition",
",",
"self",
".",
"batch",
"limit",
"=",
"self",
".",
"memory_limit",
"for",
"k",
",",
"v",
"in",
"iterator",
":",
"d",
"=",
"pdata",
"[",
"hfun",
"(",
"k",
")",
"]",
"if",
"pdata",
"else",
"data",
"d",
"[",
"k",
"]",
"=",
"comb",
"(",
"d",
"[",
"k",
"]",
",",
"v",
")",
"if",
"k",
"in",
"d",
"else",
"creator",
"(",
"v",
")",
"c",
"+=",
"1",
"if",
"c",
">=",
"batch",
":",
"if",
"get_used_memory",
"(",
")",
">=",
"limit",
":",
"self",
".",
"_spill",
"(",
")",
"limit",
"=",
"self",
".",
"_next_limit",
"(",
")",
"batch",
"/=",
"2",
"c",
"=",
"0",
"else",
":",
"batch",
"*=",
"1.5",
"if",
"get_used_memory",
"(",
")",
">=",
"limit",
":",
"self",
".",
"_spill",
"(",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | ExternalMerger.mergeCombiners | Merge (K,V) pair by mergeCombiner | python/pyspark/shuffle.py | def mergeCombiners(self, iterator, limit=None):
""" Merge (K,V) pair by mergeCombiner """
if limit is None:
limit = self.memory_limit
# speedup attribute lookup
comb, hfun, objsize = self.agg.mergeCombiners, self._partition, self._object_size
c, data, pdata, batch = 0, self.data, self.pdata, self.batch
for k, v in iterator:
d = pdata[hfun(k)] if pdata else data
d[k] = comb(d[k], v) if k in d else v
if not limit:
continue
c += objsize(v)
if c > batch:
if get_used_memory() > limit:
self._spill()
limit = self._next_limit()
batch /= 2
c = 0
else:
batch *= 1.5
if limit and get_used_memory() >= limit:
self._spill() | def mergeCombiners(self, iterator, limit=None):
""" Merge (K,V) pair by mergeCombiner """
if limit is None:
limit = self.memory_limit
# speedup attribute lookup
comb, hfun, objsize = self.agg.mergeCombiners, self._partition, self._object_size
c, data, pdata, batch = 0, self.data, self.pdata, self.batch
for k, v in iterator:
d = pdata[hfun(k)] if pdata else data
d[k] = comb(d[k], v) if k in d else v
if not limit:
continue
c += objsize(v)
if c > batch:
if get_used_memory() > limit:
self._spill()
limit = self._next_limit()
batch /= 2
c = 0
else:
batch *= 1.5
if limit and get_used_memory() >= limit:
self._spill() | [
"Merge",
"(",
"K",
"V",
")",
"pair",
"by",
"mergeCombiner"
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/shuffle.py#L265-L289 | [
"def",
"mergeCombiners",
"(",
"self",
",",
"iterator",
",",
"limit",
"=",
"None",
")",
":",
"if",
"limit",
"is",
"None",
":",
"limit",
"=",
"self",
".",
"memory_limit",
"# speedup attribute lookup",
"comb",
",",
"hfun",
",",
"objsize",
"=",
"self",
".",
"agg",
".",
"mergeCombiners",
",",
"self",
".",
"_partition",
",",
"self",
".",
"_object_size",
"c",
",",
"data",
",",
"pdata",
",",
"batch",
"=",
"0",
",",
"self",
".",
"data",
",",
"self",
".",
"pdata",
",",
"self",
".",
"batch",
"for",
"k",
",",
"v",
"in",
"iterator",
":",
"d",
"=",
"pdata",
"[",
"hfun",
"(",
"k",
")",
"]",
"if",
"pdata",
"else",
"data",
"d",
"[",
"k",
"]",
"=",
"comb",
"(",
"d",
"[",
"k",
"]",
",",
"v",
")",
"if",
"k",
"in",
"d",
"else",
"v",
"if",
"not",
"limit",
":",
"continue",
"c",
"+=",
"objsize",
"(",
"v",
")",
"if",
"c",
">",
"batch",
":",
"if",
"get_used_memory",
"(",
")",
">",
"limit",
":",
"self",
".",
"_spill",
"(",
")",
"limit",
"=",
"self",
".",
"_next_limit",
"(",
")",
"batch",
"/=",
"2",
"c",
"=",
"0",
"else",
":",
"batch",
"*=",
"1.5",
"if",
"limit",
"and",
"get_used_memory",
"(",
")",
">=",
"limit",
":",
"self",
".",
"_spill",
"(",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | ExternalMerger._spill | dump already partitioned data into disks.
It will dump the data in batch for better performance. | python/pyspark/shuffle.py | def _spill(self):
"""
dump already partitioned data into disks.
It will dump the data in batch for better performance.
"""
global MemoryBytesSpilled, DiskBytesSpilled
path = self._get_spill_dir(self.spills)
if not os.path.exists(path):
os.makedirs(path)
used_memory = get_used_memory()
if not self.pdata:
# The data has not been partitioned, it will iterator the
# dataset once, write them into different files, has no
# additional memory. It only called when the memory goes
# above limit at the first time.
# open all the files for writing
streams = [open(os.path.join(path, str(i)), 'wb')
for i in range(self.partitions)]
for k, v in self.data.items():
h = self._partition(k)
# put one item in batch, make it compatible with load_stream
# it will increase the memory if dump them in batch
self.serializer.dump_stream([(k, v)], streams[h])
for s in streams:
DiskBytesSpilled += s.tell()
s.close()
self.data.clear()
self.pdata.extend([{} for i in range(self.partitions)])
else:
for i in range(self.partitions):
p = os.path.join(path, str(i))
with open(p, "wb") as f:
# dump items in batch
self.serializer.dump_stream(iter(self.pdata[i].items()), f)
self.pdata[i].clear()
DiskBytesSpilled += os.path.getsize(p)
self.spills += 1
gc.collect() # release the memory as much as possible
MemoryBytesSpilled += max(used_memory - get_used_memory(), 0) << 20 | def _spill(self):
"""
dump already partitioned data into disks.
It will dump the data in batch for better performance.
"""
global MemoryBytesSpilled, DiskBytesSpilled
path = self._get_spill_dir(self.spills)
if not os.path.exists(path):
os.makedirs(path)
used_memory = get_used_memory()
if not self.pdata:
# The data has not been partitioned, it will iterator the
# dataset once, write them into different files, has no
# additional memory. It only called when the memory goes
# above limit at the first time.
# open all the files for writing
streams = [open(os.path.join(path, str(i)), 'wb')
for i in range(self.partitions)]
for k, v in self.data.items():
h = self._partition(k)
# put one item in batch, make it compatible with load_stream
# it will increase the memory if dump them in batch
self.serializer.dump_stream([(k, v)], streams[h])
for s in streams:
DiskBytesSpilled += s.tell()
s.close()
self.data.clear()
self.pdata.extend([{} for i in range(self.partitions)])
else:
for i in range(self.partitions):
p = os.path.join(path, str(i))
with open(p, "wb") as f:
# dump items in batch
self.serializer.dump_stream(iter(self.pdata[i].items()), f)
self.pdata[i].clear()
DiskBytesSpilled += os.path.getsize(p)
self.spills += 1
gc.collect() # release the memory as much as possible
MemoryBytesSpilled += max(used_memory - get_used_memory(), 0) << 20 | [
"dump",
"already",
"partitioned",
"data",
"into",
"disks",
"."
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/shuffle.py#L291-L337 | [
"def",
"_spill",
"(",
"self",
")",
":",
"global",
"MemoryBytesSpilled",
",",
"DiskBytesSpilled",
"path",
"=",
"self",
".",
"_get_spill_dir",
"(",
"self",
".",
"spills",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"os",
".",
"makedirs",
"(",
"path",
")",
"used_memory",
"=",
"get_used_memory",
"(",
")",
"if",
"not",
"self",
".",
"pdata",
":",
"# The data has not been partitioned, it will iterator the",
"# dataset once, write them into different files, has no",
"# additional memory. It only called when the memory goes",
"# above limit at the first time.",
"# open all the files for writing",
"streams",
"=",
"[",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"str",
"(",
"i",
")",
")",
",",
"'wb'",
")",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"partitions",
")",
"]",
"for",
"k",
",",
"v",
"in",
"self",
".",
"data",
".",
"items",
"(",
")",
":",
"h",
"=",
"self",
".",
"_partition",
"(",
"k",
")",
"# put one item in batch, make it compatible with load_stream",
"# it will increase the memory if dump them in batch",
"self",
".",
"serializer",
".",
"dump_stream",
"(",
"[",
"(",
"k",
",",
"v",
")",
"]",
",",
"streams",
"[",
"h",
"]",
")",
"for",
"s",
"in",
"streams",
":",
"DiskBytesSpilled",
"+=",
"s",
".",
"tell",
"(",
")",
"s",
".",
"close",
"(",
")",
"self",
".",
"data",
".",
"clear",
"(",
")",
"self",
".",
"pdata",
".",
"extend",
"(",
"[",
"{",
"}",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"partitions",
")",
"]",
")",
"else",
":",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"partitions",
")",
":",
"p",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"str",
"(",
"i",
")",
")",
"with",
"open",
"(",
"p",
",",
"\"wb\"",
")",
"as",
"f",
":",
"# dump items in batch",
"self",
".",
"serializer",
".",
"dump_stream",
"(",
"iter",
"(",
"self",
".",
"pdata",
"[",
"i",
"]",
".",
"items",
"(",
")",
")",
",",
"f",
")",
"self",
".",
"pdata",
"[",
"i",
"]",
".",
"clear",
"(",
")",
"DiskBytesSpilled",
"+=",
"os",
".",
"path",
".",
"getsize",
"(",
"p",
")",
"self",
".",
"spills",
"+=",
"1",
"gc",
".",
"collect",
"(",
")",
"# release the memory as much as possible",
"MemoryBytesSpilled",
"+=",
"max",
"(",
"used_memory",
"-",
"get_used_memory",
"(",
")",
",",
"0",
")",
"<<",
"20"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | ExternalMerger.items | Return all merged items as iterator | python/pyspark/shuffle.py | def items(self):
""" Return all merged items as iterator """
if not self.pdata and not self.spills:
return iter(self.data.items())
return self._external_items() | def items(self):
""" Return all merged items as iterator """
if not self.pdata and not self.spills:
return iter(self.data.items())
return self._external_items() | [
"Return",
"all",
"merged",
"items",
"as",
"iterator"
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/shuffle.py#L339-L343 | [
"def",
"items",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"pdata",
"and",
"not",
"self",
".",
"spills",
":",
"return",
"iter",
"(",
"self",
".",
"data",
".",
"items",
"(",
")",
")",
"return",
"self",
".",
"_external_items",
"(",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | ExternalMerger._external_items | Return all partitioned items as iterator | python/pyspark/shuffle.py | def _external_items(self):
""" Return all partitioned items as iterator """
assert not self.data
if any(self.pdata):
self._spill()
# disable partitioning and spilling when merge combiners from disk
self.pdata = []
try:
for i in range(self.partitions):
for v in self._merged_items(i):
yield v
self.data.clear()
# remove the merged partition
for j in range(self.spills):
path = self._get_spill_dir(j)
os.remove(os.path.join(path, str(i)))
finally:
self._cleanup() | def _external_items(self):
""" Return all partitioned items as iterator """
assert not self.data
if any(self.pdata):
self._spill()
# disable partitioning and spilling when merge combiners from disk
self.pdata = []
try:
for i in range(self.partitions):
for v in self._merged_items(i):
yield v
self.data.clear()
# remove the merged partition
for j in range(self.spills):
path = self._get_spill_dir(j)
os.remove(os.path.join(path, str(i)))
finally:
self._cleanup() | [
"Return",
"all",
"partitioned",
"items",
"as",
"iterator"
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/shuffle.py#L345-L364 | [
"def",
"_external_items",
"(",
"self",
")",
":",
"assert",
"not",
"self",
".",
"data",
"if",
"any",
"(",
"self",
".",
"pdata",
")",
":",
"self",
".",
"_spill",
"(",
")",
"# disable partitioning and spilling when merge combiners from disk",
"self",
".",
"pdata",
"=",
"[",
"]",
"try",
":",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"partitions",
")",
":",
"for",
"v",
"in",
"self",
".",
"_merged_items",
"(",
"i",
")",
":",
"yield",
"v",
"self",
".",
"data",
".",
"clear",
"(",
")",
"# remove the merged partition",
"for",
"j",
"in",
"range",
"(",
"self",
".",
"spills",
")",
":",
"path",
"=",
"self",
".",
"_get_spill_dir",
"(",
"j",
")",
"os",
".",
"remove",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"str",
"(",
"i",
")",
")",
")",
"finally",
":",
"self",
".",
"_cleanup",
"(",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | ExternalMerger._recursive_merged_items | merge the partitioned items and return the as iterator
If one partition can not be fit in memory, then them will be
partitioned and merged recursively. | python/pyspark/shuffle.py | def _recursive_merged_items(self, index):
"""
merge the partitioned items and return the as iterator
If one partition can not be fit in memory, then them will be
partitioned and merged recursively.
"""
subdirs = [os.path.join(d, "parts", str(index)) for d in self.localdirs]
m = ExternalMerger(self.agg, self.memory_limit, self.serializer, subdirs,
self.scale * self.partitions, self.partitions, self.batch)
m.pdata = [{} for _ in range(self.partitions)]
limit = self._next_limit()
for j in range(self.spills):
path = self._get_spill_dir(j)
p = os.path.join(path, str(index))
with open(p, 'rb') as f:
m.mergeCombiners(self.serializer.load_stream(f), 0)
if get_used_memory() > limit:
m._spill()
limit = self._next_limit()
return m._external_items() | def _recursive_merged_items(self, index):
"""
merge the partitioned items and return the as iterator
If one partition can not be fit in memory, then them will be
partitioned and merged recursively.
"""
subdirs = [os.path.join(d, "parts", str(index)) for d in self.localdirs]
m = ExternalMerger(self.agg, self.memory_limit, self.serializer, subdirs,
self.scale * self.partitions, self.partitions, self.batch)
m.pdata = [{} for _ in range(self.partitions)]
limit = self._next_limit()
for j in range(self.spills):
path = self._get_spill_dir(j)
p = os.path.join(path, str(index))
with open(p, 'rb') as f:
m.mergeCombiners(self.serializer.load_stream(f), 0)
if get_used_memory() > limit:
m._spill()
limit = self._next_limit()
return m._external_items() | [
"merge",
"the",
"partitioned",
"items",
"and",
"return",
"the",
"as",
"iterator"
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/shuffle.py#L386-L409 | [
"def",
"_recursive_merged_items",
"(",
"self",
",",
"index",
")",
":",
"subdirs",
"=",
"[",
"os",
".",
"path",
".",
"join",
"(",
"d",
",",
"\"parts\"",
",",
"str",
"(",
"index",
")",
")",
"for",
"d",
"in",
"self",
".",
"localdirs",
"]",
"m",
"=",
"ExternalMerger",
"(",
"self",
".",
"agg",
",",
"self",
".",
"memory_limit",
",",
"self",
".",
"serializer",
",",
"subdirs",
",",
"self",
".",
"scale",
"*",
"self",
".",
"partitions",
",",
"self",
".",
"partitions",
",",
"self",
".",
"batch",
")",
"m",
".",
"pdata",
"=",
"[",
"{",
"}",
"for",
"_",
"in",
"range",
"(",
"self",
".",
"partitions",
")",
"]",
"limit",
"=",
"self",
".",
"_next_limit",
"(",
")",
"for",
"j",
"in",
"range",
"(",
"self",
".",
"spills",
")",
":",
"path",
"=",
"self",
".",
"_get_spill_dir",
"(",
"j",
")",
"p",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"str",
"(",
"index",
")",
")",
"with",
"open",
"(",
"p",
",",
"'rb'",
")",
"as",
"f",
":",
"m",
".",
"mergeCombiners",
"(",
"self",
".",
"serializer",
".",
"load_stream",
"(",
"f",
")",
",",
"0",
")",
"if",
"get_used_memory",
"(",
")",
">",
"limit",
":",
"m",
".",
"_spill",
"(",
")",
"limit",
"=",
"self",
".",
"_next_limit",
"(",
")",
"return",
"m",
".",
"_external_items",
"(",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | ExternalSorter._get_path | Choose one directory for spill by number n | python/pyspark/shuffle.py | def _get_path(self, n):
""" Choose one directory for spill by number n """
d = self.local_dirs[n % len(self.local_dirs)]
if not os.path.exists(d):
os.makedirs(d)
return os.path.join(d, str(n)) | def _get_path(self, n):
""" Choose one directory for spill by number n """
d = self.local_dirs[n % len(self.local_dirs)]
if not os.path.exists(d):
os.makedirs(d)
return os.path.join(d, str(n)) | [
"Choose",
"one",
"directory",
"for",
"spill",
"by",
"number",
"n"
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/shuffle.py#L440-L445 | [
"def",
"_get_path",
"(",
"self",
",",
"n",
")",
":",
"d",
"=",
"self",
".",
"local_dirs",
"[",
"n",
"%",
"len",
"(",
"self",
".",
"local_dirs",
")",
"]",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"d",
")",
":",
"os",
".",
"makedirs",
"(",
"d",
")",
"return",
"os",
".",
"path",
".",
"join",
"(",
"d",
",",
"str",
"(",
"n",
")",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | ExternalSorter.sorted | Sort the elements in iterator, do external sort when the memory
goes above the limit. | python/pyspark/shuffle.py | def sorted(self, iterator, key=None, reverse=False):
"""
Sort the elements in iterator, do external sort when the memory
goes above the limit.
"""
global MemoryBytesSpilled, DiskBytesSpilled
batch, limit = 100, self._next_limit()
chunks, current_chunk = [], []
iterator = iter(iterator)
while True:
# pick elements in batch
chunk = list(itertools.islice(iterator, batch))
current_chunk.extend(chunk)
if len(chunk) < batch:
break
used_memory = get_used_memory()
if used_memory > limit:
# sort them inplace will save memory
current_chunk.sort(key=key, reverse=reverse)
path = self._get_path(len(chunks))
with open(path, 'wb') as f:
self.serializer.dump_stream(current_chunk, f)
def load(f):
for v in self.serializer.load_stream(f):
yield v
# close the file explicit once we consume all the items
# to avoid ResourceWarning in Python3
f.close()
chunks.append(load(open(path, 'rb')))
current_chunk = []
MemoryBytesSpilled += max(used_memory - get_used_memory(), 0) << 20
DiskBytesSpilled += os.path.getsize(path)
os.unlink(path) # data will be deleted after close
elif not chunks:
batch = min(int(batch * 1.5), 10000)
current_chunk.sort(key=key, reverse=reverse)
if not chunks:
return current_chunk
if current_chunk:
chunks.append(iter(current_chunk))
return heapq.merge(chunks, key=key, reverse=reverse) | def sorted(self, iterator, key=None, reverse=False):
"""
Sort the elements in iterator, do external sort when the memory
goes above the limit.
"""
global MemoryBytesSpilled, DiskBytesSpilled
batch, limit = 100, self._next_limit()
chunks, current_chunk = [], []
iterator = iter(iterator)
while True:
# pick elements in batch
chunk = list(itertools.islice(iterator, batch))
current_chunk.extend(chunk)
if len(chunk) < batch:
break
used_memory = get_used_memory()
if used_memory > limit:
# sort them inplace will save memory
current_chunk.sort(key=key, reverse=reverse)
path = self._get_path(len(chunks))
with open(path, 'wb') as f:
self.serializer.dump_stream(current_chunk, f)
def load(f):
for v in self.serializer.load_stream(f):
yield v
# close the file explicit once we consume all the items
# to avoid ResourceWarning in Python3
f.close()
chunks.append(load(open(path, 'rb')))
current_chunk = []
MemoryBytesSpilled += max(used_memory - get_used_memory(), 0) << 20
DiskBytesSpilled += os.path.getsize(path)
os.unlink(path) # data will be deleted after close
elif not chunks:
batch = min(int(batch * 1.5), 10000)
current_chunk.sort(key=key, reverse=reverse)
if not chunks:
return current_chunk
if current_chunk:
chunks.append(iter(current_chunk))
return heapq.merge(chunks, key=key, reverse=reverse) | [
"Sort",
"the",
"elements",
"in",
"iterator",
"do",
"external",
"sort",
"when",
"the",
"memory",
"goes",
"above",
"the",
"limit",
"."
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/shuffle.py#L455-L501 | [
"def",
"sorted",
"(",
"self",
",",
"iterator",
",",
"key",
"=",
"None",
",",
"reverse",
"=",
"False",
")",
":",
"global",
"MemoryBytesSpilled",
",",
"DiskBytesSpilled",
"batch",
",",
"limit",
"=",
"100",
",",
"self",
".",
"_next_limit",
"(",
")",
"chunks",
",",
"current_chunk",
"=",
"[",
"]",
",",
"[",
"]",
"iterator",
"=",
"iter",
"(",
"iterator",
")",
"while",
"True",
":",
"# pick elements in batch",
"chunk",
"=",
"list",
"(",
"itertools",
".",
"islice",
"(",
"iterator",
",",
"batch",
")",
")",
"current_chunk",
".",
"extend",
"(",
"chunk",
")",
"if",
"len",
"(",
"chunk",
")",
"<",
"batch",
":",
"break",
"used_memory",
"=",
"get_used_memory",
"(",
")",
"if",
"used_memory",
">",
"limit",
":",
"# sort them inplace will save memory",
"current_chunk",
".",
"sort",
"(",
"key",
"=",
"key",
",",
"reverse",
"=",
"reverse",
")",
"path",
"=",
"self",
".",
"_get_path",
"(",
"len",
"(",
"chunks",
")",
")",
"with",
"open",
"(",
"path",
",",
"'wb'",
")",
"as",
"f",
":",
"self",
".",
"serializer",
".",
"dump_stream",
"(",
"current_chunk",
",",
"f",
")",
"def",
"load",
"(",
"f",
")",
":",
"for",
"v",
"in",
"self",
".",
"serializer",
".",
"load_stream",
"(",
"f",
")",
":",
"yield",
"v",
"# close the file explicit once we consume all the items",
"# to avoid ResourceWarning in Python3",
"f",
".",
"close",
"(",
")",
"chunks",
".",
"append",
"(",
"load",
"(",
"open",
"(",
"path",
",",
"'rb'",
")",
")",
")",
"current_chunk",
"=",
"[",
"]",
"MemoryBytesSpilled",
"+=",
"max",
"(",
"used_memory",
"-",
"get_used_memory",
"(",
")",
",",
"0",
")",
"<<",
"20",
"DiskBytesSpilled",
"+=",
"os",
".",
"path",
".",
"getsize",
"(",
"path",
")",
"os",
".",
"unlink",
"(",
"path",
")",
"# data will be deleted after close",
"elif",
"not",
"chunks",
":",
"batch",
"=",
"min",
"(",
"int",
"(",
"batch",
"*",
"1.5",
")",
",",
"10000",
")",
"current_chunk",
".",
"sort",
"(",
"key",
"=",
"key",
",",
"reverse",
"=",
"reverse",
")",
"if",
"not",
"chunks",
":",
"return",
"current_chunk",
"if",
"current_chunk",
":",
"chunks",
".",
"append",
"(",
"iter",
"(",
"current_chunk",
")",
")",
"return",
"heapq",
".",
"merge",
"(",
"chunks",
",",
"key",
"=",
"key",
",",
"reverse",
"=",
"reverse",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | ExternalList._spill | dump the values into disk | python/pyspark/shuffle.py | def _spill(self):
""" dump the values into disk """
global MemoryBytesSpilled, DiskBytesSpilled
if self._file is None:
self._open_file()
used_memory = get_used_memory()
pos = self._file.tell()
self._ser.dump_stream(self.values, self._file)
self.values = []
gc.collect()
DiskBytesSpilled += self._file.tell() - pos
MemoryBytesSpilled += max(used_memory - get_used_memory(), 0) << 20 | def _spill(self):
""" dump the values into disk """
global MemoryBytesSpilled, DiskBytesSpilled
if self._file is None:
self._open_file()
used_memory = get_used_memory()
pos = self._file.tell()
self._ser.dump_stream(self.values, self._file)
self.values = []
gc.collect()
DiskBytesSpilled += self._file.tell() - pos
MemoryBytesSpilled += max(used_memory - get_used_memory(), 0) << 20 | [
"dump",
"the",
"values",
"into",
"disk"
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/shuffle.py#L590-L602 | [
"def",
"_spill",
"(",
"self",
")",
":",
"global",
"MemoryBytesSpilled",
",",
"DiskBytesSpilled",
"if",
"self",
".",
"_file",
"is",
"None",
":",
"self",
".",
"_open_file",
"(",
")",
"used_memory",
"=",
"get_used_memory",
"(",
")",
"pos",
"=",
"self",
".",
"_file",
".",
"tell",
"(",
")",
"self",
".",
"_ser",
".",
"dump_stream",
"(",
"self",
".",
"values",
",",
"self",
".",
"_file",
")",
"self",
".",
"values",
"=",
"[",
"]",
"gc",
".",
"collect",
"(",
")",
"DiskBytesSpilled",
"+=",
"self",
".",
"_file",
".",
"tell",
"(",
")",
"-",
"pos",
"MemoryBytesSpilled",
"+=",
"max",
"(",
"used_memory",
"-",
"get_used_memory",
"(",
")",
",",
"0",
")",
"<<",
"20"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | ExternalGroupBy._spill | dump already partitioned data into disks. | python/pyspark/shuffle.py | def _spill(self):
"""
dump already partitioned data into disks.
"""
global MemoryBytesSpilled, DiskBytesSpilled
path = self._get_spill_dir(self.spills)
if not os.path.exists(path):
os.makedirs(path)
used_memory = get_used_memory()
if not self.pdata:
# The data has not been partitioned, it will iterator the
# data once, write them into different files, has no
# additional memory. It only called when the memory goes
# above limit at the first time.
# open all the files for writing
streams = [open(os.path.join(path, str(i)), 'wb')
for i in range(self.partitions)]
# If the number of keys is small, then the overhead of sort is small
# sort them before dumping into disks
self._sorted = len(self.data) < self.SORT_KEY_LIMIT
if self._sorted:
self.serializer = self.flattened_serializer()
for k in sorted(self.data.keys()):
h = self._partition(k)
self.serializer.dump_stream([(k, self.data[k])], streams[h])
else:
for k, v in self.data.items():
h = self._partition(k)
self.serializer.dump_stream([(k, v)], streams[h])
for s in streams:
DiskBytesSpilled += s.tell()
s.close()
self.data.clear()
# self.pdata is cached in `mergeValues` and `mergeCombiners`
self.pdata.extend([{} for i in range(self.partitions)])
else:
for i in range(self.partitions):
p = os.path.join(path, str(i))
with open(p, "wb") as f:
# dump items in batch
if self._sorted:
# sort by key only (stable)
sorted_items = sorted(self.pdata[i].items(), key=operator.itemgetter(0))
self.serializer.dump_stream(sorted_items, f)
else:
self.serializer.dump_stream(self.pdata[i].items(), f)
self.pdata[i].clear()
DiskBytesSpilled += os.path.getsize(p)
self.spills += 1
gc.collect() # release the memory as much as possible
MemoryBytesSpilled += max(used_memory - get_used_memory(), 0) << 20 | def _spill(self):
"""
dump already partitioned data into disks.
"""
global MemoryBytesSpilled, DiskBytesSpilled
path = self._get_spill_dir(self.spills)
if not os.path.exists(path):
os.makedirs(path)
used_memory = get_used_memory()
if not self.pdata:
# The data has not been partitioned, it will iterator the
# data once, write them into different files, has no
# additional memory. It only called when the memory goes
# above limit at the first time.
# open all the files for writing
streams = [open(os.path.join(path, str(i)), 'wb')
for i in range(self.partitions)]
# If the number of keys is small, then the overhead of sort is small
# sort them before dumping into disks
self._sorted = len(self.data) < self.SORT_KEY_LIMIT
if self._sorted:
self.serializer = self.flattened_serializer()
for k in sorted(self.data.keys()):
h = self._partition(k)
self.serializer.dump_stream([(k, self.data[k])], streams[h])
else:
for k, v in self.data.items():
h = self._partition(k)
self.serializer.dump_stream([(k, v)], streams[h])
for s in streams:
DiskBytesSpilled += s.tell()
s.close()
self.data.clear()
# self.pdata is cached in `mergeValues` and `mergeCombiners`
self.pdata.extend([{} for i in range(self.partitions)])
else:
for i in range(self.partitions):
p = os.path.join(path, str(i))
with open(p, "wb") as f:
# dump items in batch
if self._sorted:
# sort by key only (stable)
sorted_items = sorted(self.pdata[i].items(), key=operator.itemgetter(0))
self.serializer.dump_stream(sorted_items, f)
else:
self.serializer.dump_stream(self.pdata[i].items(), f)
self.pdata[i].clear()
DiskBytesSpilled += os.path.getsize(p)
self.spills += 1
gc.collect() # release the memory as much as possible
MemoryBytesSpilled += max(used_memory - get_used_memory(), 0) << 20 | [
"dump",
"already",
"partitioned",
"data",
"into",
"disks",
"."
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/shuffle.py#L709-L766 | [
"def",
"_spill",
"(",
"self",
")",
":",
"global",
"MemoryBytesSpilled",
",",
"DiskBytesSpilled",
"path",
"=",
"self",
".",
"_get_spill_dir",
"(",
"self",
".",
"spills",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"os",
".",
"makedirs",
"(",
"path",
")",
"used_memory",
"=",
"get_used_memory",
"(",
")",
"if",
"not",
"self",
".",
"pdata",
":",
"# The data has not been partitioned, it will iterator the",
"# data once, write them into different files, has no",
"# additional memory. It only called when the memory goes",
"# above limit at the first time.",
"# open all the files for writing",
"streams",
"=",
"[",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"str",
"(",
"i",
")",
")",
",",
"'wb'",
")",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"partitions",
")",
"]",
"# If the number of keys is small, then the overhead of sort is small",
"# sort them before dumping into disks",
"self",
".",
"_sorted",
"=",
"len",
"(",
"self",
".",
"data",
")",
"<",
"self",
".",
"SORT_KEY_LIMIT",
"if",
"self",
".",
"_sorted",
":",
"self",
".",
"serializer",
"=",
"self",
".",
"flattened_serializer",
"(",
")",
"for",
"k",
"in",
"sorted",
"(",
"self",
".",
"data",
".",
"keys",
"(",
")",
")",
":",
"h",
"=",
"self",
".",
"_partition",
"(",
"k",
")",
"self",
".",
"serializer",
".",
"dump_stream",
"(",
"[",
"(",
"k",
",",
"self",
".",
"data",
"[",
"k",
"]",
")",
"]",
",",
"streams",
"[",
"h",
"]",
")",
"else",
":",
"for",
"k",
",",
"v",
"in",
"self",
".",
"data",
".",
"items",
"(",
")",
":",
"h",
"=",
"self",
".",
"_partition",
"(",
"k",
")",
"self",
".",
"serializer",
".",
"dump_stream",
"(",
"[",
"(",
"k",
",",
"v",
")",
"]",
",",
"streams",
"[",
"h",
"]",
")",
"for",
"s",
"in",
"streams",
":",
"DiskBytesSpilled",
"+=",
"s",
".",
"tell",
"(",
")",
"s",
".",
"close",
"(",
")",
"self",
".",
"data",
".",
"clear",
"(",
")",
"# self.pdata is cached in `mergeValues` and `mergeCombiners`",
"self",
".",
"pdata",
".",
"extend",
"(",
"[",
"{",
"}",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"partitions",
")",
"]",
")",
"else",
":",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"partitions",
")",
":",
"p",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"str",
"(",
"i",
")",
")",
"with",
"open",
"(",
"p",
",",
"\"wb\"",
")",
"as",
"f",
":",
"# dump items in batch",
"if",
"self",
".",
"_sorted",
":",
"# sort by key only (stable)",
"sorted_items",
"=",
"sorted",
"(",
"self",
".",
"pdata",
"[",
"i",
"]",
".",
"items",
"(",
")",
",",
"key",
"=",
"operator",
".",
"itemgetter",
"(",
"0",
")",
")",
"self",
".",
"serializer",
".",
"dump_stream",
"(",
"sorted_items",
",",
"f",
")",
"else",
":",
"self",
".",
"serializer",
".",
"dump_stream",
"(",
"self",
".",
"pdata",
"[",
"i",
"]",
".",
"items",
"(",
")",
",",
"f",
")",
"self",
".",
"pdata",
"[",
"i",
"]",
".",
"clear",
"(",
")",
"DiskBytesSpilled",
"+=",
"os",
".",
"path",
".",
"getsize",
"(",
"p",
")",
"self",
".",
"spills",
"+=",
"1",
"gc",
".",
"collect",
"(",
")",
"# release the memory as much as possible",
"MemoryBytesSpilled",
"+=",
"max",
"(",
"used_memory",
"-",
"get_used_memory",
"(",
")",
",",
"0",
")",
"<<",
"20"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | ExternalGroupBy._merge_sorted_items | load a partition from disk, then sort and group by key | python/pyspark/shuffle.py | def _merge_sorted_items(self, index):
""" load a partition from disk, then sort and group by key """
def load_partition(j):
path = self._get_spill_dir(j)
p = os.path.join(path, str(index))
with open(p, 'rb', 65536) as f:
for v in self.serializer.load_stream(f):
yield v
disk_items = [load_partition(j) for j in range(self.spills)]
if self._sorted:
# all the partitions are already sorted
sorted_items = heapq.merge(disk_items, key=operator.itemgetter(0))
else:
# Flatten the combined values, so it will not consume huge
# memory during merging sort.
ser = self.flattened_serializer()
sorter = ExternalSorter(self.memory_limit, ser)
sorted_items = sorter.sorted(itertools.chain(*disk_items),
key=operator.itemgetter(0))
return ((k, vs) for k, vs in GroupByKey(sorted_items)) | def _merge_sorted_items(self, index):
""" load a partition from disk, then sort and group by key """
def load_partition(j):
path = self._get_spill_dir(j)
p = os.path.join(path, str(index))
with open(p, 'rb', 65536) as f:
for v in self.serializer.load_stream(f):
yield v
disk_items = [load_partition(j) for j in range(self.spills)]
if self._sorted:
# all the partitions are already sorted
sorted_items = heapq.merge(disk_items, key=operator.itemgetter(0))
else:
# Flatten the combined values, so it will not consume huge
# memory during merging sort.
ser = self.flattened_serializer()
sorter = ExternalSorter(self.memory_limit, ser)
sorted_items = sorter.sorted(itertools.chain(*disk_items),
key=operator.itemgetter(0))
return ((k, vs) for k, vs in GroupByKey(sorted_items)) | [
"load",
"a",
"partition",
"from",
"disk",
"then",
"sort",
"and",
"group",
"by",
"key"
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/shuffle.py#L786-L808 | [
"def",
"_merge_sorted_items",
"(",
"self",
",",
"index",
")",
":",
"def",
"load_partition",
"(",
"j",
")",
":",
"path",
"=",
"self",
".",
"_get_spill_dir",
"(",
"j",
")",
"p",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"str",
"(",
"index",
")",
")",
"with",
"open",
"(",
"p",
",",
"'rb'",
",",
"65536",
")",
"as",
"f",
":",
"for",
"v",
"in",
"self",
".",
"serializer",
".",
"load_stream",
"(",
"f",
")",
":",
"yield",
"v",
"disk_items",
"=",
"[",
"load_partition",
"(",
"j",
")",
"for",
"j",
"in",
"range",
"(",
"self",
".",
"spills",
")",
"]",
"if",
"self",
".",
"_sorted",
":",
"# all the partitions are already sorted",
"sorted_items",
"=",
"heapq",
".",
"merge",
"(",
"disk_items",
",",
"key",
"=",
"operator",
".",
"itemgetter",
"(",
"0",
")",
")",
"else",
":",
"# Flatten the combined values, so it will not consume huge",
"# memory during merging sort.",
"ser",
"=",
"self",
".",
"flattened_serializer",
"(",
")",
"sorter",
"=",
"ExternalSorter",
"(",
"self",
".",
"memory_limit",
",",
"ser",
")",
"sorted_items",
"=",
"sorter",
".",
"sorted",
"(",
"itertools",
".",
"chain",
"(",
"*",
"disk_items",
")",
",",
"key",
"=",
"operator",
".",
"itemgetter",
"(",
"0",
")",
")",
"return",
"(",
"(",
"k",
",",
"vs",
")",
"for",
"k",
",",
"vs",
"in",
"GroupByKey",
"(",
"sorted_items",
")",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | worker | Called by a worker process after the fork(). | python/pyspark/daemon.py | def worker(sock, authenticated):
"""
Called by a worker process after the fork().
"""
signal.signal(SIGHUP, SIG_DFL)
signal.signal(SIGCHLD, SIG_DFL)
signal.signal(SIGTERM, SIG_DFL)
# restore the handler for SIGINT,
# it's useful for debugging (show the stacktrace before exit)
signal.signal(SIGINT, signal.default_int_handler)
# Read the socket using fdopen instead of socket.makefile() because the latter
# seems to be very slow; note that we need to dup() the file descriptor because
# otherwise writes also cause a seek that makes us miss data on the read side.
infile = os.fdopen(os.dup(sock.fileno()), "rb", 65536)
outfile = os.fdopen(os.dup(sock.fileno()), "wb", 65536)
if not authenticated:
client_secret = UTF8Deserializer().loads(infile)
if os.environ["PYTHON_WORKER_FACTORY_SECRET"] == client_secret:
write_with_length("ok".encode("utf-8"), outfile)
outfile.flush()
else:
write_with_length("err".encode("utf-8"), outfile)
outfile.flush()
sock.close()
return 1
exit_code = 0
try:
worker_main(infile, outfile)
except SystemExit as exc:
exit_code = compute_real_exit_code(exc.code)
finally:
try:
outfile.flush()
except Exception:
pass
return exit_code | def worker(sock, authenticated):
"""
Called by a worker process after the fork().
"""
signal.signal(SIGHUP, SIG_DFL)
signal.signal(SIGCHLD, SIG_DFL)
signal.signal(SIGTERM, SIG_DFL)
# restore the handler for SIGINT,
# it's useful for debugging (show the stacktrace before exit)
signal.signal(SIGINT, signal.default_int_handler)
# Read the socket using fdopen instead of socket.makefile() because the latter
# seems to be very slow; note that we need to dup() the file descriptor because
# otherwise writes also cause a seek that makes us miss data on the read side.
infile = os.fdopen(os.dup(sock.fileno()), "rb", 65536)
outfile = os.fdopen(os.dup(sock.fileno()), "wb", 65536)
if not authenticated:
client_secret = UTF8Deserializer().loads(infile)
if os.environ["PYTHON_WORKER_FACTORY_SECRET"] == client_secret:
write_with_length("ok".encode("utf-8"), outfile)
outfile.flush()
else:
write_with_length("err".encode("utf-8"), outfile)
outfile.flush()
sock.close()
return 1
exit_code = 0
try:
worker_main(infile, outfile)
except SystemExit as exc:
exit_code = compute_real_exit_code(exc.code)
finally:
try:
outfile.flush()
except Exception:
pass
return exit_code | [
"Called",
"by",
"a",
"worker",
"process",
"after",
"the",
"fork",
"()",
"."
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/daemon.py#L43-L81 | [
"def",
"worker",
"(",
"sock",
",",
"authenticated",
")",
":",
"signal",
".",
"signal",
"(",
"SIGHUP",
",",
"SIG_DFL",
")",
"signal",
".",
"signal",
"(",
"SIGCHLD",
",",
"SIG_DFL",
")",
"signal",
".",
"signal",
"(",
"SIGTERM",
",",
"SIG_DFL",
")",
"# restore the handler for SIGINT,",
"# it's useful for debugging (show the stacktrace before exit)",
"signal",
".",
"signal",
"(",
"SIGINT",
",",
"signal",
".",
"default_int_handler",
")",
"# Read the socket using fdopen instead of socket.makefile() because the latter",
"# seems to be very slow; note that we need to dup() the file descriptor because",
"# otherwise writes also cause a seek that makes us miss data on the read side.",
"infile",
"=",
"os",
".",
"fdopen",
"(",
"os",
".",
"dup",
"(",
"sock",
".",
"fileno",
"(",
")",
")",
",",
"\"rb\"",
",",
"65536",
")",
"outfile",
"=",
"os",
".",
"fdopen",
"(",
"os",
".",
"dup",
"(",
"sock",
".",
"fileno",
"(",
")",
")",
",",
"\"wb\"",
",",
"65536",
")",
"if",
"not",
"authenticated",
":",
"client_secret",
"=",
"UTF8Deserializer",
"(",
")",
".",
"loads",
"(",
"infile",
")",
"if",
"os",
".",
"environ",
"[",
"\"PYTHON_WORKER_FACTORY_SECRET\"",
"]",
"==",
"client_secret",
":",
"write_with_length",
"(",
"\"ok\"",
".",
"encode",
"(",
"\"utf-8\"",
")",
",",
"outfile",
")",
"outfile",
".",
"flush",
"(",
")",
"else",
":",
"write_with_length",
"(",
"\"err\"",
".",
"encode",
"(",
"\"utf-8\"",
")",
",",
"outfile",
")",
"outfile",
".",
"flush",
"(",
")",
"sock",
".",
"close",
"(",
")",
"return",
"1",
"exit_code",
"=",
"0",
"try",
":",
"worker_main",
"(",
"infile",
",",
"outfile",
")",
"except",
"SystemExit",
"as",
"exc",
":",
"exit_code",
"=",
"compute_real_exit_code",
"(",
"exc",
".",
"code",
")",
"finally",
":",
"try",
":",
"outfile",
".",
"flush",
"(",
")",
"except",
"Exception",
":",
"pass",
"return",
"exit_code"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | portable_hash | This function returns consistent hash code for builtin types, especially
for None and tuple with None.
The algorithm is similar to that one used by CPython 2.7
>>> portable_hash(None)
0
>>> portable_hash((None, 1)) & 0xffffffff
219750521 | python/pyspark/rdd.py | def portable_hash(x):
"""
This function returns consistent hash code for builtin types, especially
for None and tuple with None.
The algorithm is similar to that one used by CPython 2.7
>>> portable_hash(None)
0
>>> portable_hash((None, 1)) & 0xffffffff
219750521
"""
if sys.version_info >= (3, 2, 3) and 'PYTHONHASHSEED' not in os.environ:
raise Exception("Randomness of hash of string should be disabled via PYTHONHASHSEED")
if x is None:
return 0
if isinstance(x, tuple):
h = 0x345678
for i in x:
h ^= portable_hash(i)
h *= 1000003
h &= sys.maxsize
h ^= len(x)
if h == -1:
h = -2
return int(h)
return hash(x) | def portable_hash(x):
"""
This function returns consistent hash code for builtin types, especially
for None and tuple with None.
The algorithm is similar to that one used by CPython 2.7
>>> portable_hash(None)
0
>>> portable_hash((None, 1)) & 0xffffffff
219750521
"""
if sys.version_info >= (3, 2, 3) and 'PYTHONHASHSEED' not in os.environ:
raise Exception("Randomness of hash of string should be disabled via PYTHONHASHSEED")
if x is None:
return 0
if isinstance(x, tuple):
h = 0x345678
for i in x:
h ^= portable_hash(i)
h *= 1000003
h &= sys.maxsize
h ^= len(x)
if h == -1:
h = -2
return int(h)
return hash(x) | [
"This",
"function",
"returns",
"consistent",
"hash",
"code",
"for",
"builtin",
"types",
"especially",
"for",
"None",
"and",
"tuple",
"with",
"None",
"."
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L78-L106 | [
"def",
"portable_hash",
"(",
"x",
")",
":",
"if",
"sys",
".",
"version_info",
">=",
"(",
"3",
",",
"2",
",",
"3",
")",
"and",
"'PYTHONHASHSEED'",
"not",
"in",
"os",
".",
"environ",
":",
"raise",
"Exception",
"(",
"\"Randomness of hash of string should be disabled via PYTHONHASHSEED\"",
")",
"if",
"x",
"is",
"None",
":",
"return",
"0",
"if",
"isinstance",
"(",
"x",
",",
"tuple",
")",
":",
"h",
"=",
"0x345678",
"for",
"i",
"in",
"x",
":",
"h",
"^=",
"portable_hash",
"(",
"i",
")",
"h",
"*=",
"1000003",
"h",
"&=",
"sys",
".",
"maxsize",
"h",
"^=",
"len",
"(",
"x",
")",
"if",
"h",
"==",
"-",
"1",
":",
"h",
"=",
"-",
"2",
"return",
"int",
"(",
"h",
")",
"return",
"hash",
"(",
"x",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | _parse_memory | Parse a memory string in the format supported by Java (e.g. 1g, 200m) and
return the value in MiB
>>> _parse_memory("256m")
256
>>> _parse_memory("2g")
2048 | python/pyspark/rdd.py | def _parse_memory(s):
"""
Parse a memory string in the format supported by Java (e.g. 1g, 200m) and
return the value in MiB
>>> _parse_memory("256m")
256
>>> _parse_memory("2g")
2048
"""
units = {'g': 1024, 'm': 1, 't': 1 << 20, 'k': 1.0 / 1024}
if s[-1].lower() not in units:
raise ValueError("invalid format: " + s)
return int(float(s[:-1]) * units[s[-1].lower()]) | def _parse_memory(s):
"""
Parse a memory string in the format supported by Java (e.g. 1g, 200m) and
return the value in MiB
>>> _parse_memory("256m")
256
>>> _parse_memory("2g")
2048
"""
units = {'g': 1024, 'm': 1, 't': 1 << 20, 'k': 1.0 / 1024}
if s[-1].lower() not in units:
raise ValueError("invalid format: " + s)
return int(float(s[:-1]) * units[s[-1].lower()]) | [
"Parse",
"a",
"memory",
"string",
"in",
"the",
"format",
"supported",
"by",
"Java",
"(",
"e",
".",
"g",
".",
"1g",
"200m",
")",
"and",
"return",
"the",
"value",
"in",
"MiB"
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L125-L138 | [
"def",
"_parse_memory",
"(",
"s",
")",
":",
"units",
"=",
"{",
"'g'",
":",
"1024",
",",
"'m'",
":",
"1",
",",
"'t'",
":",
"1",
"<<",
"20",
",",
"'k'",
":",
"1.0",
"/",
"1024",
"}",
"if",
"s",
"[",
"-",
"1",
"]",
".",
"lower",
"(",
")",
"not",
"in",
"units",
":",
"raise",
"ValueError",
"(",
"\"invalid format: \"",
"+",
"s",
")",
"return",
"int",
"(",
"float",
"(",
"s",
"[",
":",
"-",
"1",
"]",
")",
"*",
"units",
"[",
"s",
"[",
"-",
"1",
"]",
".",
"lower",
"(",
")",
"]",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | ignore_unicode_prefix | Ignore the 'u' prefix of string in doc tests, to make it works
in both python 2 and 3 | python/pyspark/rdd.py | def ignore_unicode_prefix(f):
"""
Ignore the 'u' prefix of string in doc tests, to make it works
in both python 2 and 3
"""
if sys.version >= '3':
# the representation of unicode string in Python 3 does not have prefix 'u',
# so remove the prefix 'u' for doc tests
literal_re = re.compile(r"(\W|^)[uU](['])", re.UNICODE)
f.__doc__ = literal_re.sub(r'\1\2', f.__doc__)
return f | def ignore_unicode_prefix(f):
"""
Ignore the 'u' prefix of string in doc tests, to make it works
in both python 2 and 3
"""
if sys.version >= '3':
# the representation of unicode string in Python 3 does not have prefix 'u',
# so remove the prefix 'u' for doc tests
literal_re = re.compile(r"(\W|^)[uU](['])", re.UNICODE)
f.__doc__ = literal_re.sub(r'\1\2', f.__doc__)
return f | [
"Ignore",
"the",
"u",
"prefix",
"of",
"string",
"in",
"doc",
"tests",
"to",
"make",
"it",
"works",
"in",
"both",
"python",
"2",
"and",
"3"
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L150-L160 | [
"def",
"ignore_unicode_prefix",
"(",
"f",
")",
":",
"if",
"sys",
".",
"version",
">=",
"'3'",
":",
"# the representation of unicode string in Python 3 does not have prefix 'u',",
"# so remove the prefix 'u' for doc tests",
"literal_re",
"=",
"re",
".",
"compile",
"(",
"r\"(\\W|^)[uU](['])\"",
",",
"re",
".",
"UNICODE",
")",
"f",
".",
"__doc__",
"=",
"literal_re",
".",
"sub",
"(",
"r'\\1\\2'",
",",
"f",
".",
"__doc__",
")",
"return",
"f"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | RDD.cache | Persist this RDD with the default storage level (C{MEMORY_ONLY}). | python/pyspark/rdd.py | def cache(self):
"""
Persist this RDD with the default storage level (C{MEMORY_ONLY}).
"""
self.is_cached = True
self.persist(StorageLevel.MEMORY_ONLY)
return self | def cache(self):
"""
Persist this RDD with the default storage level (C{MEMORY_ONLY}).
"""
self.is_cached = True
self.persist(StorageLevel.MEMORY_ONLY)
return self | [
"Persist",
"this",
"RDD",
"with",
"the",
"default",
"storage",
"level",
"(",
"C",
"{",
"MEMORY_ONLY",
"}",
")",
"."
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L223-L229 | [
"def",
"cache",
"(",
"self",
")",
":",
"self",
".",
"is_cached",
"=",
"True",
"self",
".",
"persist",
"(",
"StorageLevel",
".",
"MEMORY_ONLY",
")",
"return",
"self"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | RDD.persist | Set this RDD's storage level to persist its values across operations
after the first time it is computed. This can only be used to assign
a new storage level if the RDD does not have a storage level set yet.
If no storage level is specified defaults to (C{MEMORY_ONLY}).
>>> rdd = sc.parallelize(["b", "a", "c"])
>>> rdd.persist().is_cached
True | python/pyspark/rdd.py | def persist(self, storageLevel=StorageLevel.MEMORY_ONLY):
"""
Set this RDD's storage level to persist its values across operations
after the first time it is computed. This can only be used to assign
a new storage level if the RDD does not have a storage level set yet.
If no storage level is specified defaults to (C{MEMORY_ONLY}).
>>> rdd = sc.parallelize(["b", "a", "c"])
>>> rdd.persist().is_cached
True
"""
self.is_cached = True
javaStorageLevel = self.ctx._getJavaStorageLevel(storageLevel)
self._jrdd.persist(javaStorageLevel)
return self | def persist(self, storageLevel=StorageLevel.MEMORY_ONLY):
"""
Set this RDD's storage level to persist its values across operations
after the first time it is computed. This can only be used to assign
a new storage level if the RDD does not have a storage level set yet.
If no storage level is specified defaults to (C{MEMORY_ONLY}).
>>> rdd = sc.parallelize(["b", "a", "c"])
>>> rdd.persist().is_cached
True
"""
self.is_cached = True
javaStorageLevel = self.ctx._getJavaStorageLevel(storageLevel)
self._jrdd.persist(javaStorageLevel)
return self | [
"Set",
"this",
"RDD",
"s",
"storage",
"level",
"to",
"persist",
"its",
"values",
"across",
"operations",
"after",
"the",
"first",
"time",
"it",
"is",
"computed",
".",
"This",
"can",
"only",
"be",
"used",
"to",
"assign",
"a",
"new",
"storage",
"level",
"if",
"the",
"RDD",
"does",
"not",
"have",
"a",
"storage",
"level",
"set",
"yet",
".",
"If",
"no",
"storage",
"level",
"is",
"specified",
"defaults",
"to",
"(",
"C",
"{",
"MEMORY_ONLY",
"}",
")",
"."
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L231-L245 | [
"def",
"persist",
"(",
"self",
",",
"storageLevel",
"=",
"StorageLevel",
".",
"MEMORY_ONLY",
")",
":",
"self",
".",
"is_cached",
"=",
"True",
"javaStorageLevel",
"=",
"self",
".",
"ctx",
".",
"_getJavaStorageLevel",
"(",
"storageLevel",
")",
"self",
".",
"_jrdd",
".",
"persist",
"(",
"javaStorageLevel",
")",
"return",
"self"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | RDD.unpersist | Mark the RDD as non-persistent, and remove all blocks for it from
memory and disk.
.. versionchanged:: 3.0.0
Added optional argument `blocking` to specify whether to block until all
blocks are deleted. | python/pyspark/rdd.py | def unpersist(self, blocking=False):
"""
Mark the RDD as non-persistent, and remove all blocks for it from
memory and disk.
.. versionchanged:: 3.0.0
Added optional argument `blocking` to specify whether to block until all
blocks are deleted.
"""
self.is_cached = False
self._jrdd.unpersist(blocking)
return self | def unpersist(self, blocking=False):
"""
Mark the RDD as non-persistent, and remove all blocks for it from
memory and disk.
.. versionchanged:: 3.0.0
Added optional argument `blocking` to specify whether to block until all
blocks are deleted.
"""
self.is_cached = False
self._jrdd.unpersist(blocking)
return self | [
"Mark",
"the",
"RDD",
"as",
"non",
"-",
"persistent",
"and",
"remove",
"all",
"blocks",
"for",
"it",
"from",
"memory",
"and",
"disk",
"."
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L247-L258 | [
"def",
"unpersist",
"(",
"self",
",",
"blocking",
"=",
"False",
")",
":",
"self",
".",
"is_cached",
"=",
"False",
"self",
".",
"_jrdd",
".",
"unpersist",
"(",
"blocking",
")",
"return",
"self"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | RDD.getCheckpointFile | Gets the name of the file to which this RDD was checkpointed
Not defined if RDD is checkpointed locally. | python/pyspark/rdd.py | def getCheckpointFile(self):
"""
Gets the name of the file to which this RDD was checkpointed
Not defined if RDD is checkpointed locally.
"""
checkpointFile = self._jrdd.rdd().getCheckpointFile()
if checkpointFile.isDefined():
return checkpointFile.get() | def getCheckpointFile(self):
"""
Gets the name of the file to which this RDD was checkpointed
Not defined if RDD is checkpointed locally.
"""
checkpointFile = self._jrdd.rdd().getCheckpointFile()
if checkpointFile.isDefined():
return checkpointFile.get() | [
"Gets",
"the",
"name",
"of",
"the",
"file",
"to",
"which",
"this",
"RDD",
"was",
"checkpointed"
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L307-L315 | [
"def",
"getCheckpointFile",
"(",
"self",
")",
":",
"checkpointFile",
"=",
"self",
".",
"_jrdd",
".",
"rdd",
"(",
")",
".",
"getCheckpointFile",
"(",
")",
"if",
"checkpointFile",
".",
"isDefined",
"(",
")",
":",
"return",
"checkpointFile",
".",
"get",
"(",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | RDD.map | Return a new RDD by applying a function to each element of this RDD.
>>> rdd = sc.parallelize(["b", "a", "c"])
>>> sorted(rdd.map(lambda x: (x, 1)).collect())
[('a', 1), ('b', 1), ('c', 1)] | python/pyspark/rdd.py | def map(self, f, preservesPartitioning=False):
"""
Return a new RDD by applying a function to each element of this RDD.
>>> rdd = sc.parallelize(["b", "a", "c"])
>>> sorted(rdd.map(lambda x: (x, 1)).collect())
[('a', 1), ('b', 1), ('c', 1)]
"""
def func(_, iterator):
return map(fail_on_stopiteration(f), iterator)
return self.mapPartitionsWithIndex(func, preservesPartitioning) | def map(self, f, preservesPartitioning=False):
"""
Return a new RDD by applying a function to each element of this RDD.
>>> rdd = sc.parallelize(["b", "a", "c"])
>>> sorted(rdd.map(lambda x: (x, 1)).collect())
[('a', 1), ('b', 1), ('c', 1)]
"""
def func(_, iterator):
return map(fail_on_stopiteration(f), iterator)
return self.mapPartitionsWithIndex(func, preservesPartitioning) | [
"Return",
"a",
"new",
"RDD",
"by",
"applying",
"a",
"function",
"to",
"each",
"element",
"of",
"this",
"RDD",
"."
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L317-L327 | [
"def",
"map",
"(",
"self",
",",
"f",
",",
"preservesPartitioning",
"=",
"False",
")",
":",
"def",
"func",
"(",
"_",
",",
"iterator",
")",
":",
"return",
"map",
"(",
"fail_on_stopiteration",
"(",
"f",
")",
",",
"iterator",
")",
"return",
"self",
".",
"mapPartitionsWithIndex",
"(",
"func",
",",
"preservesPartitioning",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | RDD.flatMap | Return a new RDD by first applying a function to all elements of this
RDD, and then flattening the results.
>>> rdd = sc.parallelize([2, 3, 4])
>>> sorted(rdd.flatMap(lambda x: range(1, x)).collect())
[1, 1, 1, 2, 2, 3]
>>> sorted(rdd.flatMap(lambda x: [(x, x), (x, x)]).collect())
[(2, 2), (2, 2), (3, 3), (3, 3), (4, 4), (4, 4)] | python/pyspark/rdd.py | def flatMap(self, f, preservesPartitioning=False):
"""
Return a new RDD by first applying a function to all elements of this
RDD, and then flattening the results.
>>> rdd = sc.parallelize([2, 3, 4])
>>> sorted(rdd.flatMap(lambda x: range(1, x)).collect())
[1, 1, 1, 2, 2, 3]
>>> sorted(rdd.flatMap(lambda x: [(x, x), (x, x)]).collect())
[(2, 2), (2, 2), (3, 3), (3, 3), (4, 4), (4, 4)]
"""
def func(s, iterator):
return chain.from_iterable(map(fail_on_stopiteration(f), iterator))
return self.mapPartitionsWithIndex(func, preservesPartitioning) | def flatMap(self, f, preservesPartitioning=False):
"""
Return a new RDD by first applying a function to all elements of this
RDD, and then flattening the results.
>>> rdd = sc.parallelize([2, 3, 4])
>>> sorted(rdd.flatMap(lambda x: range(1, x)).collect())
[1, 1, 1, 2, 2, 3]
>>> sorted(rdd.flatMap(lambda x: [(x, x), (x, x)]).collect())
[(2, 2), (2, 2), (3, 3), (3, 3), (4, 4), (4, 4)]
"""
def func(s, iterator):
return chain.from_iterable(map(fail_on_stopiteration(f), iterator))
return self.mapPartitionsWithIndex(func, preservesPartitioning) | [
"Return",
"a",
"new",
"RDD",
"by",
"first",
"applying",
"a",
"function",
"to",
"all",
"elements",
"of",
"this",
"RDD",
"and",
"then",
"flattening",
"the",
"results",
"."
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L329-L342 | [
"def",
"flatMap",
"(",
"self",
",",
"f",
",",
"preservesPartitioning",
"=",
"False",
")",
":",
"def",
"func",
"(",
"s",
",",
"iterator",
")",
":",
"return",
"chain",
".",
"from_iterable",
"(",
"map",
"(",
"fail_on_stopiteration",
"(",
"f",
")",
",",
"iterator",
")",
")",
"return",
"self",
".",
"mapPartitionsWithIndex",
"(",
"func",
",",
"preservesPartitioning",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | RDD.mapPartitions | Return a new RDD by applying a function to each partition of this RDD.
>>> rdd = sc.parallelize([1, 2, 3, 4], 2)
>>> def f(iterator): yield sum(iterator)
>>> rdd.mapPartitions(f).collect()
[3, 7] | python/pyspark/rdd.py | def mapPartitions(self, f, preservesPartitioning=False):
"""
Return a new RDD by applying a function to each partition of this RDD.
>>> rdd = sc.parallelize([1, 2, 3, 4], 2)
>>> def f(iterator): yield sum(iterator)
>>> rdd.mapPartitions(f).collect()
[3, 7]
"""
def func(s, iterator):
return f(iterator)
return self.mapPartitionsWithIndex(func, preservesPartitioning) | def mapPartitions(self, f, preservesPartitioning=False):
"""
Return a new RDD by applying a function to each partition of this RDD.
>>> rdd = sc.parallelize([1, 2, 3, 4], 2)
>>> def f(iterator): yield sum(iterator)
>>> rdd.mapPartitions(f).collect()
[3, 7]
"""
def func(s, iterator):
return f(iterator)
return self.mapPartitionsWithIndex(func, preservesPartitioning) | [
"Return",
"a",
"new",
"RDD",
"by",
"applying",
"a",
"function",
"to",
"each",
"partition",
"of",
"this",
"RDD",
"."
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L344-L355 | [
"def",
"mapPartitions",
"(",
"self",
",",
"f",
",",
"preservesPartitioning",
"=",
"False",
")",
":",
"def",
"func",
"(",
"s",
",",
"iterator",
")",
":",
"return",
"f",
"(",
"iterator",
")",
"return",
"self",
".",
"mapPartitionsWithIndex",
"(",
"func",
",",
"preservesPartitioning",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | RDD.mapPartitionsWithSplit | Deprecated: use mapPartitionsWithIndex instead.
Return a new RDD by applying a function to each partition of this RDD,
while tracking the index of the original partition.
>>> rdd = sc.parallelize([1, 2, 3, 4], 4)
>>> def f(splitIndex, iterator): yield splitIndex
>>> rdd.mapPartitionsWithSplit(f).sum()
6 | python/pyspark/rdd.py | def mapPartitionsWithSplit(self, f, preservesPartitioning=False):
"""
Deprecated: use mapPartitionsWithIndex instead.
Return a new RDD by applying a function to each partition of this RDD,
while tracking the index of the original partition.
>>> rdd = sc.parallelize([1, 2, 3, 4], 4)
>>> def f(splitIndex, iterator): yield splitIndex
>>> rdd.mapPartitionsWithSplit(f).sum()
6
"""
warnings.warn("mapPartitionsWithSplit is deprecated; "
"use mapPartitionsWithIndex instead", DeprecationWarning, stacklevel=2)
return self.mapPartitionsWithIndex(f, preservesPartitioning) | def mapPartitionsWithSplit(self, f, preservesPartitioning=False):
"""
Deprecated: use mapPartitionsWithIndex instead.
Return a new RDD by applying a function to each partition of this RDD,
while tracking the index of the original partition.
>>> rdd = sc.parallelize([1, 2, 3, 4], 4)
>>> def f(splitIndex, iterator): yield splitIndex
>>> rdd.mapPartitionsWithSplit(f).sum()
6
"""
warnings.warn("mapPartitionsWithSplit is deprecated; "
"use mapPartitionsWithIndex instead", DeprecationWarning, stacklevel=2)
return self.mapPartitionsWithIndex(f, preservesPartitioning) | [
"Deprecated",
":",
"use",
"mapPartitionsWithIndex",
"instead",
"."
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L369-L383 | [
"def",
"mapPartitionsWithSplit",
"(",
"self",
",",
"f",
",",
"preservesPartitioning",
"=",
"False",
")",
":",
"warnings",
".",
"warn",
"(",
"\"mapPartitionsWithSplit is deprecated; \"",
"\"use mapPartitionsWithIndex instead\"",
",",
"DeprecationWarning",
",",
"stacklevel",
"=",
"2",
")",
"return",
"self",
".",
"mapPartitionsWithIndex",
"(",
"f",
",",
"preservesPartitioning",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | RDD.distinct | Return a new RDD containing the distinct elements in this RDD.
>>> sorted(sc.parallelize([1, 1, 2, 3]).distinct().collect())
[1, 2, 3] | python/pyspark/rdd.py | def distinct(self, numPartitions=None):
"""
Return a new RDD containing the distinct elements in this RDD.
>>> sorted(sc.parallelize([1, 1, 2, 3]).distinct().collect())
[1, 2, 3]
"""
return self.map(lambda x: (x, None)) \
.reduceByKey(lambda x, _: x, numPartitions) \
.map(lambda x: x[0]) | def distinct(self, numPartitions=None):
"""
Return a new RDD containing the distinct elements in this RDD.
>>> sorted(sc.parallelize([1, 1, 2, 3]).distinct().collect())
[1, 2, 3]
"""
return self.map(lambda x: (x, None)) \
.reduceByKey(lambda x, _: x, numPartitions) \
.map(lambda x: x[0]) | [
"Return",
"a",
"new",
"RDD",
"containing",
"the",
"distinct",
"elements",
"in",
"this",
"RDD",
"."
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L407-L416 | [
"def",
"distinct",
"(",
"self",
",",
"numPartitions",
"=",
"None",
")",
":",
"return",
"self",
".",
"map",
"(",
"lambda",
"x",
":",
"(",
"x",
",",
"None",
")",
")",
".",
"reduceByKey",
"(",
"lambda",
"x",
",",
"_",
":",
"x",
",",
"numPartitions",
")",
".",
"map",
"(",
"lambda",
"x",
":",
"x",
"[",
"0",
"]",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | RDD.sample | Return a sampled subset of this RDD.
:param withReplacement: can elements be sampled multiple times (replaced when sampled out)
:param fraction: expected size of the sample as a fraction of this RDD's size
without replacement: probability that each element is chosen; fraction must be [0, 1]
with replacement: expected number of times each element is chosen; fraction must be >= 0
:param seed: seed for the random number generator
.. note:: This is not guaranteed to provide exactly the fraction specified of the total
count of the given :class:`DataFrame`.
>>> rdd = sc.parallelize(range(100), 4)
>>> 6 <= rdd.sample(False, 0.1, 81).count() <= 14
True | python/pyspark/rdd.py | def sample(self, withReplacement, fraction, seed=None):
"""
Return a sampled subset of this RDD.
:param withReplacement: can elements be sampled multiple times (replaced when sampled out)
:param fraction: expected size of the sample as a fraction of this RDD's size
without replacement: probability that each element is chosen; fraction must be [0, 1]
with replacement: expected number of times each element is chosen; fraction must be >= 0
:param seed: seed for the random number generator
.. note:: This is not guaranteed to provide exactly the fraction specified of the total
count of the given :class:`DataFrame`.
>>> rdd = sc.parallelize(range(100), 4)
>>> 6 <= rdd.sample(False, 0.1, 81).count() <= 14
True
"""
assert fraction >= 0.0, "Negative fraction value: %s" % fraction
return self.mapPartitionsWithIndex(RDDSampler(withReplacement, fraction, seed).func, True) | def sample(self, withReplacement, fraction, seed=None):
"""
Return a sampled subset of this RDD.
:param withReplacement: can elements be sampled multiple times (replaced when sampled out)
:param fraction: expected size of the sample as a fraction of this RDD's size
without replacement: probability that each element is chosen; fraction must be [0, 1]
with replacement: expected number of times each element is chosen; fraction must be >= 0
:param seed: seed for the random number generator
.. note:: This is not guaranteed to provide exactly the fraction specified of the total
count of the given :class:`DataFrame`.
>>> rdd = sc.parallelize(range(100), 4)
>>> 6 <= rdd.sample(False, 0.1, 81).count() <= 14
True
"""
assert fraction >= 0.0, "Negative fraction value: %s" % fraction
return self.mapPartitionsWithIndex(RDDSampler(withReplacement, fraction, seed).func, True) | [
"Return",
"a",
"sampled",
"subset",
"of",
"this",
"RDD",
"."
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L418-L436 | [
"def",
"sample",
"(",
"self",
",",
"withReplacement",
",",
"fraction",
",",
"seed",
"=",
"None",
")",
":",
"assert",
"fraction",
">=",
"0.0",
",",
"\"Negative fraction value: %s\"",
"%",
"fraction",
"return",
"self",
".",
"mapPartitionsWithIndex",
"(",
"RDDSampler",
"(",
"withReplacement",
",",
"fraction",
",",
"seed",
")",
".",
"func",
",",
"True",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | RDD.randomSplit | Randomly splits this RDD with the provided weights.
:param weights: weights for splits, will be normalized if they don't sum to 1
:param seed: random seed
:return: split RDDs in a list
>>> rdd = sc.parallelize(range(500), 1)
>>> rdd1, rdd2 = rdd.randomSplit([2, 3], 17)
>>> len(rdd1.collect() + rdd2.collect())
500
>>> 150 < rdd1.count() < 250
True
>>> 250 < rdd2.count() < 350
True | python/pyspark/rdd.py | def randomSplit(self, weights, seed=None):
"""
Randomly splits this RDD with the provided weights.
:param weights: weights for splits, will be normalized if they don't sum to 1
:param seed: random seed
:return: split RDDs in a list
>>> rdd = sc.parallelize(range(500), 1)
>>> rdd1, rdd2 = rdd.randomSplit([2, 3], 17)
>>> len(rdd1.collect() + rdd2.collect())
500
>>> 150 < rdd1.count() < 250
True
>>> 250 < rdd2.count() < 350
True
"""
s = float(sum(weights))
cweights = [0.0]
for w in weights:
cweights.append(cweights[-1] + w / s)
if seed is None:
seed = random.randint(0, 2 ** 32 - 1)
return [self.mapPartitionsWithIndex(RDDRangeSampler(lb, ub, seed).func, True)
for lb, ub in zip(cweights, cweights[1:])] | def randomSplit(self, weights, seed=None):
"""
Randomly splits this RDD with the provided weights.
:param weights: weights for splits, will be normalized if they don't sum to 1
:param seed: random seed
:return: split RDDs in a list
>>> rdd = sc.parallelize(range(500), 1)
>>> rdd1, rdd2 = rdd.randomSplit([2, 3], 17)
>>> len(rdd1.collect() + rdd2.collect())
500
>>> 150 < rdd1.count() < 250
True
>>> 250 < rdd2.count() < 350
True
"""
s = float(sum(weights))
cweights = [0.0]
for w in weights:
cweights.append(cweights[-1] + w / s)
if seed is None:
seed = random.randint(0, 2 ** 32 - 1)
return [self.mapPartitionsWithIndex(RDDRangeSampler(lb, ub, seed).func, True)
for lb, ub in zip(cweights, cweights[1:])] | [
"Randomly",
"splits",
"this",
"RDD",
"with",
"the",
"provided",
"weights",
"."
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L438-L462 | [
"def",
"randomSplit",
"(",
"self",
",",
"weights",
",",
"seed",
"=",
"None",
")",
":",
"s",
"=",
"float",
"(",
"sum",
"(",
"weights",
")",
")",
"cweights",
"=",
"[",
"0.0",
"]",
"for",
"w",
"in",
"weights",
":",
"cweights",
".",
"append",
"(",
"cweights",
"[",
"-",
"1",
"]",
"+",
"w",
"/",
"s",
")",
"if",
"seed",
"is",
"None",
":",
"seed",
"=",
"random",
".",
"randint",
"(",
"0",
",",
"2",
"**",
"32",
"-",
"1",
")",
"return",
"[",
"self",
".",
"mapPartitionsWithIndex",
"(",
"RDDRangeSampler",
"(",
"lb",
",",
"ub",
",",
"seed",
")",
".",
"func",
",",
"True",
")",
"for",
"lb",
",",
"ub",
"in",
"zip",
"(",
"cweights",
",",
"cweights",
"[",
"1",
":",
"]",
")",
"]"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | RDD.takeSample | Return a fixed-size sampled subset of this RDD.
.. note:: This method should only be used if the resulting array is expected
to be small, as all the data is loaded into the driver's memory.
>>> rdd = sc.parallelize(range(0, 10))
>>> len(rdd.takeSample(True, 20, 1))
20
>>> len(rdd.takeSample(False, 5, 2))
5
>>> len(rdd.takeSample(False, 15, 3))
10 | python/pyspark/rdd.py | def takeSample(self, withReplacement, num, seed=None):
"""
Return a fixed-size sampled subset of this RDD.
.. note:: This method should only be used if the resulting array is expected
to be small, as all the data is loaded into the driver's memory.
>>> rdd = sc.parallelize(range(0, 10))
>>> len(rdd.takeSample(True, 20, 1))
20
>>> len(rdd.takeSample(False, 5, 2))
5
>>> len(rdd.takeSample(False, 15, 3))
10
"""
numStDev = 10.0
if num < 0:
raise ValueError("Sample size cannot be negative.")
elif num == 0:
return []
initialCount = self.count()
if initialCount == 0:
return []
rand = random.Random(seed)
if (not withReplacement) and num >= initialCount:
# shuffle current RDD and return
samples = self.collect()
rand.shuffle(samples)
return samples
maxSampleSize = sys.maxsize - int(numStDev * sqrt(sys.maxsize))
if num > maxSampleSize:
raise ValueError(
"Sample size cannot be greater than %d." % maxSampleSize)
fraction = RDD._computeFractionForSampleSize(
num, initialCount, withReplacement)
samples = self.sample(withReplacement, fraction, seed).collect()
# If the first sample didn't turn out large enough, keep trying to take samples;
# this shouldn't happen often because we use a big multiplier for their initial size.
# See: scala/spark/RDD.scala
while len(samples) < num:
# TODO: add log warning for when more than one iteration was run
seed = rand.randint(0, sys.maxsize)
samples = self.sample(withReplacement, fraction, seed).collect()
rand.shuffle(samples)
return samples[0:num] | def takeSample(self, withReplacement, num, seed=None):
"""
Return a fixed-size sampled subset of this RDD.
.. note:: This method should only be used if the resulting array is expected
to be small, as all the data is loaded into the driver's memory.
>>> rdd = sc.parallelize(range(0, 10))
>>> len(rdd.takeSample(True, 20, 1))
20
>>> len(rdd.takeSample(False, 5, 2))
5
>>> len(rdd.takeSample(False, 15, 3))
10
"""
numStDev = 10.0
if num < 0:
raise ValueError("Sample size cannot be negative.")
elif num == 0:
return []
initialCount = self.count()
if initialCount == 0:
return []
rand = random.Random(seed)
if (not withReplacement) and num >= initialCount:
# shuffle current RDD and return
samples = self.collect()
rand.shuffle(samples)
return samples
maxSampleSize = sys.maxsize - int(numStDev * sqrt(sys.maxsize))
if num > maxSampleSize:
raise ValueError(
"Sample size cannot be greater than %d." % maxSampleSize)
fraction = RDD._computeFractionForSampleSize(
num, initialCount, withReplacement)
samples = self.sample(withReplacement, fraction, seed).collect()
# If the first sample didn't turn out large enough, keep trying to take samples;
# this shouldn't happen often because we use a big multiplier for their initial size.
# See: scala/spark/RDD.scala
while len(samples) < num:
# TODO: add log warning for when more than one iteration was run
seed = rand.randint(0, sys.maxsize)
samples = self.sample(withReplacement, fraction, seed).collect()
rand.shuffle(samples)
return samples[0:num] | [
"Return",
"a",
"fixed",
"-",
"size",
"sampled",
"subset",
"of",
"this",
"RDD",
"."
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L465-L518 | [
"def",
"takeSample",
"(",
"self",
",",
"withReplacement",
",",
"num",
",",
"seed",
"=",
"None",
")",
":",
"numStDev",
"=",
"10.0",
"if",
"num",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"Sample size cannot be negative.\"",
")",
"elif",
"num",
"==",
"0",
":",
"return",
"[",
"]",
"initialCount",
"=",
"self",
".",
"count",
"(",
")",
"if",
"initialCount",
"==",
"0",
":",
"return",
"[",
"]",
"rand",
"=",
"random",
".",
"Random",
"(",
"seed",
")",
"if",
"(",
"not",
"withReplacement",
")",
"and",
"num",
">=",
"initialCount",
":",
"# shuffle current RDD and return",
"samples",
"=",
"self",
".",
"collect",
"(",
")",
"rand",
".",
"shuffle",
"(",
"samples",
")",
"return",
"samples",
"maxSampleSize",
"=",
"sys",
".",
"maxsize",
"-",
"int",
"(",
"numStDev",
"*",
"sqrt",
"(",
"sys",
".",
"maxsize",
")",
")",
"if",
"num",
">",
"maxSampleSize",
":",
"raise",
"ValueError",
"(",
"\"Sample size cannot be greater than %d.\"",
"%",
"maxSampleSize",
")",
"fraction",
"=",
"RDD",
".",
"_computeFractionForSampleSize",
"(",
"num",
",",
"initialCount",
",",
"withReplacement",
")",
"samples",
"=",
"self",
".",
"sample",
"(",
"withReplacement",
",",
"fraction",
",",
"seed",
")",
".",
"collect",
"(",
")",
"# If the first sample didn't turn out large enough, keep trying to take samples;",
"# this shouldn't happen often because we use a big multiplier for their initial size.",
"# See: scala/spark/RDD.scala",
"while",
"len",
"(",
"samples",
")",
"<",
"num",
":",
"# TODO: add log warning for when more than one iteration was run",
"seed",
"=",
"rand",
".",
"randint",
"(",
"0",
",",
"sys",
".",
"maxsize",
")",
"samples",
"=",
"self",
".",
"sample",
"(",
"withReplacement",
",",
"fraction",
",",
"seed",
")",
".",
"collect",
"(",
")",
"rand",
".",
"shuffle",
"(",
"samples",
")",
"return",
"samples",
"[",
"0",
":",
"num",
"]"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | RDD._computeFractionForSampleSize | Returns a sampling rate that guarantees a sample of
size >= sampleSizeLowerBound 99.99% of the time.
How the sampling rate is determined:
Let p = num / total, where num is the sample size and total is the
total number of data points in the RDD. We're trying to compute
q > p such that
- when sampling with replacement, we're drawing each data point
with prob_i ~ Pois(q), where we want to guarantee
Pr[s < num] < 0.0001 for s = sum(prob_i for i from 0 to
total), i.e. the failure rate of not having a sufficiently large
sample < 0.0001. Setting q = p + 5 * sqrt(p/total) is sufficient
to guarantee 0.9999 success rate for num > 12, but we need a
slightly larger q (9 empirically determined).
- when sampling without replacement, we're drawing each data point
with prob_i ~ Binomial(total, fraction) and our choice of q
guarantees 1-delta, or 0.9999 success rate, where success rate is
defined the same as in sampling with replacement. | python/pyspark/rdd.py | def _computeFractionForSampleSize(sampleSizeLowerBound, total, withReplacement):
"""
Returns a sampling rate that guarantees a sample of
size >= sampleSizeLowerBound 99.99% of the time.
How the sampling rate is determined:
Let p = num / total, where num is the sample size and total is the
total number of data points in the RDD. We're trying to compute
q > p such that
- when sampling with replacement, we're drawing each data point
with prob_i ~ Pois(q), where we want to guarantee
Pr[s < num] < 0.0001 for s = sum(prob_i for i from 0 to
total), i.e. the failure rate of not having a sufficiently large
sample < 0.0001. Setting q = p + 5 * sqrt(p/total) is sufficient
to guarantee 0.9999 success rate for num > 12, but we need a
slightly larger q (9 empirically determined).
- when sampling without replacement, we're drawing each data point
with prob_i ~ Binomial(total, fraction) and our choice of q
guarantees 1-delta, or 0.9999 success rate, where success rate is
defined the same as in sampling with replacement.
"""
fraction = float(sampleSizeLowerBound) / total
if withReplacement:
numStDev = 5
if (sampleSizeLowerBound < 12):
numStDev = 9
return fraction + numStDev * sqrt(fraction / total)
else:
delta = 0.00005
gamma = - log(delta) / total
return min(1, fraction + gamma + sqrt(gamma * gamma + 2 * gamma * fraction)) | def _computeFractionForSampleSize(sampleSizeLowerBound, total, withReplacement):
"""
Returns a sampling rate that guarantees a sample of
size >= sampleSizeLowerBound 99.99% of the time.
How the sampling rate is determined:
Let p = num / total, where num is the sample size and total is the
total number of data points in the RDD. We're trying to compute
q > p such that
- when sampling with replacement, we're drawing each data point
with prob_i ~ Pois(q), where we want to guarantee
Pr[s < num] < 0.0001 for s = sum(prob_i for i from 0 to
total), i.e. the failure rate of not having a sufficiently large
sample < 0.0001. Setting q = p + 5 * sqrt(p/total) is sufficient
to guarantee 0.9999 success rate for num > 12, but we need a
slightly larger q (9 empirically determined).
- when sampling without replacement, we're drawing each data point
with prob_i ~ Binomial(total, fraction) and our choice of q
guarantees 1-delta, or 0.9999 success rate, where success rate is
defined the same as in sampling with replacement.
"""
fraction = float(sampleSizeLowerBound) / total
if withReplacement:
numStDev = 5
if (sampleSizeLowerBound < 12):
numStDev = 9
return fraction + numStDev * sqrt(fraction / total)
else:
delta = 0.00005
gamma = - log(delta) / total
return min(1, fraction + gamma + sqrt(gamma * gamma + 2 * gamma * fraction)) | [
"Returns",
"a",
"sampling",
"rate",
"that",
"guarantees",
"a",
"sample",
"of",
"size",
">",
"=",
"sampleSizeLowerBound",
"99",
".",
"99%",
"of",
"the",
"time",
"."
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L521-L551 | [
"def",
"_computeFractionForSampleSize",
"(",
"sampleSizeLowerBound",
",",
"total",
",",
"withReplacement",
")",
":",
"fraction",
"=",
"float",
"(",
"sampleSizeLowerBound",
")",
"/",
"total",
"if",
"withReplacement",
":",
"numStDev",
"=",
"5",
"if",
"(",
"sampleSizeLowerBound",
"<",
"12",
")",
":",
"numStDev",
"=",
"9",
"return",
"fraction",
"+",
"numStDev",
"*",
"sqrt",
"(",
"fraction",
"/",
"total",
")",
"else",
":",
"delta",
"=",
"0.00005",
"gamma",
"=",
"-",
"log",
"(",
"delta",
")",
"/",
"total",
"return",
"min",
"(",
"1",
",",
"fraction",
"+",
"gamma",
"+",
"sqrt",
"(",
"gamma",
"*",
"gamma",
"+",
"2",
"*",
"gamma",
"*",
"fraction",
")",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | RDD.union | Return the union of this RDD and another one.
>>> rdd = sc.parallelize([1, 1, 2, 3])
>>> rdd.union(rdd).collect()
[1, 1, 2, 3, 1, 1, 2, 3] | python/pyspark/rdd.py | def union(self, other):
"""
Return the union of this RDD and another one.
>>> rdd = sc.parallelize([1, 1, 2, 3])
>>> rdd.union(rdd).collect()
[1, 1, 2, 3, 1, 1, 2, 3]
"""
if self._jrdd_deserializer == other._jrdd_deserializer:
rdd = RDD(self._jrdd.union(other._jrdd), self.ctx,
self._jrdd_deserializer)
else:
# These RDDs contain data in different serialized formats, so we
# must normalize them to the default serializer.
self_copy = self._reserialize()
other_copy = other._reserialize()
rdd = RDD(self_copy._jrdd.union(other_copy._jrdd), self.ctx,
self.ctx.serializer)
if (self.partitioner == other.partitioner and
self.getNumPartitions() == rdd.getNumPartitions()):
rdd.partitioner = self.partitioner
return rdd | def union(self, other):
"""
Return the union of this RDD and another one.
>>> rdd = sc.parallelize([1, 1, 2, 3])
>>> rdd.union(rdd).collect()
[1, 1, 2, 3, 1, 1, 2, 3]
"""
if self._jrdd_deserializer == other._jrdd_deserializer:
rdd = RDD(self._jrdd.union(other._jrdd), self.ctx,
self._jrdd_deserializer)
else:
# These RDDs contain data in different serialized formats, so we
# must normalize them to the default serializer.
self_copy = self._reserialize()
other_copy = other._reserialize()
rdd = RDD(self_copy._jrdd.union(other_copy._jrdd), self.ctx,
self.ctx.serializer)
if (self.partitioner == other.partitioner and
self.getNumPartitions() == rdd.getNumPartitions()):
rdd.partitioner = self.partitioner
return rdd | [
"Return",
"the",
"union",
"of",
"this",
"RDD",
"and",
"another",
"one",
"."
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L553-L574 | [
"def",
"union",
"(",
"self",
",",
"other",
")",
":",
"if",
"self",
".",
"_jrdd_deserializer",
"==",
"other",
".",
"_jrdd_deserializer",
":",
"rdd",
"=",
"RDD",
"(",
"self",
".",
"_jrdd",
".",
"union",
"(",
"other",
".",
"_jrdd",
")",
",",
"self",
".",
"ctx",
",",
"self",
".",
"_jrdd_deserializer",
")",
"else",
":",
"# These RDDs contain data in different serialized formats, so we",
"# must normalize them to the default serializer.",
"self_copy",
"=",
"self",
".",
"_reserialize",
"(",
")",
"other_copy",
"=",
"other",
".",
"_reserialize",
"(",
")",
"rdd",
"=",
"RDD",
"(",
"self_copy",
".",
"_jrdd",
".",
"union",
"(",
"other_copy",
".",
"_jrdd",
")",
",",
"self",
".",
"ctx",
",",
"self",
".",
"ctx",
".",
"serializer",
")",
"if",
"(",
"self",
".",
"partitioner",
"==",
"other",
".",
"partitioner",
"and",
"self",
".",
"getNumPartitions",
"(",
")",
"==",
"rdd",
".",
"getNumPartitions",
"(",
")",
")",
":",
"rdd",
".",
"partitioner",
"=",
"self",
".",
"partitioner",
"return",
"rdd"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | RDD.intersection | Return the intersection of this RDD and another one. The output will
not contain any duplicate elements, even if the input RDDs did.
.. note:: This method performs a shuffle internally.
>>> rdd1 = sc.parallelize([1, 10, 2, 3, 4, 5])
>>> rdd2 = sc.parallelize([1, 6, 2, 3, 7, 8])
>>> rdd1.intersection(rdd2).collect()
[1, 2, 3] | python/pyspark/rdd.py | def intersection(self, other):
"""
Return the intersection of this RDD and another one. The output will
not contain any duplicate elements, even if the input RDDs did.
.. note:: This method performs a shuffle internally.
>>> rdd1 = sc.parallelize([1, 10, 2, 3, 4, 5])
>>> rdd2 = sc.parallelize([1, 6, 2, 3, 7, 8])
>>> rdd1.intersection(rdd2).collect()
[1, 2, 3]
"""
return self.map(lambda v: (v, None)) \
.cogroup(other.map(lambda v: (v, None))) \
.filter(lambda k_vs: all(k_vs[1])) \
.keys() | def intersection(self, other):
"""
Return the intersection of this RDD and another one. The output will
not contain any duplicate elements, even if the input RDDs did.
.. note:: This method performs a shuffle internally.
>>> rdd1 = sc.parallelize([1, 10, 2, 3, 4, 5])
>>> rdd2 = sc.parallelize([1, 6, 2, 3, 7, 8])
>>> rdd1.intersection(rdd2).collect()
[1, 2, 3]
"""
return self.map(lambda v: (v, None)) \
.cogroup(other.map(lambda v: (v, None))) \
.filter(lambda k_vs: all(k_vs[1])) \
.keys() | [
"Return",
"the",
"intersection",
"of",
"this",
"RDD",
"and",
"another",
"one",
".",
"The",
"output",
"will",
"not",
"contain",
"any",
"duplicate",
"elements",
"even",
"if",
"the",
"input",
"RDDs",
"did",
"."
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L576-L591 | [
"def",
"intersection",
"(",
"self",
",",
"other",
")",
":",
"return",
"self",
".",
"map",
"(",
"lambda",
"v",
":",
"(",
"v",
",",
"None",
")",
")",
".",
"cogroup",
"(",
"other",
".",
"map",
"(",
"lambda",
"v",
":",
"(",
"v",
",",
"None",
")",
")",
")",
".",
"filter",
"(",
"lambda",
"k_vs",
":",
"all",
"(",
"k_vs",
"[",
"1",
"]",
")",
")",
".",
"keys",
"(",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | RDD.repartitionAndSortWithinPartitions | Repartition the RDD according to the given partitioner and, within each resulting partition,
sort records by their keys.
>>> rdd = sc.parallelize([(0, 5), (3, 8), (2, 6), (0, 8), (3, 8), (1, 3)])
>>> rdd2 = rdd.repartitionAndSortWithinPartitions(2, lambda x: x % 2, True)
>>> rdd2.glom().collect()
[[(0, 5), (0, 8), (2, 6)], [(1, 3), (3, 8), (3, 8)]] | python/pyspark/rdd.py | def repartitionAndSortWithinPartitions(self, numPartitions=None, partitionFunc=portable_hash,
ascending=True, keyfunc=lambda x: x):
"""
Repartition the RDD according to the given partitioner and, within each resulting partition,
sort records by their keys.
>>> rdd = sc.parallelize([(0, 5), (3, 8), (2, 6), (0, 8), (3, 8), (1, 3)])
>>> rdd2 = rdd.repartitionAndSortWithinPartitions(2, lambda x: x % 2, True)
>>> rdd2.glom().collect()
[[(0, 5), (0, 8), (2, 6)], [(1, 3), (3, 8), (3, 8)]]
"""
if numPartitions is None:
numPartitions = self._defaultReducePartitions()
memory = _parse_memory(self.ctx._conf.get("spark.python.worker.memory", "512m"))
serializer = self._jrdd_deserializer
def sortPartition(iterator):
sort = ExternalSorter(memory * 0.9, serializer).sorted
return iter(sort(iterator, key=lambda k_v: keyfunc(k_v[0]), reverse=(not ascending)))
return self.partitionBy(numPartitions, partitionFunc).mapPartitions(sortPartition, True) | def repartitionAndSortWithinPartitions(self, numPartitions=None, partitionFunc=portable_hash,
ascending=True, keyfunc=lambda x: x):
"""
Repartition the RDD according to the given partitioner and, within each resulting partition,
sort records by their keys.
>>> rdd = sc.parallelize([(0, 5), (3, 8), (2, 6), (0, 8), (3, 8), (1, 3)])
>>> rdd2 = rdd.repartitionAndSortWithinPartitions(2, lambda x: x % 2, True)
>>> rdd2.glom().collect()
[[(0, 5), (0, 8), (2, 6)], [(1, 3), (3, 8), (3, 8)]]
"""
if numPartitions is None:
numPartitions = self._defaultReducePartitions()
memory = _parse_memory(self.ctx._conf.get("spark.python.worker.memory", "512m"))
serializer = self._jrdd_deserializer
def sortPartition(iterator):
sort = ExternalSorter(memory * 0.9, serializer).sorted
return iter(sort(iterator, key=lambda k_v: keyfunc(k_v[0]), reverse=(not ascending)))
return self.partitionBy(numPartitions, partitionFunc).mapPartitions(sortPartition, True) | [
"Repartition",
"the",
"RDD",
"according",
"to",
"the",
"given",
"partitioner",
"and",
"within",
"each",
"resulting",
"partition",
"sort",
"records",
"by",
"their",
"keys",
"."
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L612-L633 | [
"def",
"repartitionAndSortWithinPartitions",
"(",
"self",
",",
"numPartitions",
"=",
"None",
",",
"partitionFunc",
"=",
"portable_hash",
",",
"ascending",
"=",
"True",
",",
"keyfunc",
"=",
"lambda",
"x",
":",
"x",
")",
":",
"if",
"numPartitions",
"is",
"None",
":",
"numPartitions",
"=",
"self",
".",
"_defaultReducePartitions",
"(",
")",
"memory",
"=",
"_parse_memory",
"(",
"self",
".",
"ctx",
".",
"_conf",
".",
"get",
"(",
"\"spark.python.worker.memory\"",
",",
"\"512m\"",
")",
")",
"serializer",
"=",
"self",
".",
"_jrdd_deserializer",
"def",
"sortPartition",
"(",
"iterator",
")",
":",
"sort",
"=",
"ExternalSorter",
"(",
"memory",
"*",
"0.9",
",",
"serializer",
")",
".",
"sorted",
"return",
"iter",
"(",
"sort",
"(",
"iterator",
",",
"key",
"=",
"lambda",
"k_v",
":",
"keyfunc",
"(",
"k_v",
"[",
"0",
"]",
")",
",",
"reverse",
"=",
"(",
"not",
"ascending",
")",
")",
")",
"return",
"self",
".",
"partitionBy",
"(",
"numPartitions",
",",
"partitionFunc",
")",
".",
"mapPartitions",
"(",
"sortPartition",
",",
"True",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | RDD.sortByKey | Sorts this RDD, which is assumed to consist of (key, value) pairs.
>>> tmp = [('a', 1), ('b', 2), ('1', 3), ('d', 4), ('2', 5)]
>>> sc.parallelize(tmp).sortByKey().first()
('1', 3)
>>> sc.parallelize(tmp).sortByKey(True, 1).collect()
[('1', 3), ('2', 5), ('a', 1), ('b', 2), ('d', 4)]
>>> sc.parallelize(tmp).sortByKey(True, 2).collect()
[('1', 3), ('2', 5), ('a', 1), ('b', 2), ('d', 4)]
>>> tmp2 = [('Mary', 1), ('had', 2), ('a', 3), ('little', 4), ('lamb', 5)]
>>> tmp2.extend([('whose', 6), ('fleece', 7), ('was', 8), ('white', 9)])
>>> sc.parallelize(tmp2).sortByKey(True, 3, keyfunc=lambda k: k.lower()).collect()
[('a', 3), ('fleece', 7), ('had', 2), ('lamb', 5),...('white', 9), ('whose', 6)] | python/pyspark/rdd.py | def sortByKey(self, ascending=True, numPartitions=None, keyfunc=lambda x: x):
"""
Sorts this RDD, which is assumed to consist of (key, value) pairs.
>>> tmp = [('a', 1), ('b', 2), ('1', 3), ('d', 4), ('2', 5)]
>>> sc.parallelize(tmp).sortByKey().first()
('1', 3)
>>> sc.parallelize(tmp).sortByKey(True, 1).collect()
[('1', 3), ('2', 5), ('a', 1), ('b', 2), ('d', 4)]
>>> sc.parallelize(tmp).sortByKey(True, 2).collect()
[('1', 3), ('2', 5), ('a', 1), ('b', 2), ('d', 4)]
>>> tmp2 = [('Mary', 1), ('had', 2), ('a', 3), ('little', 4), ('lamb', 5)]
>>> tmp2.extend([('whose', 6), ('fleece', 7), ('was', 8), ('white', 9)])
>>> sc.parallelize(tmp2).sortByKey(True, 3, keyfunc=lambda k: k.lower()).collect()
[('a', 3), ('fleece', 7), ('had', 2), ('lamb', 5),...('white', 9), ('whose', 6)]
"""
if numPartitions is None:
numPartitions = self._defaultReducePartitions()
memory = self._memory_limit()
serializer = self._jrdd_deserializer
def sortPartition(iterator):
sort = ExternalSorter(memory * 0.9, serializer).sorted
return iter(sort(iterator, key=lambda kv: keyfunc(kv[0]), reverse=(not ascending)))
if numPartitions == 1:
if self.getNumPartitions() > 1:
self = self.coalesce(1)
return self.mapPartitions(sortPartition, True)
# first compute the boundary of each part via sampling: we want to partition
# the key-space into bins such that the bins have roughly the same
# number of (key, value) pairs falling into them
rddSize = self.count()
if not rddSize:
return self # empty RDD
maxSampleSize = numPartitions * 20.0 # constant from Spark's RangePartitioner
fraction = min(maxSampleSize / max(rddSize, 1), 1.0)
samples = self.sample(False, fraction, 1).map(lambda kv: kv[0]).collect()
samples = sorted(samples, key=keyfunc)
# we have numPartitions many parts but one of the them has
# an implicit boundary
bounds = [samples[int(len(samples) * (i + 1) / numPartitions)]
for i in range(0, numPartitions - 1)]
def rangePartitioner(k):
p = bisect.bisect_left(bounds, keyfunc(k))
if ascending:
return p
else:
return numPartitions - 1 - p
return self.partitionBy(numPartitions, rangePartitioner).mapPartitions(sortPartition, True) | def sortByKey(self, ascending=True, numPartitions=None, keyfunc=lambda x: x):
"""
Sorts this RDD, which is assumed to consist of (key, value) pairs.
>>> tmp = [('a', 1), ('b', 2), ('1', 3), ('d', 4), ('2', 5)]
>>> sc.parallelize(tmp).sortByKey().first()
('1', 3)
>>> sc.parallelize(tmp).sortByKey(True, 1).collect()
[('1', 3), ('2', 5), ('a', 1), ('b', 2), ('d', 4)]
>>> sc.parallelize(tmp).sortByKey(True, 2).collect()
[('1', 3), ('2', 5), ('a', 1), ('b', 2), ('d', 4)]
>>> tmp2 = [('Mary', 1), ('had', 2), ('a', 3), ('little', 4), ('lamb', 5)]
>>> tmp2.extend([('whose', 6), ('fleece', 7), ('was', 8), ('white', 9)])
>>> sc.parallelize(tmp2).sortByKey(True, 3, keyfunc=lambda k: k.lower()).collect()
[('a', 3), ('fleece', 7), ('had', 2), ('lamb', 5),...('white', 9), ('whose', 6)]
"""
if numPartitions is None:
numPartitions = self._defaultReducePartitions()
memory = self._memory_limit()
serializer = self._jrdd_deserializer
def sortPartition(iterator):
sort = ExternalSorter(memory * 0.9, serializer).sorted
return iter(sort(iterator, key=lambda kv: keyfunc(kv[0]), reverse=(not ascending)))
if numPartitions == 1:
if self.getNumPartitions() > 1:
self = self.coalesce(1)
return self.mapPartitions(sortPartition, True)
# first compute the boundary of each part via sampling: we want to partition
# the key-space into bins such that the bins have roughly the same
# number of (key, value) pairs falling into them
rddSize = self.count()
if not rddSize:
return self # empty RDD
maxSampleSize = numPartitions * 20.0 # constant from Spark's RangePartitioner
fraction = min(maxSampleSize / max(rddSize, 1), 1.0)
samples = self.sample(False, fraction, 1).map(lambda kv: kv[0]).collect()
samples = sorted(samples, key=keyfunc)
# we have numPartitions many parts but one of the them has
# an implicit boundary
bounds = [samples[int(len(samples) * (i + 1) / numPartitions)]
for i in range(0, numPartitions - 1)]
def rangePartitioner(k):
p = bisect.bisect_left(bounds, keyfunc(k))
if ascending:
return p
else:
return numPartitions - 1 - p
return self.partitionBy(numPartitions, rangePartitioner).mapPartitions(sortPartition, True) | [
"Sorts",
"this",
"RDD",
"which",
"is",
"assumed",
"to",
"consist",
"of",
"(",
"key",
"value",
")",
"pairs",
"."
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L635-L689 | [
"def",
"sortByKey",
"(",
"self",
",",
"ascending",
"=",
"True",
",",
"numPartitions",
"=",
"None",
",",
"keyfunc",
"=",
"lambda",
"x",
":",
"x",
")",
":",
"if",
"numPartitions",
"is",
"None",
":",
"numPartitions",
"=",
"self",
".",
"_defaultReducePartitions",
"(",
")",
"memory",
"=",
"self",
".",
"_memory_limit",
"(",
")",
"serializer",
"=",
"self",
".",
"_jrdd_deserializer",
"def",
"sortPartition",
"(",
"iterator",
")",
":",
"sort",
"=",
"ExternalSorter",
"(",
"memory",
"*",
"0.9",
",",
"serializer",
")",
".",
"sorted",
"return",
"iter",
"(",
"sort",
"(",
"iterator",
",",
"key",
"=",
"lambda",
"kv",
":",
"keyfunc",
"(",
"kv",
"[",
"0",
"]",
")",
",",
"reverse",
"=",
"(",
"not",
"ascending",
")",
")",
")",
"if",
"numPartitions",
"==",
"1",
":",
"if",
"self",
".",
"getNumPartitions",
"(",
")",
">",
"1",
":",
"self",
"=",
"self",
".",
"coalesce",
"(",
"1",
")",
"return",
"self",
".",
"mapPartitions",
"(",
"sortPartition",
",",
"True",
")",
"# first compute the boundary of each part via sampling: we want to partition",
"# the key-space into bins such that the bins have roughly the same",
"# number of (key, value) pairs falling into them",
"rddSize",
"=",
"self",
".",
"count",
"(",
")",
"if",
"not",
"rddSize",
":",
"return",
"self",
"# empty RDD",
"maxSampleSize",
"=",
"numPartitions",
"*",
"20.0",
"# constant from Spark's RangePartitioner",
"fraction",
"=",
"min",
"(",
"maxSampleSize",
"/",
"max",
"(",
"rddSize",
",",
"1",
")",
",",
"1.0",
")",
"samples",
"=",
"self",
".",
"sample",
"(",
"False",
",",
"fraction",
",",
"1",
")",
".",
"map",
"(",
"lambda",
"kv",
":",
"kv",
"[",
"0",
"]",
")",
".",
"collect",
"(",
")",
"samples",
"=",
"sorted",
"(",
"samples",
",",
"key",
"=",
"keyfunc",
")",
"# we have numPartitions many parts but one of the them has",
"# an implicit boundary",
"bounds",
"=",
"[",
"samples",
"[",
"int",
"(",
"len",
"(",
"samples",
")",
"*",
"(",
"i",
"+",
"1",
")",
"/",
"numPartitions",
")",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"numPartitions",
"-",
"1",
")",
"]",
"def",
"rangePartitioner",
"(",
"k",
")",
":",
"p",
"=",
"bisect",
".",
"bisect_left",
"(",
"bounds",
",",
"keyfunc",
"(",
"k",
")",
")",
"if",
"ascending",
":",
"return",
"p",
"else",
":",
"return",
"numPartitions",
"-",
"1",
"-",
"p",
"return",
"self",
".",
"partitionBy",
"(",
"numPartitions",
",",
"rangePartitioner",
")",
".",
"mapPartitions",
"(",
"sortPartition",
",",
"True",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | RDD.sortBy | Sorts this RDD by the given keyfunc
>>> tmp = [('a', 1), ('b', 2), ('1', 3), ('d', 4), ('2', 5)]
>>> sc.parallelize(tmp).sortBy(lambda x: x[0]).collect()
[('1', 3), ('2', 5), ('a', 1), ('b', 2), ('d', 4)]
>>> sc.parallelize(tmp).sortBy(lambda x: x[1]).collect()
[('a', 1), ('b', 2), ('1', 3), ('d', 4), ('2', 5)] | python/pyspark/rdd.py | def sortBy(self, keyfunc, ascending=True, numPartitions=None):
"""
Sorts this RDD by the given keyfunc
>>> tmp = [('a', 1), ('b', 2), ('1', 3), ('d', 4), ('2', 5)]
>>> sc.parallelize(tmp).sortBy(lambda x: x[0]).collect()
[('1', 3), ('2', 5), ('a', 1), ('b', 2), ('d', 4)]
>>> sc.parallelize(tmp).sortBy(lambda x: x[1]).collect()
[('a', 1), ('b', 2), ('1', 3), ('d', 4), ('2', 5)]
"""
return self.keyBy(keyfunc).sortByKey(ascending, numPartitions).values() | def sortBy(self, keyfunc, ascending=True, numPartitions=None):
"""
Sorts this RDD by the given keyfunc
>>> tmp = [('a', 1), ('b', 2), ('1', 3), ('d', 4), ('2', 5)]
>>> sc.parallelize(tmp).sortBy(lambda x: x[0]).collect()
[('1', 3), ('2', 5), ('a', 1), ('b', 2), ('d', 4)]
>>> sc.parallelize(tmp).sortBy(lambda x: x[1]).collect()
[('a', 1), ('b', 2), ('1', 3), ('d', 4), ('2', 5)]
"""
return self.keyBy(keyfunc).sortByKey(ascending, numPartitions).values() | [
"Sorts",
"this",
"RDD",
"by",
"the",
"given",
"keyfunc"
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L691-L701 | [
"def",
"sortBy",
"(",
"self",
",",
"keyfunc",
",",
"ascending",
"=",
"True",
",",
"numPartitions",
"=",
"None",
")",
":",
"return",
"self",
".",
"keyBy",
"(",
"keyfunc",
")",
".",
"sortByKey",
"(",
"ascending",
",",
"numPartitions",
")",
".",
"values",
"(",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | RDD.cartesian | Return the Cartesian product of this RDD and another one, that is, the
RDD of all pairs of elements C{(a, b)} where C{a} is in C{self} and
C{b} is in C{other}.
>>> rdd = sc.parallelize([1, 2])
>>> sorted(rdd.cartesian(rdd).collect())
[(1, 1), (1, 2), (2, 1), (2, 2)] | python/pyspark/rdd.py | def cartesian(self, other):
"""
Return the Cartesian product of this RDD and another one, that is, the
RDD of all pairs of elements C{(a, b)} where C{a} is in C{self} and
C{b} is in C{other}.
>>> rdd = sc.parallelize([1, 2])
>>> sorted(rdd.cartesian(rdd).collect())
[(1, 1), (1, 2), (2, 1), (2, 2)]
"""
# Due to batching, we can't use the Java cartesian method.
deserializer = CartesianDeserializer(self._jrdd_deserializer,
other._jrdd_deserializer)
return RDD(self._jrdd.cartesian(other._jrdd), self.ctx, deserializer) | def cartesian(self, other):
"""
Return the Cartesian product of this RDD and another one, that is, the
RDD of all pairs of elements C{(a, b)} where C{a} is in C{self} and
C{b} is in C{other}.
>>> rdd = sc.parallelize([1, 2])
>>> sorted(rdd.cartesian(rdd).collect())
[(1, 1), (1, 2), (2, 1), (2, 2)]
"""
# Due to batching, we can't use the Java cartesian method.
deserializer = CartesianDeserializer(self._jrdd_deserializer,
other._jrdd_deserializer)
return RDD(self._jrdd.cartesian(other._jrdd), self.ctx, deserializer) | [
"Return",
"the",
"Cartesian",
"product",
"of",
"this",
"RDD",
"and",
"another",
"one",
"that",
"is",
"the",
"RDD",
"of",
"all",
"pairs",
"of",
"elements",
"C",
"{",
"(",
"a",
"b",
")",
"}",
"where",
"C",
"{",
"a",
"}",
"is",
"in",
"C",
"{",
"self",
"}",
"and",
"C",
"{",
"b",
"}",
"is",
"in",
"C",
"{",
"other",
"}",
"."
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L716-L729 | [
"def",
"cartesian",
"(",
"self",
",",
"other",
")",
":",
"# Due to batching, we can't use the Java cartesian method.",
"deserializer",
"=",
"CartesianDeserializer",
"(",
"self",
".",
"_jrdd_deserializer",
",",
"other",
".",
"_jrdd_deserializer",
")",
"return",
"RDD",
"(",
"self",
".",
"_jrdd",
".",
"cartesian",
"(",
"other",
".",
"_jrdd",
")",
",",
"self",
".",
"ctx",
",",
"deserializer",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | RDD.groupBy | Return an RDD of grouped items.
>>> rdd = sc.parallelize([1, 1, 2, 3, 5, 8])
>>> result = rdd.groupBy(lambda x: x % 2).collect()
>>> sorted([(x, sorted(y)) for (x, y) in result])
[(0, [2, 8]), (1, [1, 1, 3, 5])] | python/pyspark/rdd.py | def groupBy(self, f, numPartitions=None, partitionFunc=portable_hash):
"""
Return an RDD of grouped items.
>>> rdd = sc.parallelize([1, 1, 2, 3, 5, 8])
>>> result = rdd.groupBy(lambda x: x % 2).collect()
>>> sorted([(x, sorted(y)) for (x, y) in result])
[(0, [2, 8]), (1, [1, 1, 3, 5])]
"""
return self.map(lambda x: (f(x), x)).groupByKey(numPartitions, partitionFunc) | def groupBy(self, f, numPartitions=None, partitionFunc=portable_hash):
"""
Return an RDD of grouped items.
>>> rdd = sc.parallelize([1, 1, 2, 3, 5, 8])
>>> result = rdd.groupBy(lambda x: x % 2).collect()
>>> sorted([(x, sorted(y)) for (x, y) in result])
[(0, [2, 8]), (1, [1, 1, 3, 5])]
"""
return self.map(lambda x: (f(x), x)).groupByKey(numPartitions, partitionFunc) | [
"Return",
"an",
"RDD",
"of",
"grouped",
"items",
"."
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L731-L740 | [
"def",
"groupBy",
"(",
"self",
",",
"f",
",",
"numPartitions",
"=",
"None",
",",
"partitionFunc",
"=",
"portable_hash",
")",
":",
"return",
"self",
".",
"map",
"(",
"lambda",
"x",
":",
"(",
"f",
"(",
"x",
")",
",",
"x",
")",
")",
".",
"groupByKey",
"(",
"numPartitions",
",",
"partitionFunc",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | RDD.pipe | Return an RDD created by piping elements to a forked external process.
>>> sc.parallelize(['1', '2', '', '3']).pipe('cat').collect()
[u'1', u'2', u'', u'3']
:param checkCode: whether or not to check the return value of the shell command. | python/pyspark/rdd.py | def pipe(self, command, env=None, checkCode=False):
"""
Return an RDD created by piping elements to a forked external process.
>>> sc.parallelize(['1', '2', '', '3']).pipe('cat').collect()
[u'1', u'2', u'', u'3']
:param checkCode: whether or not to check the return value of the shell command.
"""
if env is None:
env = dict()
def func(iterator):
pipe = Popen(
shlex.split(command), env=env, stdin=PIPE, stdout=PIPE)
def pipe_objs(out):
for obj in iterator:
s = unicode(obj).rstrip('\n') + '\n'
out.write(s.encode('utf-8'))
out.close()
Thread(target=pipe_objs, args=[pipe.stdin]).start()
def check_return_code():
pipe.wait()
if checkCode and pipe.returncode:
raise Exception("Pipe function `%s' exited "
"with error code %d" % (command, pipe.returncode))
else:
for i in range(0):
yield i
return (x.rstrip(b'\n').decode('utf-8') for x in
chain(iter(pipe.stdout.readline, b''), check_return_code()))
return self.mapPartitions(func) | def pipe(self, command, env=None, checkCode=False):
"""
Return an RDD created by piping elements to a forked external process.
>>> sc.parallelize(['1', '2', '', '3']).pipe('cat').collect()
[u'1', u'2', u'', u'3']
:param checkCode: whether or not to check the return value of the shell command.
"""
if env is None:
env = dict()
def func(iterator):
pipe = Popen(
shlex.split(command), env=env, stdin=PIPE, stdout=PIPE)
def pipe_objs(out):
for obj in iterator:
s = unicode(obj).rstrip('\n') + '\n'
out.write(s.encode('utf-8'))
out.close()
Thread(target=pipe_objs, args=[pipe.stdin]).start()
def check_return_code():
pipe.wait()
if checkCode and pipe.returncode:
raise Exception("Pipe function `%s' exited "
"with error code %d" % (command, pipe.returncode))
else:
for i in range(0):
yield i
return (x.rstrip(b'\n').decode('utf-8') for x in
chain(iter(pipe.stdout.readline, b''), check_return_code()))
return self.mapPartitions(func) | [
"Return",
"an",
"RDD",
"created",
"by",
"piping",
"elements",
"to",
"a",
"forked",
"external",
"process",
"."
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L743-L776 | [
"def",
"pipe",
"(",
"self",
",",
"command",
",",
"env",
"=",
"None",
",",
"checkCode",
"=",
"False",
")",
":",
"if",
"env",
"is",
"None",
":",
"env",
"=",
"dict",
"(",
")",
"def",
"func",
"(",
"iterator",
")",
":",
"pipe",
"=",
"Popen",
"(",
"shlex",
".",
"split",
"(",
"command",
")",
",",
"env",
"=",
"env",
",",
"stdin",
"=",
"PIPE",
",",
"stdout",
"=",
"PIPE",
")",
"def",
"pipe_objs",
"(",
"out",
")",
":",
"for",
"obj",
"in",
"iterator",
":",
"s",
"=",
"unicode",
"(",
"obj",
")",
".",
"rstrip",
"(",
"'\\n'",
")",
"+",
"'\\n'",
"out",
".",
"write",
"(",
"s",
".",
"encode",
"(",
"'utf-8'",
")",
")",
"out",
".",
"close",
"(",
")",
"Thread",
"(",
"target",
"=",
"pipe_objs",
",",
"args",
"=",
"[",
"pipe",
".",
"stdin",
"]",
")",
".",
"start",
"(",
")",
"def",
"check_return_code",
"(",
")",
":",
"pipe",
".",
"wait",
"(",
")",
"if",
"checkCode",
"and",
"pipe",
".",
"returncode",
":",
"raise",
"Exception",
"(",
"\"Pipe function `%s' exited \"",
"\"with error code %d\"",
"%",
"(",
"command",
",",
"pipe",
".",
"returncode",
")",
")",
"else",
":",
"for",
"i",
"in",
"range",
"(",
"0",
")",
":",
"yield",
"i",
"return",
"(",
"x",
".",
"rstrip",
"(",
"b'\\n'",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"for",
"x",
"in",
"chain",
"(",
"iter",
"(",
"pipe",
".",
"stdout",
".",
"readline",
",",
"b''",
")",
",",
"check_return_code",
"(",
")",
")",
")",
"return",
"self",
".",
"mapPartitions",
"(",
"func",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | RDD.foreach | Applies a function to all elements of this RDD.
>>> def f(x): print(x)
>>> sc.parallelize([1, 2, 3, 4, 5]).foreach(f) | python/pyspark/rdd.py | def foreach(self, f):
"""
Applies a function to all elements of this RDD.
>>> def f(x): print(x)
>>> sc.parallelize([1, 2, 3, 4, 5]).foreach(f)
"""
f = fail_on_stopiteration(f)
def processPartition(iterator):
for x in iterator:
f(x)
return iter([])
self.mapPartitions(processPartition).count() | def foreach(self, f):
"""
Applies a function to all elements of this RDD.
>>> def f(x): print(x)
>>> sc.parallelize([1, 2, 3, 4, 5]).foreach(f)
"""
f = fail_on_stopiteration(f)
def processPartition(iterator):
for x in iterator:
f(x)
return iter([])
self.mapPartitions(processPartition).count() | [
"Applies",
"a",
"function",
"to",
"all",
"elements",
"of",
"this",
"RDD",
"."
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L778-L791 | [
"def",
"foreach",
"(",
"self",
",",
"f",
")",
":",
"f",
"=",
"fail_on_stopiteration",
"(",
"f",
")",
"def",
"processPartition",
"(",
"iterator",
")",
":",
"for",
"x",
"in",
"iterator",
":",
"f",
"(",
"x",
")",
"return",
"iter",
"(",
"[",
"]",
")",
"self",
".",
"mapPartitions",
"(",
"processPartition",
")",
".",
"count",
"(",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | RDD.foreachPartition | Applies a function to each partition of this RDD.
>>> def f(iterator):
... for x in iterator:
... print(x)
>>> sc.parallelize([1, 2, 3, 4, 5]).foreachPartition(f) | python/pyspark/rdd.py | def foreachPartition(self, f):
"""
Applies a function to each partition of this RDD.
>>> def f(iterator):
... for x in iterator:
... print(x)
>>> sc.parallelize([1, 2, 3, 4, 5]).foreachPartition(f)
"""
def func(it):
r = f(it)
try:
return iter(r)
except TypeError:
return iter([])
self.mapPartitions(func).count() | def foreachPartition(self, f):
"""
Applies a function to each partition of this RDD.
>>> def f(iterator):
... for x in iterator:
... print(x)
>>> sc.parallelize([1, 2, 3, 4, 5]).foreachPartition(f)
"""
def func(it):
r = f(it)
try:
return iter(r)
except TypeError:
return iter([])
self.mapPartitions(func).count() | [
"Applies",
"a",
"function",
"to",
"each",
"partition",
"of",
"this",
"RDD",
"."
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L793-L808 | [
"def",
"foreachPartition",
"(",
"self",
",",
"f",
")",
":",
"def",
"func",
"(",
"it",
")",
":",
"r",
"=",
"f",
"(",
"it",
")",
"try",
":",
"return",
"iter",
"(",
"r",
")",
"except",
"TypeError",
":",
"return",
"iter",
"(",
"[",
"]",
")",
"self",
".",
"mapPartitions",
"(",
"func",
")",
".",
"count",
"(",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | RDD.collect | Return a list that contains all of the elements in this RDD.
.. note:: This method should only be used if the resulting array is expected
to be small, as all the data is loaded into the driver's memory. | python/pyspark/rdd.py | def collect(self):
"""
Return a list that contains all of the elements in this RDD.
.. note:: This method should only be used if the resulting array is expected
to be small, as all the data is loaded into the driver's memory.
"""
with SCCallSiteSync(self.context) as css:
sock_info = self.ctx._jvm.PythonRDD.collectAndServe(self._jrdd.rdd())
return list(_load_from_socket(sock_info, self._jrdd_deserializer)) | def collect(self):
"""
Return a list that contains all of the elements in this RDD.
.. note:: This method should only be used if the resulting array is expected
to be small, as all the data is loaded into the driver's memory.
"""
with SCCallSiteSync(self.context) as css:
sock_info = self.ctx._jvm.PythonRDD.collectAndServe(self._jrdd.rdd())
return list(_load_from_socket(sock_info, self._jrdd_deserializer)) | [
"Return",
"a",
"list",
"that",
"contains",
"all",
"of",
"the",
"elements",
"in",
"this",
"RDD",
"."
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L810-L819 | [
"def",
"collect",
"(",
"self",
")",
":",
"with",
"SCCallSiteSync",
"(",
"self",
".",
"context",
")",
"as",
"css",
":",
"sock_info",
"=",
"self",
".",
"ctx",
".",
"_jvm",
".",
"PythonRDD",
".",
"collectAndServe",
"(",
"self",
".",
"_jrdd",
".",
"rdd",
"(",
")",
")",
"return",
"list",
"(",
"_load_from_socket",
"(",
"sock_info",
",",
"self",
".",
"_jrdd_deserializer",
")",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | RDD.reduce | Reduces the elements of this RDD using the specified commutative and
associative binary operator. Currently reduces partitions locally.
>>> from operator import add
>>> sc.parallelize([1, 2, 3, 4, 5]).reduce(add)
15
>>> sc.parallelize((2 for _ in range(10))).map(lambda x: 1).cache().reduce(add)
10
>>> sc.parallelize([]).reduce(add)
Traceback (most recent call last):
...
ValueError: Can not reduce() empty RDD | python/pyspark/rdd.py | def reduce(self, f):
"""
Reduces the elements of this RDD using the specified commutative and
associative binary operator. Currently reduces partitions locally.
>>> from operator import add
>>> sc.parallelize([1, 2, 3, 4, 5]).reduce(add)
15
>>> sc.parallelize((2 for _ in range(10))).map(lambda x: 1).cache().reduce(add)
10
>>> sc.parallelize([]).reduce(add)
Traceback (most recent call last):
...
ValueError: Can not reduce() empty RDD
"""
f = fail_on_stopiteration(f)
def func(iterator):
iterator = iter(iterator)
try:
initial = next(iterator)
except StopIteration:
return
yield reduce(f, iterator, initial)
vals = self.mapPartitions(func).collect()
if vals:
return reduce(f, vals)
raise ValueError("Can not reduce() empty RDD") | def reduce(self, f):
"""
Reduces the elements of this RDD using the specified commutative and
associative binary operator. Currently reduces partitions locally.
>>> from operator import add
>>> sc.parallelize([1, 2, 3, 4, 5]).reduce(add)
15
>>> sc.parallelize((2 for _ in range(10))).map(lambda x: 1).cache().reduce(add)
10
>>> sc.parallelize([]).reduce(add)
Traceback (most recent call last):
...
ValueError: Can not reduce() empty RDD
"""
f = fail_on_stopiteration(f)
def func(iterator):
iterator = iter(iterator)
try:
initial = next(iterator)
except StopIteration:
return
yield reduce(f, iterator, initial)
vals = self.mapPartitions(func).collect()
if vals:
return reduce(f, vals)
raise ValueError("Can not reduce() empty RDD") | [
"Reduces",
"the",
"elements",
"of",
"this",
"RDD",
"using",
"the",
"specified",
"commutative",
"and",
"associative",
"binary",
"operator",
".",
"Currently",
"reduces",
"partitions",
"locally",
"."
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L821-L849 | [
"def",
"reduce",
"(",
"self",
",",
"f",
")",
":",
"f",
"=",
"fail_on_stopiteration",
"(",
"f",
")",
"def",
"func",
"(",
"iterator",
")",
":",
"iterator",
"=",
"iter",
"(",
"iterator",
")",
"try",
":",
"initial",
"=",
"next",
"(",
"iterator",
")",
"except",
"StopIteration",
":",
"return",
"yield",
"reduce",
"(",
"f",
",",
"iterator",
",",
"initial",
")",
"vals",
"=",
"self",
".",
"mapPartitions",
"(",
"func",
")",
".",
"collect",
"(",
")",
"if",
"vals",
":",
"return",
"reduce",
"(",
"f",
",",
"vals",
")",
"raise",
"ValueError",
"(",
"\"Can not reduce() empty RDD\"",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | RDD.treeReduce | Reduces the elements of this RDD in a multi-level tree pattern.
:param depth: suggested depth of the tree (default: 2)
>>> add = lambda x, y: x + y
>>> rdd = sc.parallelize([-5, -4, -3, -2, -1, 1, 2, 3, 4], 10)
>>> rdd.treeReduce(add)
-5
>>> rdd.treeReduce(add, 1)
-5
>>> rdd.treeReduce(add, 2)
-5
>>> rdd.treeReduce(add, 5)
-5
>>> rdd.treeReduce(add, 10)
-5 | python/pyspark/rdd.py | def treeReduce(self, f, depth=2):
"""
Reduces the elements of this RDD in a multi-level tree pattern.
:param depth: suggested depth of the tree (default: 2)
>>> add = lambda x, y: x + y
>>> rdd = sc.parallelize([-5, -4, -3, -2, -1, 1, 2, 3, 4], 10)
>>> rdd.treeReduce(add)
-5
>>> rdd.treeReduce(add, 1)
-5
>>> rdd.treeReduce(add, 2)
-5
>>> rdd.treeReduce(add, 5)
-5
>>> rdd.treeReduce(add, 10)
-5
"""
if depth < 1:
raise ValueError("Depth cannot be smaller than 1 but got %d." % depth)
zeroValue = None, True # Use the second entry to indicate whether this is a dummy value.
def op(x, y):
if x[1]:
return y
elif y[1]:
return x
else:
return f(x[0], y[0]), False
reduced = self.map(lambda x: (x, False)).treeAggregate(zeroValue, op, op, depth)
if reduced[1]:
raise ValueError("Cannot reduce empty RDD.")
return reduced[0] | def treeReduce(self, f, depth=2):
"""
Reduces the elements of this RDD in a multi-level tree pattern.
:param depth: suggested depth of the tree (default: 2)
>>> add = lambda x, y: x + y
>>> rdd = sc.parallelize([-5, -4, -3, -2, -1, 1, 2, 3, 4], 10)
>>> rdd.treeReduce(add)
-5
>>> rdd.treeReduce(add, 1)
-5
>>> rdd.treeReduce(add, 2)
-5
>>> rdd.treeReduce(add, 5)
-5
>>> rdd.treeReduce(add, 10)
-5
"""
if depth < 1:
raise ValueError("Depth cannot be smaller than 1 but got %d." % depth)
zeroValue = None, True # Use the second entry to indicate whether this is a dummy value.
def op(x, y):
if x[1]:
return y
elif y[1]:
return x
else:
return f(x[0], y[0]), False
reduced = self.map(lambda x: (x, False)).treeAggregate(zeroValue, op, op, depth)
if reduced[1]:
raise ValueError("Cannot reduce empty RDD.")
return reduced[0] | [
"Reduces",
"the",
"elements",
"of",
"this",
"RDD",
"in",
"a",
"multi",
"-",
"level",
"tree",
"pattern",
"."
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L851-L886 | [
"def",
"treeReduce",
"(",
"self",
",",
"f",
",",
"depth",
"=",
"2",
")",
":",
"if",
"depth",
"<",
"1",
":",
"raise",
"ValueError",
"(",
"\"Depth cannot be smaller than 1 but got %d.\"",
"%",
"depth",
")",
"zeroValue",
"=",
"None",
",",
"True",
"# Use the second entry to indicate whether this is a dummy value.",
"def",
"op",
"(",
"x",
",",
"y",
")",
":",
"if",
"x",
"[",
"1",
"]",
":",
"return",
"y",
"elif",
"y",
"[",
"1",
"]",
":",
"return",
"x",
"else",
":",
"return",
"f",
"(",
"x",
"[",
"0",
"]",
",",
"y",
"[",
"0",
"]",
")",
",",
"False",
"reduced",
"=",
"self",
".",
"map",
"(",
"lambda",
"x",
":",
"(",
"x",
",",
"False",
")",
")",
".",
"treeAggregate",
"(",
"zeroValue",
",",
"op",
",",
"op",
",",
"depth",
")",
"if",
"reduced",
"[",
"1",
"]",
":",
"raise",
"ValueError",
"(",
"\"Cannot reduce empty RDD.\"",
")",
"return",
"reduced",
"[",
"0",
"]"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | RDD.fold | Aggregate the elements of each partition, and then the results for all
the partitions, using a given associative function and a neutral "zero value."
The function C{op(t1, t2)} is allowed to modify C{t1} and return it
as its result value to avoid object allocation; however, it should not
modify C{t2}.
This behaves somewhat differently from fold operations implemented
for non-distributed collections in functional languages like Scala.
This fold operation may be applied to partitions individually, and then
fold those results into the final result, rather than apply the fold
to each element sequentially in some defined ordering. For functions
that are not commutative, the result may differ from that of a fold
applied to a non-distributed collection.
>>> from operator import add
>>> sc.parallelize([1, 2, 3, 4, 5]).fold(0, add)
15 | python/pyspark/rdd.py | def fold(self, zeroValue, op):
"""
Aggregate the elements of each partition, and then the results for all
the partitions, using a given associative function and a neutral "zero value."
The function C{op(t1, t2)} is allowed to modify C{t1} and return it
as its result value to avoid object allocation; however, it should not
modify C{t2}.
This behaves somewhat differently from fold operations implemented
for non-distributed collections in functional languages like Scala.
This fold operation may be applied to partitions individually, and then
fold those results into the final result, rather than apply the fold
to each element sequentially in some defined ordering. For functions
that are not commutative, the result may differ from that of a fold
applied to a non-distributed collection.
>>> from operator import add
>>> sc.parallelize([1, 2, 3, 4, 5]).fold(0, add)
15
"""
op = fail_on_stopiteration(op)
def func(iterator):
acc = zeroValue
for obj in iterator:
acc = op(acc, obj)
yield acc
# collecting result of mapPartitions here ensures that the copy of
# zeroValue provided to each partition is unique from the one provided
# to the final reduce call
vals = self.mapPartitions(func).collect()
return reduce(op, vals, zeroValue) | def fold(self, zeroValue, op):
"""
Aggregate the elements of each partition, and then the results for all
the partitions, using a given associative function and a neutral "zero value."
The function C{op(t1, t2)} is allowed to modify C{t1} and return it
as its result value to avoid object allocation; however, it should not
modify C{t2}.
This behaves somewhat differently from fold operations implemented
for non-distributed collections in functional languages like Scala.
This fold operation may be applied to partitions individually, and then
fold those results into the final result, rather than apply the fold
to each element sequentially in some defined ordering. For functions
that are not commutative, the result may differ from that of a fold
applied to a non-distributed collection.
>>> from operator import add
>>> sc.parallelize([1, 2, 3, 4, 5]).fold(0, add)
15
"""
op = fail_on_stopiteration(op)
def func(iterator):
acc = zeroValue
for obj in iterator:
acc = op(acc, obj)
yield acc
# collecting result of mapPartitions here ensures that the copy of
# zeroValue provided to each partition is unique from the one provided
# to the final reduce call
vals = self.mapPartitions(func).collect()
return reduce(op, vals, zeroValue) | [
"Aggregate",
"the",
"elements",
"of",
"each",
"partition",
"and",
"then",
"the",
"results",
"for",
"all",
"the",
"partitions",
"using",
"a",
"given",
"associative",
"function",
"and",
"a",
"neutral",
"zero",
"value",
"."
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L888-L920 | [
"def",
"fold",
"(",
"self",
",",
"zeroValue",
",",
"op",
")",
":",
"op",
"=",
"fail_on_stopiteration",
"(",
"op",
")",
"def",
"func",
"(",
"iterator",
")",
":",
"acc",
"=",
"zeroValue",
"for",
"obj",
"in",
"iterator",
":",
"acc",
"=",
"op",
"(",
"acc",
",",
"obj",
")",
"yield",
"acc",
"# collecting result of mapPartitions here ensures that the copy of",
"# zeroValue provided to each partition is unique from the one provided",
"# to the final reduce call",
"vals",
"=",
"self",
".",
"mapPartitions",
"(",
"func",
")",
".",
"collect",
"(",
")",
"return",
"reduce",
"(",
"op",
",",
"vals",
",",
"zeroValue",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | RDD.aggregate | Aggregate the elements of each partition, and then the results for all
the partitions, using a given combine functions and a neutral "zero
value."
The functions C{op(t1, t2)} is allowed to modify C{t1} and return it
as its result value to avoid object allocation; however, it should not
modify C{t2}.
The first function (seqOp) can return a different result type, U, than
the type of this RDD. Thus, we need one operation for merging a T into
an U and one operation for merging two U
>>> seqOp = (lambda x, y: (x[0] + y, x[1] + 1))
>>> combOp = (lambda x, y: (x[0] + y[0], x[1] + y[1]))
>>> sc.parallelize([1, 2, 3, 4]).aggregate((0, 0), seqOp, combOp)
(10, 4)
>>> sc.parallelize([]).aggregate((0, 0), seqOp, combOp)
(0, 0) | python/pyspark/rdd.py | def aggregate(self, zeroValue, seqOp, combOp):
"""
Aggregate the elements of each partition, and then the results for all
the partitions, using a given combine functions and a neutral "zero
value."
The functions C{op(t1, t2)} is allowed to modify C{t1} and return it
as its result value to avoid object allocation; however, it should not
modify C{t2}.
The first function (seqOp) can return a different result type, U, than
the type of this RDD. Thus, we need one operation for merging a T into
an U and one operation for merging two U
>>> seqOp = (lambda x, y: (x[0] + y, x[1] + 1))
>>> combOp = (lambda x, y: (x[0] + y[0], x[1] + y[1]))
>>> sc.parallelize([1, 2, 3, 4]).aggregate((0, 0), seqOp, combOp)
(10, 4)
>>> sc.parallelize([]).aggregate((0, 0), seqOp, combOp)
(0, 0)
"""
seqOp = fail_on_stopiteration(seqOp)
combOp = fail_on_stopiteration(combOp)
def func(iterator):
acc = zeroValue
for obj in iterator:
acc = seqOp(acc, obj)
yield acc
# collecting result of mapPartitions here ensures that the copy of
# zeroValue provided to each partition is unique from the one provided
# to the final reduce call
vals = self.mapPartitions(func).collect()
return reduce(combOp, vals, zeroValue) | def aggregate(self, zeroValue, seqOp, combOp):
"""
Aggregate the elements of each partition, and then the results for all
the partitions, using a given combine functions and a neutral "zero
value."
The functions C{op(t1, t2)} is allowed to modify C{t1} and return it
as its result value to avoid object allocation; however, it should not
modify C{t2}.
The first function (seqOp) can return a different result type, U, than
the type of this RDD. Thus, we need one operation for merging a T into
an U and one operation for merging two U
>>> seqOp = (lambda x, y: (x[0] + y, x[1] + 1))
>>> combOp = (lambda x, y: (x[0] + y[0], x[1] + y[1]))
>>> sc.parallelize([1, 2, 3, 4]).aggregate((0, 0), seqOp, combOp)
(10, 4)
>>> sc.parallelize([]).aggregate((0, 0), seqOp, combOp)
(0, 0)
"""
seqOp = fail_on_stopiteration(seqOp)
combOp = fail_on_stopiteration(combOp)
def func(iterator):
acc = zeroValue
for obj in iterator:
acc = seqOp(acc, obj)
yield acc
# collecting result of mapPartitions here ensures that the copy of
# zeroValue provided to each partition is unique from the one provided
# to the final reduce call
vals = self.mapPartitions(func).collect()
return reduce(combOp, vals, zeroValue) | [
"Aggregate",
"the",
"elements",
"of",
"each",
"partition",
"and",
"then",
"the",
"results",
"for",
"all",
"the",
"partitions",
"using",
"a",
"given",
"combine",
"functions",
"and",
"a",
"neutral",
"zero",
"value",
"."
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L922-L955 | [
"def",
"aggregate",
"(",
"self",
",",
"zeroValue",
",",
"seqOp",
",",
"combOp",
")",
":",
"seqOp",
"=",
"fail_on_stopiteration",
"(",
"seqOp",
")",
"combOp",
"=",
"fail_on_stopiteration",
"(",
"combOp",
")",
"def",
"func",
"(",
"iterator",
")",
":",
"acc",
"=",
"zeroValue",
"for",
"obj",
"in",
"iterator",
":",
"acc",
"=",
"seqOp",
"(",
"acc",
",",
"obj",
")",
"yield",
"acc",
"# collecting result of mapPartitions here ensures that the copy of",
"# zeroValue provided to each partition is unique from the one provided",
"# to the final reduce call",
"vals",
"=",
"self",
".",
"mapPartitions",
"(",
"func",
")",
".",
"collect",
"(",
")",
"return",
"reduce",
"(",
"combOp",
",",
"vals",
",",
"zeroValue",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | RDD.treeAggregate | Aggregates the elements of this RDD in a multi-level tree
pattern.
:param depth: suggested depth of the tree (default: 2)
>>> add = lambda x, y: x + y
>>> rdd = sc.parallelize([-5, -4, -3, -2, -1, 1, 2, 3, 4], 10)
>>> rdd.treeAggregate(0, add, add)
-5
>>> rdd.treeAggregate(0, add, add, 1)
-5
>>> rdd.treeAggregate(0, add, add, 2)
-5
>>> rdd.treeAggregate(0, add, add, 5)
-5
>>> rdd.treeAggregate(0, add, add, 10)
-5 | python/pyspark/rdd.py | def treeAggregate(self, zeroValue, seqOp, combOp, depth=2):
"""
Aggregates the elements of this RDD in a multi-level tree
pattern.
:param depth: suggested depth of the tree (default: 2)
>>> add = lambda x, y: x + y
>>> rdd = sc.parallelize([-5, -4, -3, -2, -1, 1, 2, 3, 4], 10)
>>> rdd.treeAggregate(0, add, add)
-5
>>> rdd.treeAggregate(0, add, add, 1)
-5
>>> rdd.treeAggregate(0, add, add, 2)
-5
>>> rdd.treeAggregate(0, add, add, 5)
-5
>>> rdd.treeAggregate(0, add, add, 10)
-5
"""
if depth < 1:
raise ValueError("Depth cannot be smaller than 1 but got %d." % depth)
if self.getNumPartitions() == 0:
return zeroValue
def aggregatePartition(iterator):
acc = zeroValue
for obj in iterator:
acc = seqOp(acc, obj)
yield acc
partiallyAggregated = self.mapPartitions(aggregatePartition)
numPartitions = partiallyAggregated.getNumPartitions()
scale = max(int(ceil(pow(numPartitions, 1.0 / depth))), 2)
# If creating an extra level doesn't help reduce the wall-clock time, we stop the tree
# aggregation.
while numPartitions > scale + numPartitions / scale:
numPartitions /= scale
curNumPartitions = int(numPartitions)
def mapPartition(i, iterator):
for obj in iterator:
yield (i % curNumPartitions, obj)
partiallyAggregated = partiallyAggregated \
.mapPartitionsWithIndex(mapPartition) \
.reduceByKey(combOp, curNumPartitions) \
.values()
return partiallyAggregated.reduce(combOp) | def treeAggregate(self, zeroValue, seqOp, combOp, depth=2):
"""
Aggregates the elements of this RDD in a multi-level tree
pattern.
:param depth: suggested depth of the tree (default: 2)
>>> add = lambda x, y: x + y
>>> rdd = sc.parallelize([-5, -4, -3, -2, -1, 1, 2, 3, 4], 10)
>>> rdd.treeAggregate(0, add, add)
-5
>>> rdd.treeAggregate(0, add, add, 1)
-5
>>> rdd.treeAggregate(0, add, add, 2)
-5
>>> rdd.treeAggregate(0, add, add, 5)
-5
>>> rdd.treeAggregate(0, add, add, 10)
-5
"""
if depth < 1:
raise ValueError("Depth cannot be smaller than 1 but got %d." % depth)
if self.getNumPartitions() == 0:
return zeroValue
def aggregatePartition(iterator):
acc = zeroValue
for obj in iterator:
acc = seqOp(acc, obj)
yield acc
partiallyAggregated = self.mapPartitions(aggregatePartition)
numPartitions = partiallyAggregated.getNumPartitions()
scale = max(int(ceil(pow(numPartitions, 1.0 / depth))), 2)
# If creating an extra level doesn't help reduce the wall-clock time, we stop the tree
# aggregation.
while numPartitions > scale + numPartitions / scale:
numPartitions /= scale
curNumPartitions = int(numPartitions)
def mapPartition(i, iterator):
for obj in iterator:
yield (i % curNumPartitions, obj)
partiallyAggregated = partiallyAggregated \
.mapPartitionsWithIndex(mapPartition) \
.reduceByKey(combOp, curNumPartitions) \
.values()
return partiallyAggregated.reduce(combOp) | [
"Aggregates",
"the",
"elements",
"of",
"this",
"RDD",
"in",
"a",
"multi",
"-",
"level",
"tree",
"pattern",
"."
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L957-L1007 | [
"def",
"treeAggregate",
"(",
"self",
",",
"zeroValue",
",",
"seqOp",
",",
"combOp",
",",
"depth",
"=",
"2",
")",
":",
"if",
"depth",
"<",
"1",
":",
"raise",
"ValueError",
"(",
"\"Depth cannot be smaller than 1 but got %d.\"",
"%",
"depth",
")",
"if",
"self",
".",
"getNumPartitions",
"(",
")",
"==",
"0",
":",
"return",
"zeroValue",
"def",
"aggregatePartition",
"(",
"iterator",
")",
":",
"acc",
"=",
"zeroValue",
"for",
"obj",
"in",
"iterator",
":",
"acc",
"=",
"seqOp",
"(",
"acc",
",",
"obj",
")",
"yield",
"acc",
"partiallyAggregated",
"=",
"self",
".",
"mapPartitions",
"(",
"aggregatePartition",
")",
"numPartitions",
"=",
"partiallyAggregated",
".",
"getNumPartitions",
"(",
")",
"scale",
"=",
"max",
"(",
"int",
"(",
"ceil",
"(",
"pow",
"(",
"numPartitions",
",",
"1.0",
"/",
"depth",
")",
")",
")",
",",
"2",
")",
"# If creating an extra level doesn't help reduce the wall-clock time, we stop the tree",
"# aggregation.",
"while",
"numPartitions",
">",
"scale",
"+",
"numPartitions",
"/",
"scale",
":",
"numPartitions",
"/=",
"scale",
"curNumPartitions",
"=",
"int",
"(",
"numPartitions",
")",
"def",
"mapPartition",
"(",
"i",
",",
"iterator",
")",
":",
"for",
"obj",
"in",
"iterator",
":",
"yield",
"(",
"i",
"%",
"curNumPartitions",
",",
"obj",
")",
"partiallyAggregated",
"=",
"partiallyAggregated",
".",
"mapPartitionsWithIndex",
"(",
"mapPartition",
")",
".",
"reduceByKey",
"(",
"combOp",
",",
"curNumPartitions",
")",
".",
"values",
"(",
")",
"return",
"partiallyAggregated",
".",
"reduce",
"(",
"combOp",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | RDD.max | Find the maximum item in this RDD.
:param key: A function used to generate key for comparing
>>> rdd = sc.parallelize([1.0, 5.0, 43.0, 10.0])
>>> rdd.max()
43.0
>>> rdd.max(key=str)
5.0 | python/pyspark/rdd.py | def max(self, key=None):
"""
Find the maximum item in this RDD.
:param key: A function used to generate key for comparing
>>> rdd = sc.parallelize([1.0, 5.0, 43.0, 10.0])
>>> rdd.max()
43.0
>>> rdd.max(key=str)
5.0
"""
if key is None:
return self.reduce(max)
return self.reduce(lambda a, b: max(a, b, key=key)) | def max(self, key=None):
"""
Find the maximum item in this RDD.
:param key: A function used to generate key for comparing
>>> rdd = sc.parallelize([1.0, 5.0, 43.0, 10.0])
>>> rdd.max()
43.0
>>> rdd.max(key=str)
5.0
"""
if key is None:
return self.reduce(max)
return self.reduce(lambda a, b: max(a, b, key=key)) | [
"Find",
"the",
"maximum",
"item",
"in",
"this",
"RDD",
"."
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L1009-L1023 | [
"def",
"max",
"(",
"self",
",",
"key",
"=",
"None",
")",
":",
"if",
"key",
"is",
"None",
":",
"return",
"self",
".",
"reduce",
"(",
"max",
")",
"return",
"self",
".",
"reduce",
"(",
"lambda",
"a",
",",
"b",
":",
"max",
"(",
"a",
",",
"b",
",",
"key",
"=",
"key",
")",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | RDD.min | Find the minimum item in this RDD.
:param key: A function used to generate key for comparing
>>> rdd = sc.parallelize([2.0, 5.0, 43.0, 10.0])
>>> rdd.min()
2.0
>>> rdd.min(key=str)
10.0 | python/pyspark/rdd.py | def min(self, key=None):
"""
Find the minimum item in this RDD.
:param key: A function used to generate key for comparing
>>> rdd = sc.parallelize([2.0, 5.0, 43.0, 10.0])
>>> rdd.min()
2.0
>>> rdd.min(key=str)
10.0
"""
if key is None:
return self.reduce(min)
return self.reduce(lambda a, b: min(a, b, key=key)) | def min(self, key=None):
"""
Find the minimum item in this RDD.
:param key: A function used to generate key for comparing
>>> rdd = sc.parallelize([2.0, 5.0, 43.0, 10.0])
>>> rdd.min()
2.0
>>> rdd.min(key=str)
10.0
"""
if key is None:
return self.reduce(min)
return self.reduce(lambda a, b: min(a, b, key=key)) | [
"Find",
"the",
"minimum",
"item",
"in",
"this",
"RDD",
"."
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L1025-L1039 | [
"def",
"min",
"(",
"self",
",",
"key",
"=",
"None",
")",
":",
"if",
"key",
"is",
"None",
":",
"return",
"self",
".",
"reduce",
"(",
"min",
")",
"return",
"self",
".",
"reduce",
"(",
"lambda",
"a",
",",
"b",
":",
"min",
"(",
"a",
",",
"b",
",",
"key",
"=",
"key",
")",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | RDD.sum | Add up the elements in this RDD.
>>> sc.parallelize([1.0, 2.0, 3.0]).sum()
6.0 | python/pyspark/rdd.py | def sum(self):
"""
Add up the elements in this RDD.
>>> sc.parallelize([1.0, 2.0, 3.0]).sum()
6.0
"""
return self.mapPartitions(lambda x: [sum(x)]).fold(0, operator.add) | def sum(self):
"""
Add up the elements in this RDD.
>>> sc.parallelize([1.0, 2.0, 3.0]).sum()
6.0
"""
return self.mapPartitions(lambda x: [sum(x)]).fold(0, operator.add) | [
"Add",
"up",
"the",
"elements",
"in",
"this",
"RDD",
"."
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L1041-L1048 | [
"def",
"sum",
"(",
"self",
")",
":",
"return",
"self",
".",
"mapPartitions",
"(",
"lambda",
"x",
":",
"[",
"sum",
"(",
"x",
")",
"]",
")",
".",
"fold",
"(",
"0",
",",
"operator",
".",
"add",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | RDD.stats | Return a L{StatCounter} object that captures the mean, variance
and count of the RDD's elements in one operation. | python/pyspark/rdd.py | def stats(self):
"""
Return a L{StatCounter} object that captures the mean, variance
and count of the RDD's elements in one operation.
"""
def redFunc(left_counter, right_counter):
return left_counter.mergeStats(right_counter)
return self.mapPartitions(lambda i: [StatCounter(i)]).reduce(redFunc) | def stats(self):
"""
Return a L{StatCounter} object that captures the mean, variance
and count of the RDD's elements in one operation.
"""
def redFunc(left_counter, right_counter):
return left_counter.mergeStats(right_counter)
return self.mapPartitions(lambda i: [StatCounter(i)]).reduce(redFunc) | [
"Return",
"a",
"L",
"{",
"StatCounter",
"}",
"object",
"that",
"captures",
"the",
"mean",
"variance",
"and",
"count",
"of",
"the",
"RDD",
"s",
"elements",
"in",
"one",
"operation",
"."
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L1059-L1067 | [
"def",
"stats",
"(",
"self",
")",
":",
"def",
"redFunc",
"(",
"left_counter",
",",
"right_counter",
")",
":",
"return",
"left_counter",
".",
"mergeStats",
"(",
"right_counter",
")",
"return",
"self",
".",
"mapPartitions",
"(",
"lambda",
"i",
":",
"[",
"StatCounter",
"(",
"i",
")",
"]",
")",
".",
"reduce",
"(",
"redFunc",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | RDD.histogram | Compute a histogram using the provided buckets. The buckets
are all open to the right except for the last which is closed.
e.g. [1,10,20,50] means the buckets are [1,10) [10,20) [20,50],
which means 1<=x<10, 10<=x<20, 20<=x<=50. And on the input of 1
and 50 we would have a histogram of 1,0,1.
If your histogram is evenly spaced (e.g. [0, 10, 20, 30]),
this can be switched from an O(log n) inseration to O(1) per
element (where n is the number of buckets).
Buckets must be sorted, not contain any duplicates, and have
at least two elements.
If `buckets` is a number, it will generate buckets which are
evenly spaced between the minimum and maximum of the RDD. For
example, if the min value is 0 and the max is 100, given `buckets`
as 2, the resulting buckets will be [0,50) [50,100]. `buckets` must
be at least 1. An exception is raised if the RDD contains infinity.
If the elements in the RDD do not vary (max == min), a single bucket
will be used.
The return value is a tuple of buckets and histogram.
>>> rdd = sc.parallelize(range(51))
>>> rdd.histogram(2)
([0, 25, 50], [25, 26])
>>> rdd.histogram([0, 5, 25, 50])
([0, 5, 25, 50], [5, 20, 26])
>>> rdd.histogram([0, 15, 30, 45, 60]) # evenly spaced buckets
([0, 15, 30, 45, 60], [15, 15, 15, 6])
>>> rdd = sc.parallelize(["ab", "ac", "b", "bd", "ef"])
>>> rdd.histogram(("a", "b", "c"))
(('a', 'b', 'c'), [2, 2]) | python/pyspark/rdd.py | def histogram(self, buckets):
"""
Compute a histogram using the provided buckets. The buckets
are all open to the right except for the last which is closed.
e.g. [1,10,20,50] means the buckets are [1,10) [10,20) [20,50],
which means 1<=x<10, 10<=x<20, 20<=x<=50. And on the input of 1
and 50 we would have a histogram of 1,0,1.
If your histogram is evenly spaced (e.g. [0, 10, 20, 30]),
this can be switched from an O(log n) inseration to O(1) per
element (where n is the number of buckets).
Buckets must be sorted, not contain any duplicates, and have
at least two elements.
If `buckets` is a number, it will generate buckets which are
evenly spaced between the minimum and maximum of the RDD. For
example, if the min value is 0 and the max is 100, given `buckets`
as 2, the resulting buckets will be [0,50) [50,100]. `buckets` must
be at least 1. An exception is raised if the RDD contains infinity.
If the elements in the RDD do not vary (max == min), a single bucket
will be used.
The return value is a tuple of buckets and histogram.
>>> rdd = sc.parallelize(range(51))
>>> rdd.histogram(2)
([0, 25, 50], [25, 26])
>>> rdd.histogram([0, 5, 25, 50])
([0, 5, 25, 50], [5, 20, 26])
>>> rdd.histogram([0, 15, 30, 45, 60]) # evenly spaced buckets
([0, 15, 30, 45, 60], [15, 15, 15, 6])
>>> rdd = sc.parallelize(["ab", "ac", "b", "bd", "ef"])
>>> rdd.histogram(("a", "b", "c"))
(('a', 'b', 'c'), [2, 2])
"""
if isinstance(buckets, int):
if buckets < 1:
raise ValueError("number of buckets must be >= 1")
# filter out non-comparable elements
def comparable(x):
if x is None:
return False
if type(x) is float and isnan(x):
return False
return True
filtered = self.filter(comparable)
# faster than stats()
def minmax(a, b):
return min(a[0], b[0]), max(a[1], b[1])
try:
minv, maxv = filtered.map(lambda x: (x, x)).reduce(minmax)
except TypeError as e:
if " empty " in str(e):
raise ValueError("can not generate buckets from empty RDD")
raise
if minv == maxv or buckets == 1:
return [minv, maxv], [filtered.count()]
try:
inc = (maxv - minv) / buckets
except TypeError:
raise TypeError("Can not generate buckets with non-number in RDD")
if isinf(inc):
raise ValueError("Can not generate buckets with infinite value")
# keep them as integer if possible
inc = int(inc)
if inc * buckets != maxv - minv:
inc = (maxv - minv) * 1.0 / buckets
buckets = [i * inc + minv for i in range(buckets)]
buckets.append(maxv) # fix accumulated error
even = True
elif isinstance(buckets, (list, tuple)):
if len(buckets) < 2:
raise ValueError("buckets should have more than one value")
if any(i is None or isinstance(i, float) and isnan(i) for i in buckets):
raise ValueError("can not have None or NaN in buckets")
if sorted(buckets) != list(buckets):
raise ValueError("buckets should be sorted")
if len(set(buckets)) != len(buckets):
raise ValueError("buckets should not contain duplicated values")
minv = buckets[0]
maxv = buckets[-1]
even = False
inc = None
try:
steps = [buckets[i + 1] - buckets[i] for i in range(len(buckets) - 1)]
except TypeError:
pass # objects in buckets do not support '-'
else:
if max(steps) - min(steps) < 1e-10: # handle precision errors
even = True
inc = (maxv - minv) / (len(buckets) - 1)
else:
raise TypeError("buckets should be a list or tuple or number(int or long)")
def histogram(iterator):
counters = [0] * len(buckets)
for i in iterator:
if i is None or (type(i) is float and isnan(i)) or i > maxv or i < minv:
continue
t = (int((i - minv) / inc) if even
else bisect.bisect_right(buckets, i) - 1)
counters[t] += 1
# add last two together
last = counters.pop()
counters[-1] += last
return [counters]
def mergeCounters(a, b):
return [i + j for i, j in zip(a, b)]
return buckets, self.mapPartitions(histogram).reduce(mergeCounters) | def histogram(self, buckets):
"""
Compute a histogram using the provided buckets. The buckets
are all open to the right except for the last which is closed.
e.g. [1,10,20,50] means the buckets are [1,10) [10,20) [20,50],
which means 1<=x<10, 10<=x<20, 20<=x<=50. And on the input of 1
and 50 we would have a histogram of 1,0,1.
If your histogram is evenly spaced (e.g. [0, 10, 20, 30]),
this can be switched from an O(log n) inseration to O(1) per
element (where n is the number of buckets).
Buckets must be sorted, not contain any duplicates, and have
at least two elements.
If `buckets` is a number, it will generate buckets which are
evenly spaced between the minimum and maximum of the RDD. For
example, if the min value is 0 and the max is 100, given `buckets`
as 2, the resulting buckets will be [0,50) [50,100]. `buckets` must
be at least 1. An exception is raised if the RDD contains infinity.
If the elements in the RDD do not vary (max == min), a single bucket
will be used.
The return value is a tuple of buckets and histogram.
>>> rdd = sc.parallelize(range(51))
>>> rdd.histogram(2)
([0, 25, 50], [25, 26])
>>> rdd.histogram([0, 5, 25, 50])
([0, 5, 25, 50], [5, 20, 26])
>>> rdd.histogram([0, 15, 30, 45, 60]) # evenly spaced buckets
([0, 15, 30, 45, 60], [15, 15, 15, 6])
>>> rdd = sc.parallelize(["ab", "ac", "b", "bd", "ef"])
>>> rdd.histogram(("a", "b", "c"))
(('a', 'b', 'c'), [2, 2])
"""
if isinstance(buckets, int):
if buckets < 1:
raise ValueError("number of buckets must be >= 1")
# filter out non-comparable elements
def comparable(x):
if x is None:
return False
if type(x) is float and isnan(x):
return False
return True
filtered = self.filter(comparable)
# faster than stats()
def minmax(a, b):
return min(a[0], b[0]), max(a[1], b[1])
try:
minv, maxv = filtered.map(lambda x: (x, x)).reduce(minmax)
except TypeError as e:
if " empty " in str(e):
raise ValueError("can not generate buckets from empty RDD")
raise
if minv == maxv or buckets == 1:
return [minv, maxv], [filtered.count()]
try:
inc = (maxv - minv) / buckets
except TypeError:
raise TypeError("Can not generate buckets with non-number in RDD")
if isinf(inc):
raise ValueError("Can not generate buckets with infinite value")
# keep them as integer if possible
inc = int(inc)
if inc * buckets != maxv - minv:
inc = (maxv - minv) * 1.0 / buckets
buckets = [i * inc + minv for i in range(buckets)]
buckets.append(maxv) # fix accumulated error
even = True
elif isinstance(buckets, (list, tuple)):
if len(buckets) < 2:
raise ValueError("buckets should have more than one value")
if any(i is None or isinstance(i, float) and isnan(i) for i in buckets):
raise ValueError("can not have None or NaN in buckets")
if sorted(buckets) != list(buckets):
raise ValueError("buckets should be sorted")
if len(set(buckets)) != len(buckets):
raise ValueError("buckets should not contain duplicated values")
minv = buckets[0]
maxv = buckets[-1]
even = False
inc = None
try:
steps = [buckets[i + 1] - buckets[i] for i in range(len(buckets) - 1)]
except TypeError:
pass # objects in buckets do not support '-'
else:
if max(steps) - min(steps) < 1e-10: # handle precision errors
even = True
inc = (maxv - minv) / (len(buckets) - 1)
else:
raise TypeError("buckets should be a list or tuple or number(int or long)")
def histogram(iterator):
counters = [0] * len(buckets)
for i in iterator:
if i is None or (type(i) is float and isnan(i)) or i > maxv or i < minv:
continue
t = (int((i - minv) / inc) if even
else bisect.bisect_right(buckets, i) - 1)
counters[t] += 1
# add last two together
last = counters.pop()
counters[-1] += last
return [counters]
def mergeCounters(a, b):
return [i + j for i, j in zip(a, b)]
return buckets, self.mapPartitions(histogram).reduce(mergeCounters) | [
"Compute",
"a",
"histogram",
"using",
"the",
"provided",
"buckets",
".",
"The",
"buckets",
"are",
"all",
"open",
"to",
"the",
"right",
"except",
"for",
"the",
"last",
"which",
"is",
"closed",
".",
"e",
".",
"g",
".",
"[",
"1",
"10",
"20",
"50",
"]",
"means",
"the",
"buckets",
"are",
"[",
"1",
"10",
")",
"[",
"10",
"20",
")",
"[",
"20",
"50",
"]",
"which",
"means",
"1<",
"=",
"x<10",
"10<",
"=",
"x<20",
"20<",
"=",
"x<",
"=",
"50",
".",
"And",
"on",
"the",
"input",
"of",
"1",
"and",
"50",
"we",
"would",
"have",
"a",
"histogram",
"of",
"1",
"0",
"1",
"."
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L1069-L1195 | [
"def",
"histogram",
"(",
"self",
",",
"buckets",
")",
":",
"if",
"isinstance",
"(",
"buckets",
",",
"int",
")",
":",
"if",
"buckets",
"<",
"1",
":",
"raise",
"ValueError",
"(",
"\"number of buckets must be >= 1\"",
")",
"# filter out non-comparable elements",
"def",
"comparable",
"(",
"x",
")",
":",
"if",
"x",
"is",
"None",
":",
"return",
"False",
"if",
"type",
"(",
"x",
")",
"is",
"float",
"and",
"isnan",
"(",
"x",
")",
":",
"return",
"False",
"return",
"True",
"filtered",
"=",
"self",
".",
"filter",
"(",
"comparable",
")",
"# faster than stats()",
"def",
"minmax",
"(",
"a",
",",
"b",
")",
":",
"return",
"min",
"(",
"a",
"[",
"0",
"]",
",",
"b",
"[",
"0",
"]",
")",
",",
"max",
"(",
"a",
"[",
"1",
"]",
",",
"b",
"[",
"1",
"]",
")",
"try",
":",
"minv",
",",
"maxv",
"=",
"filtered",
".",
"map",
"(",
"lambda",
"x",
":",
"(",
"x",
",",
"x",
")",
")",
".",
"reduce",
"(",
"minmax",
")",
"except",
"TypeError",
"as",
"e",
":",
"if",
"\" empty \"",
"in",
"str",
"(",
"e",
")",
":",
"raise",
"ValueError",
"(",
"\"can not generate buckets from empty RDD\"",
")",
"raise",
"if",
"minv",
"==",
"maxv",
"or",
"buckets",
"==",
"1",
":",
"return",
"[",
"minv",
",",
"maxv",
"]",
",",
"[",
"filtered",
".",
"count",
"(",
")",
"]",
"try",
":",
"inc",
"=",
"(",
"maxv",
"-",
"minv",
")",
"/",
"buckets",
"except",
"TypeError",
":",
"raise",
"TypeError",
"(",
"\"Can not generate buckets with non-number in RDD\"",
")",
"if",
"isinf",
"(",
"inc",
")",
":",
"raise",
"ValueError",
"(",
"\"Can not generate buckets with infinite value\"",
")",
"# keep them as integer if possible",
"inc",
"=",
"int",
"(",
"inc",
")",
"if",
"inc",
"*",
"buckets",
"!=",
"maxv",
"-",
"minv",
":",
"inc",
"=",
"(",
"maxv",
"-",
"minv",
")",
"*",
"1.0",
"/",
"buckets",
"buckets",
"=",
"[",
"i",
"*",
"inc",
"+",
"minv",
"for",
"i",
"in",
"range",
"(",
"buckets",
")",
"]",
"buckets",
".",
"append",
"(",
"maxv",
")",
"# fix accumulated error",
"even",
"=",
"True",
"elif",
"isinstance",
"(",
"buckets",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"if",
"len",
"(",
"buckets",
")",
"<",
"2",
":",
"raise",
"ValueError",
"(",
"\"buckets should have more than one value\"",
")",
"if",
"any",
"(",
"i",
"is",
"None",
"or",
"isinstance",
"(",
"i",
",",
"float",
")",
"and",
"isnan",
"(",
"i",
")",
"for",
"i",
"in",
"buckets",
")",
":",
"raise",
"ValueError",
"(",
"\"can not have None or NaN in buckets\"",
")",
"if",
"sorted",
"(",
"buckets",
")",
"!=",
"list",
"(",
"buckets",
")",
":",
"raise",
"ValueError",
"(",
"\"buckets should be sorted\"",
")",
"if",
"len",
"(",
"set",
"(",
"buckets",
")",
")",
"!=",
"len",
"(",
"buckets",
")",
":",
"raise",
"ValueError",
"(",
"\"buckets should not contain duplicated values\"",
")",
"minv",
"=",
"buckets",
"[",
"0",
"]",
"maxv",
"=",
"buckets",
"[",
"-",
"1",
"]",
"even",
"=",
"False",
"inc",
"=",
"None",
"try",
":",
"steps",
"=",
"[",
"buckets",
"[",
"i",
"+",
"1",
"]",
"-",
"buckets",
"[",
"i",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"buckets",
")",
"-",
"1",
")",
"]",
"except",
"TypeError",
":",
"pass",
"# objects in buckets do not support '-'",
"else",
":",
"if",
"max",
"(",
"steps",
")",
"-",
"min",
"(",
"steps",
")",
"<",
"1e-10",
":",
"# handle precision errors",
"even",
"=",
"True",
"inc",
"=",
"(",
"maxv",
"-",
"minv",
")",
"/",
"(",
"len",
"(",
"buckets",
")",
"-",
"1",
")",
"else",
":",
"raise",
"TypeError",
"(",
"\"buckets should be a list or tuple or number(int or long)\"",
")",
"def",
"histogram",
"(",
"iterator",
")",
":",
"counters",
"=",
"[",
"0",
"]",
"*",
"len",
"(",
"buckets",
")",
"for",
"i",
"in",
"iterator",
":",
"if",
"i",
"is",
"None",
"or",
"(",
"type",
"(",
"i",
")",
"is",
"float",
"and",
"isnan",
"(",
"i",
")",
")",
"or",
"i",
">",
"maxv",
"or",
"i",
"<",
"minv",
":",
"continue",
"t",
"=",
"(",
"int",
"(",
"(",
"i",
"-",
"minv",
")",
"/",
"inc",
")",
"if",
"even",
"else",
"bisect",
".",
"bisect_right",
"(",
"buckets",
",",
"i",
")",
"-",
"1",
")",
"counters",
"[",
"t",
"]",
"+=",
"1",
"# add last two together",
"last",
"=",
"counters",
".",
"pop",
"(",
")",
"counters",
"[",
"-",
"1",
"]",
"+=",
"last",
"return",
"[",
"counters",
"]",
"def",
"mergeCounters",
"(",
"a",
",",
"b",
")",
":",
"return",
"[",
"i",
"+",
"j",
"for",
"i",
",",
"j",
"in",
"zip",
"(",
"a",
",",
"b",
")",
"]",
"return",
"buckets",
",",
"self",
".",
"mapPartitions",
"(",
"histogram",
")",
".",
"reduce",
"(",
"mergeCounters",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | RDD.countByValue | Return the count of each unique value in this RDD as a dictionary of
(value, count) pairs.
>>> sorted(sc.parallelize([1, 2, 1, 2, 2], 2).countByValue().items())
[(1, 2), (2, 3)] | python/pyspark/rdd.py | def countByValue(self):
"""
Return the count of each unique value in this RDD as a dictionary of
(value, count) pairs.
>>> sorted(sc.parallelize([1, 2, 1, 2, 2], 2).countByValue().items())
[(1, 2), (2, 3)]
"""
def countPartition(iterator):
counts = defaultdict(int)
for obj in iterator:
counts[obj] += 1
yield counts
def mergeMaps(m1, m2):
for k, v in m2.items():
m1[k] += v
return m1
return self.mapPartitions(countPartition).reduce(mergeMaps) | def countByValue(self):
"""
Return the count of each unique value in this RDD as a dictionary of
(value, count) pairs.
>>> sorted(sc.parallelize([1, 2, 1, 2, 2], 2).countByValue().items())
[(1, 2), (2, 3)]
"""
def countPartition(iterator):
counts = defaultdict(int)
for obj in iterator:
counts[obj] += 1
yield counts
def mergeMaps(m1, m2):
for k, v in m2.items():
m1[k] += v
return m1
return self.mapPartitions(countPartition).reduce(mergeMaps) | [
"Return",
"the",
"count",
"of",
"each",
"unique",
"value",
"in",
"this",
"RDD",
"as",
"a",
"dictionary",
"of",
"(",
"value",
"count",
")",
"pairs",
"."
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L1245-L1263 | [
"def",
"countByValue",
"(",
"self",
")",
":",
"def",
"countPartition",
"(",
"iterator",
")",
":",
"counts",
"=",
"defaultdict",
"(",
"int",
")",
"for",
"obj",
"in",
"iterator",
":",
"counts",
"[",
"obj",
"]",
"+=",
"1",
"yield",
"counts",
"def",
"mergeMaps",
"(",
"m1",
",",
"m2",
")",
":",
"for",
"k",
",",
"v",
"in",
"m2",
".",
"items",
"(",
")",
":",
"m1",
"[",
"k",
"]",
"+=",
"v",
"return",
"m1",
"return",
"self",
".",
"mapPartitions",
"(",
"countPartition",
")",
".",
"reduce",
"(",
"mergeMaps",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | RDD.top | Get the top N elements from an RDD.
.. note:: This method should only be used if the resulting array is expected
to be small, as all the data is loaded into the driver's memory.
.. note:: It returns the list sorted in descending order.
>>> sc.parallelize([10, 4, 2, 12, 3]).top(1)
[12]
>>> sc.parallelize([2, 3, 4, 5, 6], 2).top(2)
[6, 5]
>>> sc.parallelize([10, 4, 2, 12, 3]).top(3, key=str)
[4, 3, 2] | python/pyspark/rdd.py | def top(self, num, key=None):
"""
Get the top N elements from an RDD.
.. note:: This method should only be used if the resulting array is expected
to be small, as all the data is loaded into the driver's memory.
.. note:: It returns the list sorted in descending order.
>>> sc.parallelize([10, 4, 2, 12, 3]).top(1)
[12]
>>> sc.parallelize([2, 3, 4, 5, 6], 2).top(2)
[6, 5]
>>> sc.parallelize([10, 4, 2, 12, 3]).top(3, key=str)
[4, 3, 2]
"""
def topIterator(iterator):
yield heapq.nlargest(num, iterator, key=key)
def merge(a, b):
return heapq.nlargest(num, a + b, key=key)
return self.mapPartitions(topIterator).reduce(merge) | def top(self, num, key=None):
"""
Get the top N elements from an RDD.
.. note:: This method should only be used if the resulting array is expected
to be small, as all the data is loaded into the driver's memory.
.. note:: It returns the list sorted in descending order.
>>> sc.parallelize([10, 4, 2, 12, 3]).top(1)
[12]
>>> sc.parallelize([2, 3, 4, 5, 6], 2).top(2)
[6, 5]
>>> sc.parallelize([10, 4, 2, 12, 3]).top(3, key=str)
[4, 3, 2]
"""
def topIterator(iterator):
yield heapq.nlargest(num, iterator, key=key)
def merge(a, b):
return heapq.nlargest(num, a + b, key=key)
return self.mapPartitions(topIterator).reduce(merge) | [
"Get",
"the",
"top",
"N",
"elements",
"from",
"an",
"RDD",
"."
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L1265-L1287 | [
"def",
"top",
"(",
"self",
",",
"num",
",",
"key",
"=",
"None",
")",
":",
"def",
"topIterator",
"(",
"iterator",
")",
":",
"yield",
"heapq",
".",
"nlargest",
"(",
"num",
",",
"iterator",
",",
"key",
"=",
"key",
")",
"def",
"merge",
"(",
"a",
",",
"b",
")",
":",
"return",
"heapq",
".",
"nlargest",
"(",
"num",
",",
"a",
"+",
"b",
",",
"key",
"=",
"key",
")",
"return",
"self",
".",
"mapPartitions",
"(",
"topIterator",
")",
".",
"reduce",
"(",
"merge",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | RDD.takeOrdered | Get the N elements from an RDD ordered in ascending order or as
specified by the optional key function.
.. note:: this method should only be used if the resulting array is expected
to be small, as all the data is loaded into the driver's memory.
>>> sc.parallelize([10, 1, 2, 9, 3, 4, 5, 6, 7]).takeOrdered(6)
[1, 2, 3, 4, 5, 6]
>>> sc.parallelize([10, 1, 2, 9, 3, 4, 5, 6, 7], 2).takeOrdered(6, key=lambda x: -x)
[10, 9, 7, 6, 5, 4] | python/pyspark/rdd.py | def takeOrdered(self, num, key=None):
"""
Get the N elements from an RDD ordered in ascending order or as
specified by the optional key function.
.. note:: this method should only be used if the resulting array is expected
to be small, as all the data is loaded into the driver's memory.
>>> sc.parallelize([10, 1, 2, 9, 3, 4, 5, 6, 7]).takeOrdered(6)
[1, 2, 3, 4, 5, 6]
>>> sc.parallelize([10, 1, 2, 9, 3, 4, 5, 6, 7], 2).takeOrdered(6, key=lambda x: -x)
[10, 9, 7, 6, 5, 4]
"""
def merge(a, b):
return heapq.nsmallest(num, a + b, key)
return self.mapPartitions(lambda it: [heapq.nsmallest(num, it, key)]).reduce(merge) | def takeOrdered(self, num, key=None):
"""
Get the N elements from an RDD ordered in ascending order or as
specified by the optional key function.
.. note:: this method should only be used if the resulting array is expected
to be small, as all the data is loaded into the driver's memory.
>>> sc.parallelize([10, 1, 2, 9, 3, 4, 5, 6, 7]).takeOrdered(6)
[1, 2, 3, 4, 5, 6]
>>> sc.parallelize([10, 1, 2, 9, 3, 4, 5, 6, 7], 2).takeOrdered(6, key=lambda x: -x)
[10, 9, 7, 6, 5, 4]
"""
def merge(a, b):
return heapq.nsmallest(num, a + b, key)
return self.mapPartitions(lambda it: [heapq.nsmallest(num, it, key)]).reduce(merge) | [
"Get",
"the",
"N",
"elements",
"from",
"an",
"RDD",
"ordered",
"in",
"ascending",
"order",
"or",
"as",
"specified",
"by",
"the",
"optional",
"key",
"function",
"."
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L1289-L1306 | [
"def",
"takeOrdered",
"(",
"self",
",",
"num",
",",
"key",
"=",
"None",
")",
":",
"def",
"merge",
"(",
"a",
",",
"b",
")",
":",
"return",
"heapq",
".",
"nsmallest",
"(",
"num",
",",
"a",
"+",
"b",
",",
"key",
")",
"return",
"self",
".",
"mapPartitions",
"(",
"lambda",
"it",
":",
"[",
"heapq",
".",
"nsmallest",
"(",
"num",
",",
"it",
",",
"key",
")",
"]",
")",
".",
"reduce",
"(",
"merge",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | RDD.take | Take the first num elements of the RDD.
It works by first scanning one partition, and use the results from
that partition to estimate the number of additional partitions needed
to satisfy the limit.
Translated from the Scala implementation in RDD#take().
.. note:: this method should only be used if the resulting array is expected
to be small, as all the data is loaded into the driver's memory.
>>> sc.parallelize([2, 3, 4, 5, 6]).cache().take(2)
[2, 3]
>>> sc.parallelize([2, 3, 4, 5, 6]).take(10)
[2, 3, 4, 5, 6]
>>> sc.parallelize(range(100), 100).filter(lambda x: x > 90).take(3)
[91, 92, 93] | python/pyspark/rdd.py | def take(self, num):
"""
Take the first num elements of the RDD.
It works by first scanning one partition, and use the results from
that partition to estimate the number of additional partitions needed
to satisfy the limit.
Translated from the Scala implementation in RDD#take().
.. note:: this method should only be used if the resulting array is expected
to be small, as all the data is loaded into the driver's memory.
>>> sc.parallelize([2, 3, 4, 5, 6]).cache().take(2)
[2, 3]
>>> sc.parallelize([2, 3, 4, 5, 6]).take(10)
[2, 3, 4, 5, 6]
>>> sc.parallelize(range(100), 100).filter(lambda x: x > 90).take(3)
[91, 92, 93]
"""
items = []
totalParts = self.getNumPartitions()
partsScanned = 0
while len(items) < num and partsScanned < totalParts:
# The number of partitions to try in this iteration.
# It is ok for this number to be greater than totalParts because
# we actually cap it at totalParts in runJob.
numPartsToTry = 1
if partsScanned > 0:
# If we didn't find any rows after the previous iteration,
# quadruple and retry. Otherwise, interpolate the number of
# partitions we need to try, but overestimate it by 50%.
# We also cap the estimation in the end.
if len(items) == 0:
numPartsToTry = partsScanned * 4
else:
# the first parameter of max is >=1 whenever partsScanned >= 2
numPartsToTry = int(1.5 * num * partsScanned / len(items)) - partsScanned
numPartsToTry = min(max(numPartsToTry, 1), partsScanned * 4)
left = num - len(items)
def takeUpToNumLeft(iterator):
iterator = iter(iterator)
taken = 0
while taken < left:
try:
yield next(iterator)
except StopIteration:
return
taken += 1
p = range(partsScanned, min(partsScanned + numPartsToTry, totalParts))
res = self.context.runJob(self, takeUpToNumLeft, p)
items += res
partsScanned += numPartsToTry
return items[:num] | def take(self, num):
"""
Take the first num elements of the RDD.
It works by first scanning one partition, and use the results from
that partition to estimate the number of additional partitions needed
to satisfy the limit.
Translated from the Scala implementation in RDD#take().
.. note:: this method should only be used if the resulting array is expected
to be small, as all the data is loaded into the driver's memory.
>>> sc.parallelize([2, 3, 4, 5, 6]).cache().take(2)
[2, 3]
>>> sc.parallelize([2, 3, 4, 5, 6]).take(10)
[2, 3, 4, 5, 6]
>>> sc.parallelize(range(100), 100).filter(lambda x: x > 90).take(3)
[91, 92, 93]
"""
items = []
totalParts = self.getNumPartitions()
partsScanned = 0
while len(items) < num and partsScanned < totalParts:
# The number of partitions to try in this iteration.
# It is ok for this number to be greater than totalParts because
# we actually cap it at totalParts in runJob.
numPartsToTry = 1
if partsScanned > 0:
# If we didn't find any rows after the previous iteration,
# quadruple and retry. Otherwise, interpolate the number of
# partitions we need to try, but overestimate it by 50%.
# We also cap the estimation in the end.
if len(items) == 0:
numPartsToTry = partsScanned * 4
else:
# the first parameter of max is >=1 whenever partsScanned >= 2
numPartsToTry = int(1.5 * num * partsScanned / len(items)) - partsScanned
numPartsToTry = min(max(numPartsToTry, 1), partsScanned * 4)
left = num - len(items)
def takeUpToNumLeft(iterator):
iterator = iter(iterator)
taken = 0
while taken < left:
try:
yield next(iterator)
except StopIteration:
return
taken += 1
p = range(partsScanned, min(partsScanned + numPartsToTry, totalParts))
res = self.context.runJob(self, takeUpToNumLeft, p)
items += res
partsScanned += numPartsToTry
return items[:num] | [
"Take",
"the",
"first",
"num",
"elements",
"of",
"the",
"RDD",
"."
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L1308-L1367 | [
"def",
"take",
"(",
"self",
",",
"num",
")",
":",
"items",
"=",
"[",
"]",
"totalParts",
"=",
"self",
".",
"getNumPartitions",
"(",
")",
"partsScanned",
"=",
"0",
"while",
"len",
"(",
"items",
")",
"<",
"num",
"and",
"partsScanned",
"<",
"totalParts",
":",
"# The number of partitions to try in this iteration.",
"# It is ok for this number to be greater than totalParts because",
"# we actually cap it at totalParts in runJob.",
"numPartsToTry",
"=",
"1",
"if",
"partsScanned",
">",
"0",
":",
"# If we didn't find any rows after the previous iteration,",
"# quadruple and retry. Otherwise, interpolate the number of",
"# partitions we need to try, but overestimate it by 50%.",
"# We also cap the estimation in the end.",
"if",
"len",
"(",
"items",
")",
"==",
"0",
":",
"numPartsToTry",
"=",
"partsScanned",
"*",
"4",
"else",
":",
"# the first parameter of max is >=1 whenever partsScanned >= 2",
"numPartsToTry",
"=",
"int",
"(",
"1.5",
"*",
"num",
"*",
"partsScanned",
"/",
"len",
"(",
"items",
")",
")",
"-",
"partsScanned",
"numPartsToTry",
"=",
"min",
"(",
"max",
"(",
"numPartsToTry",
",",
"1",
")",
",",
"partsScanned",
"*",
"4",
")",
"left",
"=",
"num",
"-",
"len",
"(",
"items",
")",
"def",
"takeUpToNumLeft",
"(",
"iterator",
")",
":",
"iterator",
"=",
"iter",
"(",
"iterator",
")",
"taken",
"=",
"0",
"while",
"taken",
"<",
"left",
":",
"try",
":",
"yield",
"next",
"(",
"iterator",
")",
"except",
"StopIteration",
":",
"return",
"taken",
"+=",
"1",
"p",
"=",
"range",
"(",
"partsScanned",
",",
"min",
"(",
"partsScanned",
"+",
"numPartsToTry",
",",
"totalParts",
")",
")",
"res",
"=",
"self",
".",
"context",
".",
"runJob",
"(",
"self",
",",
"takeUpToNumLeft",
",",
"p",
")",
"items",
"+=",
"res",
"partsScanned",
"+=",
"numPartsToTry",
"return",
"items",
"[",
":",
"num",
"]"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | RDD.saveAsNewAPIHadoopDataset | Output a Python RDD of key-value pairs (of form C{RDD[(K, V)]}) to any Hadoop file
system, using the new Hadoop OutputFormat API (mapreduce package). Keys/values are
converted for output using either user specified converters or, by default,
L{org.apache.spark.api.python.JavaToWritableConverter}.
:param conf: Hadoop job configuration, passed in as a dict
:param keyConverter: (None by default)
:param valueConverter: (None by default) | python/pyspark/rdd.py | def saveAsNewAPIHadoopDataset(self, conf, keyConverter=None, valueConverter=None):
"""
Output a Python RDD of key-value pairs (of form C{RDD[(K, V)]}) to any Hadoop file
system, using the new Hadoop OutputFormat API (mapreduce package). Keys/values are
converted for output using either user specified converters or, by default,
L{org.apache.spark.api.python.JavaToWritableConverter}.
:param conf: Hadoop job configuration, passed in as a dict
:param keyConverter: (None by default)
:param valueConverter: (None by default)
"""
jconf = self.ctx._dictToJavaMap(conf)
pickledRDD = self._pickled()
self.ctx._jvm.PythonRDD.saveAsHadoopDataset(pickledRDD._jrdd, True, jconf,
keyConverter, valueConverter, True) | def saveAsNewAPIHadoopDataset(self, conf, keyConverter=None, valueConverter=None):
"""
Output a Python RDD of key-value pairs (of form C{RDD[(K, V)]}) to any Hadoop file
system, using the new Hadoop OutputFormat API (mapreduce package). Keys/values are
converted for output using either user specified converters or, by default,
L{org.apache.spark.api.python.JavaToWritableConverter}.
:param conf: Hadoop job configuration, passed in as a dict
:param keyConverter: (None by default)
:param valueConverter: (None by default)
"""
jconf = self.ctx._dictToJavaMap(conf)
pickledRDD = self._pickled()
self.ctx._jvm.PythonRDD.saveAsHadoopDataset(pickledRDD._jrdd, True, jconf,
keyConverter, valueConverter, True) | [
"Output",
"a",
"Python",
"RDD",
"of",
"key",
"-",
"value",
"pairs",
"(",
"of",
"form",
"C",
"{",
"RDD",
"[",
"(",
"K",
"V",
")",
"]",
"}",
")",
"to",
"any",
"Hadoop",
"file",
"system",
"using",
"the",
"new",
"Hadoop",
"OutputFormat",
"API",
"(",
"mapreduce",
"package",
")",
".",
"Keys",
"/",
"values",
"are",
"converted",
"for",
"output",
"using",
"either",
"user",
"specified",
"converters",
"or",
"by",
"default",
"L",
"{",
"org",
".",
"apache",
".",
"spark",
".",
"api",
".",
"python",
".",
"JavaToWritableConverter",
"}",
"."
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L1398-L1412 | [
"def",
"saveAsNewAPIHadoopDataset",
"(",
"self",
",",
"conf",
",",
"keyConverter",
"=",
"None",
",",
"valueConverter",
"=",
"None",
")",
":",
"jconf",
"=",
"self",
".",
"ctx",
".",
"_dictToJavaMap",
"(",
"conf",
")",
"pickledRDD",
"=",
"self",
".",
"_pickled",
"(",
")",
"self",
".",
"ctx",
".",
"_jvm",
".",
"PythonRDD",
".",
"saveAsHadoopDataset",
"(",
"pickledRDD",
".",
"_jrdd",
",",
"True",
",",
"jconf",
",",
"keyConverter",
",",
"valueConverter",
",",
"True",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | RDD.saveAsNewAPIHadoopFile | Output a Python RDD of key-value pairs (of form C{RDD[(K, V)]}) to any Hadoop file
system, using the new Hadoop OutputFormat API (mapreduce package). Key and value types
will be inferred if not specified. Keys and values are converted for output using either
user specified converters or L{org.apache.spark.api.python.JavaToWritableConverter}. The
C{conf} is applied on top of the base Hadoop conf associated with the SparkContext
of this RDD to create a merged Hadoop MapReduce job configuration for saving the data.
:param path: path to Hadoop file
:param outputFormatClass: fully qualified classname of Hadoop OutputFormat
(e.g. "org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat")
:param keyClass: fully qualified classname of key Writable class
(e.g. "org.apache.hadoop.io.IntWritable", None by default)
:param valueClass: fully qualified classname of value Writable class
(e.g. "org.apache.hadoop.io.Text", None by default)
:param keyConverter: (None by default)
:param valueConverter: (None by default)
:param conf: Hadoop job configuration, passed in as a dict (None by default) | python/pyspark/rdd.py | def saveAsNewAPIHadoopFile(self, path, outputFormatClass, keyClass=None, valueClass=None,
keyConverter=None, valueConverter=None, conf=None):
"""
Output a Python RDD of key-value pairs (of form C{RDD[(K, V)]}) to any Hadoop file
system, using the new Hadoop OutputFormat API (mapreduce package). Key and value types
will be inferred if not specified. Keys and values are converted for output using either
user specified converters or L{org.apache.spark.api.python.JavaToWritableConverter}. The
C{conf} is applied on top of the base Hadoop conf associated with the SparkContext
of this RDD to create a merged Hadoop MapReduce job configuration for saving the data.
:param path: path to Hadoop file
:param outputFormatClass: fully qualified classname of Hadoop OutputFormat
(e.g. "org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat")
:param keyClass: fully qualified classname of key Writable class
(e.g. "org.apache.hadoop.io.IntWritable", None by default)
:param valueClass: fully qualified classname of value Writable class
(e.g. "org.apache.hadoop.io.Text", None by default)
:param keyConverter: (None by default)
:param valueConverter: (None by default)
:param conf: Hadoop job configuration, passed in as a dict (None by default)
"""
jconf = self.ctx._dictToJavaMap(conf)
pickledRDD = self._pickled()
self.ctx._jvm.PythonRDD.saveAsNewAPIHadoopFile(pickledRDD._jrdd, True, path,
outputFormatClass,
keyClass, valueClass,
keyConverter, valueConverter, jconf) | def saveAsNewAPIHadoopFile(self, path, outputFormatClass, keyClass=None, valueClass=None,
keyConverter=None, valueConverter=None, conf=None):
"""
Output a Python RDD of key-value pairs (of form C{RDD[(K, V)]}) to any Hadoop file
system, using the new Hadoop OutputFormat API (mapreduce package). Key and value types
will be inferred if not specified. Keys and values are converted for output using either
user specified converters or L{org.apache.spark.api.python.JavaToWritableConverter}. The
C{conf} is applied on top of the base Hadoop conf associated with the SparkContext
of this RDD to create a merged Hadoop MapReduce job configuration for saving the data.
:param path: path to Hadoop file
:param outputFormatClass: fully qualified classname of Hadoop OutputFormat
(e.g. "org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat")
:param keyClass: fully qualified classname of key Writable class
(e.g. "org.apache.hadoop.io.IntWritable", None by default)
:param valueClass: fully qualified classname of value Writable class
(e.g. "org.apache.hadoop.io.Text", None by default)
:param keyConverter: (None by default)
:param valueConverter: (None by default)
:param conf: Hadoop job configuration, passed in as a dict (None by default)
"""
jconf = self.ctx._dictToJavaMap(conf)
pickledRDD = self._pickled()
self.ctx._jvm.PythonRDD.saveAsNewAPIHadoopFile(pickledRDD._jrdd, True, path,
outputFormatClass,
keyClass, valueClass,
keyConverter, valueConverter, jconf) | [
"Output",
"a",
"Python",
"RDD",
"of",
"key",
"-",
"value",
"pairs",
"(",
"of",
"form",
"C",
"{",
"RDD",
"[",
"(",
"K",
"V",
")",
"]",
"}",
")",
"to",
"any",
"Hadoop",
"file",
"system",
"using",
"the",
"new",
"Hadoop",
"OutputFormat",
"API",
"(",
"mapreduce",
"package",
")",
".",
"Key",
"and",
"value",
"types",
"will",
"be",
"inferred",
"if",
"not",
"specified",
".",
"Keys",
"and",
"values",
"are",
"converted",
"for",
"output",
"using",
"either",
"user",
"specified",
"converters",
"or",
"L",
"{",
"org",
".",
"apache",
".",
"spark",
".",
"api",
".",
"python",
".",
"JavaToWritableConverter",
"}",
".",
"The",
"C",
"{",
"conf",
"}",
"is",
"applied",
"on",
"top",
"of",
"the",
"base",
"Hadoop",
"conf",
"associated",
"with",
"the",
"SparkContext",
"of",
"this",
"RDD",
"to",
"create",
"a",
"merged",
"Hadoop",
"MapReduce",
"job",
"configuration",
"for",
"saving",
"the",
"data",
"."
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L1414-L1440 | [
"def",
"saveAsNewAPIHadoopFile",
"(",
"self",
",",
"path",
",",
"outputFormatClass",
",",
"keyClass",
"=",
"None",
",",
"valueClass",
"=",
"None",
",",
"keyConverter",
"=",
"None",
",",
"valueConverter",
"=",
"None",
",",
"conf",
"=",
"None",
")",
":",
"jconf",
"=",
"self",
".",
"ctx",
".",
"_dictToJavaMap",
"(",
"conf",
")",
"pickledRDD",
"=",
"self",
".",
"_pickled",
"(",
")",
"self",
".",
"ctx",
".",
"_jvm",
".",
"PythonRDD",
".",
"saveAsNewAPIHadoopFile",
"(",
"pickledRDD",
".",
"_jrdd",
",",
"True",
",",
"path",
",",
"outputFormatClass",
",",
"keyClass",
",",
"valueClass",
",",
"keyConverter",
",",
"valueConverter",
",",
"jconf",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | RDD.saveAsSequenceFile | Output a Python RDD of key-value pairs (of form C{RDD[(K, V)]}) to any Hadoop file
system, using the L{org.apache.hadoop.io.Writable} types that we convert from the
RDD's key and value types. The mechanism is as follows:
1. Pyrolite is used to convert pickled Python RDD into RDD of Java objects.
2. Keys and values of this Java RDD are converted to Writables and written out.
:param path: path to sequence file
:param compressionCodecClass: (None by default) | python/pyspark/rdd.py | def saveAsSequenceFile(self, path, compressionCodecClass=None):
"""
Output a Python RDD of key-value pairs (of form C{RDD[(K, V)]}) to any Hadoop file
system, using the L{org.apache.hadoop.io.Writable} types that we convert from the
RDD's key and value types. The mechanism is as follows:
1. Pyrolite is used to convert pickled Python RDD into RDD of Java objects.
2. Keys and values of this Java RDD are converted to Writables and written out.
:param path: path to sequence file
:param compressionCodecClass: (None by default)
"""
pickledRDD = self._pickled()
self.ctx._jvm.PythonRDD.saveAsSequenceFile(pickledRDD._jrdd, True,
path, compressionCodecClass) | def saveAsSequenceFile(self, path, compressionCodecClass=None):
"""
Output a Python RDD of key-value pairs (of form C{RDD[(K, V)]}) to any Hadoop file
system, using the L{org.apache.hadoop.io.Writable} types that we convert from the
RDD's key and value types. The mechanism is as follows:
1. Pyrolite is used to convert pickled Python RDD into RDD of Java objects.
2. Keys and values of this Java RDD are converted to Writables and written out.
:param path: path to sequence file
:param compressionCodecClass: (None by default)
"""
pickledRDD = self._pickled()
self.ctx._jvm.PythonRDD.saveAsSequenceFile(pickledRDD._jrdd, True,
path, compressionCodecClass) | [
"Output",
"a",
"Python",
"RDD",
"of",
"key",
"-",
"value",
"pairs",
"(",
"of",
"form",
"C",
"{",
"RDD",
"[",
"(",
"K",
"V",
")",
"]",
"}",
")",
"to",
"any",
"Hadoop",
"file",
"system",
"using",
"the",
"L",
"{",
"org",
".",
"apache",
".",
"hadoop",
".",
"io",
".",
"Writable",
"}",
"types",
"that",
"we",
"convert",
"from",
"the",
"RDD",
"s",
"key",
"and",
"value",
"types",
".",
"The",
"mechanism",
"is",
"as",
"follows",
":"
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L1489-L1503 | [
"def",
"saveAsSequenceFile",
"(",
"self",
",",
"path",
",",
"compressionCodecClass",
"=",
"None",
")",
":",
"pickledRDD",
"=",
"self",
".",
"_pickled",
"(",
")",
"self",
".",
"ctx",
".",
"_jvm",
".",
"PythonRDD",
".",
"saveAsSequenceFile",
"(",
"pickledRDD",
".",
"_jrdd",
",",
"True",
",",
"path",
",",
"compressionCodecClass",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | RDD.saveAsPickleFile | Save this RDD as a SequenceFile of serialized objects. The serializer
used is L{pyspark.serializers.PickleSerializer}, default batch size
is 10.
>>> tmpFile = NamedTemporaryFile(delete=True)
>>> tmpFile.close()
>>> sc.parallelize([1, 2, 'spark', 'rdd']).saveAsPickleFile(tmpFile.name, 3)
>>> sorted(sc.pickleFile(tmpFile.name, 5).map(str).collect())
['1', '2', 'rdd', 'spark'] | python/pyspark/rdd.py | def saveAsPickleFile(self, path, batchSize=10):
"""
Save this RDD as a SequenceFile of serialized objects. The serializer
used is L{pyspark.serializers.PickleSerializer}, default batch size
is 10.
>>> tmpFile = NamedTemporaryFile(delete=True)
>>> tmpFile.close()
>>> sc.parallelize([1, 2, 'spark', 'rdd']).saveAsPickleFile(tmpFile.name, 3)
>>> sorted(sc.pickleFile(tmpFile.name, 5).map(str).collect())
['1', '2', 'rdd', 'spark']
"""
if batchSize == 0:
ser = AutoBatchedSerializer(PickleSerializer())
else:
ser = BatchedSerializer(PickleSerializer(), batchSize)
self._reserialize(ser)._jrdd.saveAsObjectFile(path) | def saveAsPickleFile(self, path, batchSize=10):
"""
Save this RDD as a SequenceFile of serialized objects. The serializer
used is L{pyspark.serializers.PickleSerializer}, default batch size
is 10.
>>> tmpFile = NamedTemporaryFile(delete=True)
>>> tmpFile.close()
>>> sc.parallelize([1, 2, 'spark', 'rdd']).saveAsPickleFile(tmpFile.name, 3)
>>> sorted(sc.pickleFile(tmpFile.name, 5).map(str).collect())
['1', '2', 'rdd', 'spark']
"""
if batchSize == 0:
ser = AutoBatchedSerializer(PickleSerializer())
else:
ser = BatchedSerializer(PickleSerializer(), batchSize)
self._reserialize(ser)._jrdd.saveAsObjectFile(path) | [
"Save",
"this",
"RDD",
"as",
"a",
"SequenceFile",
"of",
"serialized",
"objects",
".",
"The",
"serializer",
"used",
"is",
"L",
"{",
"pyspark",
".",
"serializers",
".",
"PickleSerializer",
"}",
"default",
"batch",
"size",
"is",
"10",
"."
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L1505-L1521 | [
"def",
"saveAsPickleFile",
"(",
"self",
",",
"path",
",",
"batchSize",
"=",
"10",
")",
":",
"if",
"batchSize",
"==",
"0",
":",
"ser",
"=",
"AutoBatchedSerializer",
"(",
"PickleSerializer",
"(",
")",
")",
"else",
":",
"ser",
"=",
"BatchedSerializer",
"(",
"PickleSerializer",
"(",
")",
",",
"batchSize",
")",
"self",
".",
"_reserialize",
"(",
"ser",
")",
".",
"_jrdd",
".",
"saveAsObjectFile",
"(",
"path",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | RDD.saveAsTextFile | Save this RDD as a text file, using string representations of elements.
@param path: path to text file
@param compressionCodecClass: (None by default) string i.e.
"org.apache.hadoop.io.compress.GzipCodec"
>>> tempFile = NamedTemporaryFile(delete=True)
>>> tempFile.close()
>>> sc.parallelize(range(10)).saveAsTextFile(tempFile.name)
>>> from fileinput import input
>>> from glob import glob
>>> ''.join(sorted(input(glob(tempFile.name + "/part-0000*"))))
'0\\n1\\n2\\n3\\n4\\n5\\n6\\n7\\n8\\n9\\n'
Empty lines are tolerated when saving to text files.
>>> tempFile2 = NamedTemporaryFile(delete=True)
>>> tempFile2.close()
>>> sc.parallelize(['', 'foo', '', 'bar', '']).saveAsTextFile(tempFile2.name)
>>> ''.join(sorted(input(glob(tempFile2.name + "/part-0000*"))))
'\\n\\n\\nbar\\nfoo\\n'
Using compressionCodecClass
>>> tempFile3 = NamedTemporaryFile(delete=True)
>>> tempFile3.close()
>>> codec = "org.apache.hadoop.io.compress.GzipCodec"
>>> sc.parallelize(['foo', 'bar']).saveAsTextFile(tempFile3.name, codec)
>>> from fileinput import input, hook_compressed
>>> result = sorted(input(glob(tempFile3.name + "/part*.gz"), openhook=hook_compressed))
>>> b''.join(result).decode('utf-8')
u'bar\\nfoo\\n' | python/pyspark/rdd.py | def saveAsTextFile(self, path, compressionCodecClass=None):
"""
Save this RDD as a text file, using string representations of elements.
@param path: path to text file
@param compressionCodecClass: (None by default) string i.e.
"org.apache.hadoop.io.compress.GzipCodec"
>>> tempFile = NamedTemporaryFile(delete=True)
>>> tempFile.close()
>>> sc.parallelize(range(10)).saveAsTextFile(tempFile.name)
>>> from fileinput import input
>>> from glob import glob
>>> ''.join(sorted(input(glob(tempFile.name + "/part-0000*"))))
'0\\n1\\n2\\n3\\n4\\n5\\n6\\n7\\n8\\n9\\n'
Empty lines are tolerated when saving to text files.
>>> tempFile2 = NamedTemporaryFile(delete=True)
>>> tempFile2.close()
>>> sc.parallelize(['', 'foo', '', 'bar', '']).saveAsTextFile(tempFile2.name)
>>> ''.join(sorted(input(glob(tempFile2.name + "/part-0000*"))))
'\\n\\n\\nbar\\nfoo\\n'
Using compressionCodecClass
>>> tempFile3 = NamedTemporaryFile(delete=True)
>>> tempFile3.close()
>>> codec = "org.apache.hadoop.io.compress.GzipCodec"
>>> sc.parallelize(['foo', 'bar']).saveAsTextFile(tempFile3.name, codec)
>>> from fileinput import input, hook_compressed
>>> result = sorted(input(glob(tempFile3.name + "/part*.gz"), openhook=hook_compressed))
>>> b''.join(result).decode('utf-8')
u'bar\\nfoo\\n'
"""
def func(split, iterator):
for x in iterator:
if not isinstance(x, (unicode, bytes)):
x = unicode(x)
if isinstance(x, unicode):
x = x.encode("utf-8")
yield x
keyed = self.mapPartitionsWithIndex(func)
keyed._bypass_serializer = True
if compressionCodecClass:
compressionCodec = self.ctx._jvm.java.lang.Class.forName(compressionCodecClass)
keyed._jrdd.map(self.ctx._jvm.BytesToString()).saveAsTextFile(path, compressionCodec)
else:
keyed._jrdd.map(self.ctx._jvm.BytesToString()).saveAsTextFile(path) | def saveAsTextFile(self, path, compressionCodecClass=None):
"""
Save this RDD as a text file, using string representations of elements.
@param path: path to text file
@param compressionCodecClass: (None by default) string i.e.
"org.apache.hadoop.io.compress.GzipCodec"
>>> tempFile = NamedTemporaryFile(delete=True)
>>> tempFile.close()
>>> sc.parallelize(range(10)).saveAsTextFile(tempFile.name)
>>> from fileinput import input
>>> from glob import glob
>>> ''.join(sorted(input(glob(tempFile.name + "/part-0000*"))))
'0\\n1\\n2\\n3\\n4\\n5\\n6\\n7\\n8\\n9\\n'
Empty lines are tolerated when saving to text files.
>>> tempFile2 = NamedTemporaryFile(delete=True)
>>> tempFile2.close()
>>> sc.parallelize(['', 'foo', '', 'bar', '']).saveAsTextFile(tempFile2.name)
>>> ''.join(sorted(input(glob(tempFile2.name + "/part-0000*"))))
'\\n\\n\\nbar\\nfoo\\n'
Using compressionCodecClass
>>> tempFile3 = NamedTemporaryFile(delete=True)
>>> tempFile3.close()
>>> codec = "org.apache.hadoop.io.compress.GzipCodec"
>>> sc.parallelize(['foo', 'bar']).saveAsTextFile(tempFile3.name, codec)
>>> from fileinput import input, hook_compressed
>>> result = sorted(input(glob(tempFile3.name + "/part*.gz"), openhook=hook_compressed))
>>> b''.join(result).decode('utf-8')
u'bar\\nfoo\\n'
"""
def func(split, iterator):
for x in iterator:
if not isinstance(x, (unicode, bytes)):
x = unicode(x)
if isinstance(x, unicode):
x = x.encode("utf-8")
yield x
keyed = self.mapPartitionsWithIndex(func)
keyed._bypass_serializer = True
if compressionCodecClass:
compressionCodec = self.ctx._jvm.java.lang.Class.forName(compressionCodecClass)
keyed._jrdd.map(self.ctx._jvm.BytesToString()).saveAsTextFile(path, compressionCodec)
else:
keyed._jrdd.map(self.ctx._jvm.BytesToString()).saveAsTextFile(path) | [
"Save",
"this",
"RDD",
"as",
"a",
"text",
"file",
"using",
"string",
"representations",
"of",
"elements",
"."
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L1524-L1572 | [
"def",
"saveAsTextFile",
"(",
"self",
",",
"path",
",",
"compressionCodecClass",
"=",
"None",
")",
":",
"def",
"func",
"(",
"split",
",",
"iterator",
")",
":",
"for",
"x",
"in",
"iterator",
":",
"if",
"not",
"isinstance",
"(",
"x",
",",
"(",
"unicode",
",",
"bytes",
")",
")",
":",
"x",
"=",
"unicode",
"(",
"x",
")",
"if",
"isinstance",
"(",
"x",
",",
"unicode",
")",
":",
"x",
"=",
"x",
".",
"encode",
"(",
"\"utf-8\"",
")",
"yield",
"x",
"keyed",
"=",
"self",
".",
"mapPartitionsWithIndex",
"(",
"func",
")",
"keyed",
".",
"_bypass_serializer",
"=",
"True",
"if",
"compressionCodecClass",
":",
"compressionCodec",
"=",
"self",
".",
"ctx",
".",
"_jvm",
".",
"java",
".",
"lang",
".",
"Class",
".",
"forName",
"(",
"compressionCodecClass",
")",
"keyed",
".",
"_jrdd",
".",
"map",
"(",
"self",
".",
"ctx",
".",
"_jvm",
".",
"BytesToString",
"(",
")",
")",
".",
"saveAsTextFile",
"(",
"path",
",",
"compressionCodec",
")",
"else",
":",
"keyed",
".",
"_jrdd",
".",
"map",
"(",
"self",
".",
"ctx",
".",
"_jvm",
".",
"BytesToString",
"(",
")",
")",
".",
"saveAsTextFile",
"(",
"path",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | RDD.reduceByKey | Merge the values for each key using an associative and commutative reduce function.
This will also perform the merging locally on each mapper before
sending results to a reducer, similarly to a "combiner" in MapReduce.
Output will be partitioned with C{numPartitions} partitions, or
the default parallelism level if C{numPartitions} is not specified.
Default partitioner is hash-partition.
>>> from operator import add
>>> rdd = sc.parallelize([("a", 1), ("b", 1), ("a", 1)])
>>> sorted(rdd.reduceByKey(add).collect())
[('a', 2), ('b', 1)] | python/pyspark/rdd.py | def reduceByKey(self, func, numPartitions=None, partitionFunc=portable_hash):
"""
Merge the values for each key using an associative and commutative reduce function.
This will also perform the merging locally on each mapper before
sending results to a reducer, similarly to a "combiner" in MapReduce.
Output will be partitioned with C{numPartitions} partitions, or
the default parallelism level if C{numPartitions} is not specified.
Default partitioner is hash-partition.
>>> from operator import add
>>> rdd = sc.parallelize([("a", 1), ("b", 1), ("a", 1)])
>>> sorted(rdd.reduceByKey(add).collect())
[('a', 2), ('b', 1)]
"""
return self.combineByKey(lambda x: x, func, func, numPartitions, partitionFunc) | def reduceByKey(self, func, numPartitions=None, partitionFunc=portable_hash):
"""
Merge the values for each key using an associative and commutative reduce function.
This will also perform the merging locally on each mapper before
sending results to a reducer, similarly to a "combiner" in MapReduce.
Output will be partitioned with C{numPartitions} partitions, or
the default parallelism level if C{numPartitions} is not specified.
Default partitioner is hash-partition.
>>> from operator import add
>>> rdd = sc.parallelize([("a", 1), ("b", 1), ("a", 1)])
>>> sorted(rdd.reduceByKey(add).collect())
[('a', 2), ('b', 1)]
"""
return self.combineByKey(lambda x: x, func, func, numPartitions, partitionFunc) | [
"Merge",
"the",
"values",
"for",
"each",
"key",
"using",
"an",
"associative",
"and",
"commutative",
"reduce",
"function",
"."
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L1611-L1627 | [
"def",
"reduceByKey",
"(",
"self",
",",
"func",
",",
"numPartitions",
"=",
"None",
",",
"partitionFunc",
"=",
"portable_hash",
")",
":",
"return",
"self",
".",
"combineByKey",
"(",
"lambda",
"x",
":",
"x",
",",
"func",
",",
"func",
",",
"numPartitions",
",",
"partitionFunc",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | RDD.reduceByKeyLocally | Merge the values for each key using an associative and commutative reduce function, but
return the results immediately to the master as a dictionary.
This will also perform the merging locally on each mapper before
sending results to a reducer, similarly to a "combiner" in MapReduce.
>>> from operator import add
>>> rdd = sc.parallelize([("a", 1), ("b", 1), ("a", 1)])
>>> sorted(rdd.reduceByKeyLocally(add).items())
[('a', 2), ('b', 1)] | python/pyspark/rdd.py | def reduceByKeyLocally(self, func):
"""
Merge the values for each key using an associative and commutative reduce function, but
return the results immediately to the master as a dictionary.
This will also perform the merging locally on each mapper before
sending results to a reducer, similarly to a "combiner" in MapReduce.
>>> from operator import add
>>> rdd = sc.parallelize([("a", 1), ("b", 1), ("a", 1)])
>>> sorted(rdd.reduceByKeyLocally(add).items())
[('a', 2), ('b', 1)]
"""
func = fail_on_stopiteration(func)
def reducePartition(iterator):
m = {}
for k, v in iterator:
m[k] = func(m[k], v) if k in m else v
yield m
def mergeMaps(m1, m2):
for k, v in m2.items():
m1[k] = func(m1[k], v) if k in m1 else v
return m1
return self.mapPartitions(reducePartition).reduce(mergeMaps) | def reduceByKeyLocally(self, func):
"""
Merge the values for each key using an associative and commutative reduce function, but
return the results immediately to the master as a dictionary.
This will also perform the merging locally on each mapper before
sending results to a reducer, similarly to a "combiner" in MapReduce.
>>> from operator import add
>>> rdd = sc.parallelize([("a", 1), ("b", 1), ("a", 1)])
>>> sorted(rdd.reduceByKeyLocally(add).items())
[('a', 2), ('b', 1)]
"""
func = fail_on_stopiteration(func)
def reducePartition(iterator):
m = {}
for k, v in iterator:
m[k] = func(m[k], v) if k in m else v
yield m
def mergeMaps(m1, m2):
for k, v in m2.items():
m1[k] = func(m1[k], v) if k in m1 else v
return m1
return self.mapPartitions(reducePartition).reduce(mergeMaps) | [
"Merge",
"the",
"values",
"for",
"each",
"key",
"using",
"an",
"associative",
"and",
"commutative",
"reduce",
"function",
"but",
"return",
"the",
"results",
"immediately",
"to",
"the",
"master",
"as",
"a",
"dictionary",
"."
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L1629-L1654 | [
"def",
"reduceByKeyLocally",
"(",
"self",
",",
"func",
")",
":",
"func",
"=",
"fail_on_stopiteration",
"(",
"func",
")",
"def",
"reducePartition",
"(",
"iterator",
")",
":",
"m",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"iterator",
":",
"m",
"[",
"k",
"]",
"=",
"func",
"(",
"m",
"[",
"k",
"]",
",",
"v",
")",
"if",
"k",
"in",
"m",
"else",
"v",
"yield",
"m",
"def",
"mergeMaps",
"(",
"m1",
",",
"m2",
")",
":",
"for",
"k",
",",
"v",
"in",
"m2",
".",
"items",
"(",
")",
":",
"m1",
"[",
"k",
"]",
"=",
"func",
"(",
"m1",
"[",
"k",
"]",
",",
"v",
")",
"if",
"k",
"in",
"m1",
"else",
"v",
"return",
"m1",
"return",
"self",
".",
"mapPartitions",
"(",
"reducePartition",
")",
".",
"reduce",
"(",
"mergeMaps",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | RDD.partitionBy | Return a copy of the RDD partitioned using the specified partitioner.
>>> pairs = sc.parallelize([1, 2, 3, 4, 2, 4, 1]).map(lambda x: (x, x))
>>> sets = pairs.partitionBy(2).glom().collect()
>>> len(set(sets[0]).intersection(set(sets[1])))
0 | python/pyspark/rdd.py | def partitionBy(self, numPartitions, partitionFunc=portable_hash):
"""
Return a copy of the RDD partitioned using the specified partitioner.
>>> pairs = sc.parallelize([1, 2, 3, 4, 2, 4, 1]).map(lambda x: (x, x))
>>> sets = pairs.partitionBy(2).glom().collect()
>>> len(set(sets[0]).intersection(set(sets[1])))
0
"""
if numPartitions is None:
numPartitions = self._defaultReducePartitions()
partitioner = Partitioner(numPartitions, partitionFunc)
if self.partitioner == partitioner:
return self
# Transferring O(n) objects to Java is too expensive.
# Instead, we'll form the hash buckets in Python,
# transferring O(numPartitions) objects to Java.
# Each object is a (splitNumber, [objects]) pair.
# In order to avoid too huge objects, the objects are
# grouped into chunks.
outputSerializer = self.ctx._unbatched_serializer
limit = (_parse_memory(self.ctx._conf.get(
"spark.python.worker.memory", "512m")) / 2)
def add_shuffle_key(split, iterator):
buckets = defaultdict(list)
c, batch = 0, min(10 * numPartitions, 1000)
for k, v in iterator:
buckets[partitionFunc(k) % numPartitions].append((k, v))
c += 1
# check used memory and avg size of chunk of objects
if (c % 1000 == 0 and get_used_memory() > limit
or c > batch):
n, size = len(buckets), 0
for split in list(buckets.keys()):
yield pack_long(split)
d = outputSerializer.dumps(buckets[split])
del buckets[split]
yield d
size += len(d)
avg = int(size / n) >> 20
# let 1M < avg < 10M
if avg < 1:
batch *= 1.5
elif avg > 10:
batch = max(int(batch / 1.5), 1)
c = 0
for split, items in buckets.items():
yield pack_long(split)
yield outputSerializer.dumps(items)
keyed = self.mapPartitionsWithIndex(add_shuffle_key, preservesPartitioning=True)
keyed._bypass_serializer = True
with SCCallSiteSync(self.context) as css:
pairRDD = self.ctx._jvm.PairwiseRDD(
keyed._jrdd.rdd()).asJavaPairRDD()
jpartitioner = self.ctx._jvm.PythonPartitioner(numPartitions,
id(partitionFunc))
jrdd = self.ctx._jvm.PythonRDD.valueOfPair(pairRDD.partitionBy(jpartitioner))
rdd = RDD(jrdd, self.ctx, BatchedSerializer(outputSerializer))
rdd.partitioner = partitioner
return rdd | def partitionBy(self, numPartitions, partitionFunc=portable_hash):
"""
Return a copy of the RDD partitioned using the specified partitioner.
>>> pairs = sc.parallelize([1, 2, 3, 4, 2, 4, 1]).map(lambda x: (x, x))
>>> sets = pairs.partitionBy(2).glom().collect()
>>> len(set(sets[0]).intersection(set(sets[1])))
0
"""
if numPartitions is None:
numPartitions = self._defaultReducePartitions()
partitioner = Partitioner(numPartitions, partitionFunc)
if self.partitioner == partitioner:
return self
# Transferring O(n) objects to Java is too expensive.
# Instead, we'll form the hash buckets in Python,
# transferring O(numPartitions) objects to Java.
# Each object is a (splitNumber, [objects]) pair.
# In order to avoid too huge objects, the objects are
# grouped into chunks.
outputSerializer = self.ctx._unbatched_serializer
limit = (_parse_memory(self.ctx._conf.get(
"spark.python.worker.memory", "512m")) / 2)
def add_shuffle_key(split, iterator):
buckets = defaultdict(list)
c, batch = 0, min(10 * numPartitions, 1000)
for k, v in iterator:
buckets[partitionFunc(k) % numPartitions].append((k, v))
c += 1
# check used memory and avg size of chunk of objects
if (c % 1000 == 0 and get_used_memory() > limit
or c > batch):
n, size = len(buckets), 0
for split in list(buckets.keys()):
yield pack_long(split)
d = outputSerializer.dumps(buckets[split])
del buckets[split]
yield d
size += len(d)
avg = int(size / n) >> 20
# let 1M < avg < 10M
if avg < 1:
batch *= 1.5
elif avg > 10:
batch = max(int(batch / 1.5), 1)
c = 0
for split, items in buckets.items():
yield pack_long(split)
yield outputSerializer.dumps(items)
keyed = self.mapPartitionsWithIndex(add_shuffle_key, preservesPartitioning=True)
keyed._bypass_serializer = True
with SCCallSiteSync(self.context) as css:
pairRDD = self.ctx._jvm.PairwiseRDD(
keyed._jrdd.rdd()).asJavaPairRDD()
jpartitioner = self.ctx._jvm.PythonPartitioner(numPartitions,
id(partitionFunc))
jrdd = self.ctx._jvm.PythonRDD.valueOfPair(pairRDD.partitionBy(jpartitioner))
rdd = RDD(jrdd, self.ctx, BatchedSerializer(outputSerializer))
rdd.partitioner = partitioner
return rdd | [
"Return",
"a",
"copy",
"of",
"the",
"RDD",
"partitioned",
"using",
"the",
"specified",
"partitioner",
"."
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L1742-L1810 | [
"def",
"partitionBy",
"(",
"self",
",",
"numPartitions",
",",
"partitionFunc",
"=",
"portable_hash",
")",
":",
"if",
"numPartitions",
"is",
"None",
":",
"numPartitions",
"=",
"self",
".",
"_defaultReducePartitions",
"(",
")",
"partitioner",
"=",
"Partitioner",
"(",
"numPartitions",
",",
"partitionFunc",
")",
"if",
"self",
".",
"partitioner",
"==",
"partitioner",
":",
"return",
"self",
"# Transferring O(n) objects to Java is too expensive.",
"# Instead, we'll form the hash buckets in Python,",
"# transferring O(numPartitions) objects to Java.",
"# Each object is a (splitNumber, [objects]) pair.",
"# In order to avoid too huge objects, the objects are",
"# grouped into chunks.",
"outputSerializer",
"=",
"self",
".",
"ctx",
".",
"_unbatched_serializer",
"limit",
"=",
"(",
"_parse_memory",
"(",
"self",
".",
"ctx",
".",
"_conf",
".",
"get",
"(",
"\"spark.python.worker.memory\"",
",",
"\"512m\"",
")",
")",
"/",
"2",
")",
"def",
"add_shuffle_key",
"(",
"split",
",",
"iterator",
")",
":",
"buckets",
"=",
"defaultdict",
"(",
"list",
")",
"c",
",",
"batch",
"=",
"0",
",",
"min",
"(",
"10",
"*",
"numPartitions",
",",
"1000",
")",
"for",
"k",
",",
"v",
"in",
"iterator",
":",
"buckets",
"[",
"partitionFunc",
"(",
"k",
")",
"%",
"numPartitions",
"]",
".",
"append",
"(",
"(",
"k",
",",
"v",
")",
")",
"c",
"+=",
"1",
"# check used memory and avg size of chunk of objects",
"if",
"(",
"c",
"%",
"1000",
"==",
"0",
"and",
"get_used_memory",
"(",
")",
">",
"limit",
"or",
"c",
">",
"batch",
")",
":",
"n",
",",
"size",
"=",
"len",
"(",
"buckets",
")",
",",
"0",
"for",
"split",
"in",
"list",
"(",
"buckets",
".",
"keys",
"(",
")",
")",
":",
"yield",
"pack_long",
"(",
"split",
")",
"d",
"=",
"outputSerializer",
".",
"dumps",
"(",
"buckets",
"[",
"split",
"]",
")",
"del",
"buckets",
"[",
"split",
"]",
"yield",
"d",
"size",
"+=",
"len",
"(",
"d",
")",
"avg",
"=",
"int",
"(",
"size",
"/",
"n",
")",
">>",
"20",
"# let 1M < avg < 10M",
"if",
"avg",
"<",
"1",
":",
"batch",
"*=",
"1.5",
"elif",
"avg",
">",
"10",
":",
"batch",
"=",
"max",
"(",
"int",
"(",
"batch",
"/",
"1.5",
")",
",",
"1",
")",
"c",
"=",
"0",
"for",
"split",
",",
"items",
"in",
"buckets",
".",
"items",
"(",
")",
":",
"yield",
"pack_long",
"(",
"split",
")",
"yield",
"outputSerializer",
".",
"dumps",
"(",
"items",
")",
"keyed",
"=",
"self",
".",
"mapPartitionsWithIndex",
"(",
"add_shuffle_key",
",",
"preservesPartitioning",
"=",
"True",
")",
"keyed",
".",
"_bypass_serializer",
"=",
"True",
"with",
"SCCallSiteSync",
"(",
"self",
".",
"context",
")",
"as",
"css",
":",
"pairRDD",
"=",
"self",
".",
"ctx",
".",
"_jvm",
".",
"PairwiseRDD",
"(",
"keyed",
".",
"_jrdd",
".",
"rdd",
"(",
")",
")",
".",
"asJavaPairRDD",
"(",
")",
"jpartitioner",
"=",
"self",
".",
"ctx",
".",
"_jvm",
".",
"PythonPartitioner",
"(",
"numPartitions",
",",
"id",
"(",
"partitionFunc",
")",
")",
"jrdd",
"=",
"self",
".",
"ctx",
".",
"_jvm",
".",
"PythonRDD",
".",
"valueOfPair",
"(",
"pairRDD",
".",
"partitionBy",
"(",
"jpartitioner",
")",
")",
"rdd",
"=",
"RDD",
"(",
"jrdd",
",",
"self",
".",
"ctx",
",",
"BatchedSerializer",
"(",
"outputSerializer",
")",
")",
"rdd",
".",
"partitioner",
"=",
"partitioner",
"return",
"rdd"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | RDD.combineByKey | Generic function to combine the elements for each key using a custom
set of aggregation functions.
Turns an RDD[(K, V)] into a result of type RDD[(K, C)], for a "combined
type" C.
Users provide three functions:
- C{createCombiner}, which turns a V into a C (e.g., creates
a one-element list)
- C{mergeValue}, to merge a V into a C (e.g., adds it to the end of
a list)
- C{mergeCombiners}, to combine two C's into a single one (e.g., merges
the lists)
To avoid memory allocation, both mergeValue and mergeCombiners are allowed to
modify and return their first argument instead of creating a new C.
In addition, users can control the partitioning of the output RDD.
.. note:: V and C can be different -- for example, one might group an RDD of type
(Int, Int) into an RDD of type (Int, List[Int]).
>>> x = sc.parallelize([("a", 1), ("b", 1), ("a", 2)])
>>> def to_list(a):
... return [a]
...
>>> def append(a, b):
... a.append(b)
... return a
...
>>> def extend(a, b):
... a.extend(b)
... return a
...
>>> sorted(x.combineByKey(to_list, append, extend).collect())
[('a', [1, 2]), ('b', [1])] | python/pyspark/rdd.py | def combineByKey(self, createCombiner, mergeValue, mergeCombiners,
numPartitions=None, partitionFunc=portable_hash):
"""
Generic function to combine the elements for each key using a custom
set of aggregation functions.
Turns an RDD[(K, V)] into a result of type RDD[(K, C)], for a "combined
type" C.
Users provide three functions:
- C{createCombiner}, which turns a V into a C (e.g., creates
a one-element list)
- C{mergeValue}, to merge a V into a C (e.g., adds it to the end of
a list)
- C{mergeCombiners}, to combine two C's into a single one (e.g., merges
the lists)
To avoid memory allocation, both mergeValue and mergeCombiners are allowed to
modify and return their first argument instead of creating a new C.
In addition, users can control the partitioning of the output RDD.
.. note:: V and C can be different -- for example, one might group an RDD of type
(Int, Int) into an RDD of type (Int, List[Int]).
>>> x = sc.parallelize([("a", 1), ("b", 1), ("a", 2)])
>>> def to_list(a):
... return [a]
...
>>> def append(a, b):
... a.append(b)
... return a
...
>>> def extend(a, b):
... a.extend(b)
... return a
...
>>> sorted(x.combineByKey(to_list, append, extend).collect())
[('a', [1, 2]), ('b', [1])]
"""
if numPartitions is None:
numPartitions = self._defaultReducePartitions()
serializer = self.ctx.serializer
memory = self._memory_limit()
agg = Aggregator(createCombiner, mergeValue, mergeCombiners)
def combineLocally(iterator):
merger = ExternalMerger(agg, memory * 0.9, serializer)
merger.mergeValues(iterator)
return merger.items()
locally_combined = self.mapPartitions(combineLocally, preservesPartitioning=True)
shuffled = locally_combined.partitionBy(numPartitions, partitionFunc)
def _mergeCombiners(iterator):
merger = ExternalMerger(agg, memory, serializer)
merger.mergeCombiners(iterator)
return merger.items()
return shuffled.mapPartitions(_mergeCombiners, preservesPartitioning=True) | def combineByKey(self, createCombiner, mergeValue, mergeCombiners,
numPartitions=None, partitionFunc=portable_hash):
"""
Generic function to combine the elements for each key using a custom
set of aggregation functions.
Turns an RDD[(K, V)] into a result of type RDD[(K, C)], for a "combined
type" C.
Users provide three functions:
- C{createCombiner}, which turns a V into a C (e.g., creates
a one-element list)
- C{mergeValue}, to merge a V into a C (e.g., adds it to the end of
a list)
- C{mergeCombiners}, to combine two C's into a single one (e.g., merges
the lists)
To avoid memory allocation, both mergeValue and mergeCombiners are allowed to
modify and return their first argument instead of creating a new C.
In addition, users can control the partitioning of the output RDD.
.. note:: V and C can be different -- for example, one might group an RDD of type
(Int, Int) into an RDD of type (Int, List[Int]).
>>> x = sc.parallelize([("a", 1), ("b", 1), ("a", 2)])
>>> def to_list(a):
... return [a]
...
>>> def append(a, b):
... a.append(b)
... return a
...
>>> def extend(a, b):
... a.extend(b)
... return a
...
>>> sorted(x.combineByKey(to_list, append, extend).collect())
[('a', [1, 2]), ('b', [1])]
"""
if numPartitions is None:
numPartitions = self._defaultReducePartitions()
serializer = self.ctx.serializer
memory = self._memory_limit()
agg = Aggregator(createCombiner, mergeValue, mergeCombiners)
def combineLocally(iterator):
merger = ExternalMerger(agg, memory * 0.9, serializer)
merger.mergeValues(iterator)
return merger.items()
locally_combined = self.mapPartitions(combineLocally, preservesPartitioning=True)
shuffled = locally_combined.partitionBy(numPartitions, partitionFunc)
def _mergeCombiners(iterator):
merger = ExternalMerger(agg, memory, serializer)
merger.mergeCombiners(iterator)
return merger.items()
return shuffled.mapPartitions(_mergeCombiners, preservesPartitioning=True) | [
"Generic",
"function",
"to",
"combine",
"the",
"elements",
"for",
"each",
"key",
"using",
"a",
"custom",
"set",
"of",
"aggregation",
"functions",
"."
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L1813-L1874 | [
"def",
"combineByKey",
"(",
"self",
",",
"createCombiner",
",",
"mergeValue",
",",
"mergeCombiners",
",",
"numPartitions",
"=",
"None",
",",
"partitionFunc",
"=",
"portable_hash",
")",
":",
"if",
"numPartitions",
"is",
"None",
":",
"numPartitions",
"=",
"self",
".",
"_defaultReducePartitions",
"(",
")",
"serializer",
"=",
"self",
".",
"ctx",
".",
"serializer",
"memory",
"=",
"self",
".",
"_memory_limit",
"(",
")",
"agg",
"=",
"Aggregator",
"(",
"createCombiner",
",",
"mergeValue",
",",
"mergeCombiners",
")",
"def",
"combineLocally",
"(",
"iterator",
")",
":",
"merger",
"=",
"ExternalMerger",
"(",
"agg",
",",
"memory",
"*",
"0.9",
",",
"serializer",
")",
"merger",
".",
"mergeValues",
"(",
"iterator",
")",
"return",
"merger",
".",
"items",
"(",
")",
"locally_combined",
"=",
"self",
".",
"mapPartitions",
"(",
"combineLocally",
",",
"preservesPartitioning",
"=",
"True",
")",
"shuffled",
"=",
"locally_combined",
".",
"partitionBy",
"(",
"numPartitions",
",",
"partitionFunc",
")",
"def",
"_mergeCombiners",
"(",
"iterator",
")",
":",
"merger",
"=",
"ExternalMerger",
"(",
"agg",
",",
"memory",
",",
"serializer",
")",
"merger",
".",
"mergeCombiners",
"(",
"iterator",
")",
"return",
"merger",
".",
"items",
"(",
")",
"return",
"shuffled",
".",
"mapPartitions",
"(",
"_mergeCombiners",
",",
"preservesPartitioning",
"=",
"True",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | RDD.aggregateByKey | Aggregate the values of each key, using given combine functions and a neutral
"zero value". This function can return a different result type, U, than the type
of the values in this RDD, V. Thus, we need one operation for merging a V into
a U and one operation for merging two U's, The former operation is used for merging
values within a partition, and the latter is used for merging values between
partitions. To avoid memory allocation, both of these functions are
allowed to modify and return their first argument instead of creating a new U. | python/pyspark/rdd.py | def aggregateByKey(self, zeroValue, seqFunc, combFunc, numPartitions=None,
partitionFunc=portable_hash):
"""
Aggregate the values of each key, using given combine functions and a neutral
"zero value". This function can return a different result type, U, than the type
of the values in this RDD, V. Thus, we need one operation for merging a V into
a U and one operation for merging two U's, The former operation is used for merging
values within a partition, and the latter is used for merging values between
partitions. To avoid memory allocation, both of these functions are
allowed to modify and return their first argument instead of creating a new U.
"""
def createZero():
return copy.deepcopy(zeroValue)
return self.combineByKey(
lambda v: seqFunc(createZero(), v), seqFunc, combFunc, numPartitions, partitionFunc) | def aggregateByKey(self, zeroValue, seqFunc, combFunc, numPartitions=None,
partitionFunc=portable_hash):
"""
Aggregate the values of each key, using given combine functions and a neutral
"zero value". This function can return a different result type, U, than the type
of the values in this RDD, V. Thus, we need one operation for merging a V into
a U and one operation for merging two U's, The former operation is used for merging
values within a partition, and the latter is used for merging values between
partitions. To avoid memory allocation, both of these functions are
allowed to modify and return their first argument instead of creating a new U.
"""
def createZero():
return copy.deepcopy(zeroValue)
return self.combineByKey(
lambda v: seqFunc(createZero(), v), seqFunc, combFunc, numPartitions, partitionFunc) | [
"Aggregate",
"the",
"values",
"of",
"each",
"key",
"using",
"given",
"combine",
"functions",
"and",
"a",
"neutral",
"zero",
"value",
".",
"This",
"function",
"can",
"return",
"a",
"different",
"result",
"type",
"U",
"than",
"the",
"type",
"of",
"the",
"values",
"in",
"this",
"RDD",
"V",
".",
"Thus",
"we",
"need",
"one",
"operation",
"for",
"merging",
"a",
"V",
"into",
"a",
"U",
"and",
"one",
"operation",
"for",
"merging",
"two",
"U",
"s",
"The",
"former",
"operation",
"is",
"used",
"for",
"merging",
"values",
"within",
"a",
"partition",
"and",
"the",
"latter",
"is",
"used",
"for",
"merging",
"values",
"between",
"partitions",
".",
"To",
"avoid",
"memory",
"allocation",
"both",
"of",
"these",
"functions",
"are",
"allowed",
"to",
"modify",
"and",
"return",
"their",
"first",
"argument",
"instead",
"of",
"creating",
"a",
"new",
"U",
"."
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L1876-L1891 | [
"def",
"aggregateByKey",
"(",
"self",
",",
"zeroValue",
",",
"seqFunc",
",",
"combFunc",
",",
"numPartitions",
"=",
"None",
",",
"partitionFunc",
"=",
"portable_hash",
")",
":",
"def",
"createZero",
"(",
")",
":",
"return",
"copy",
".",
"deepcopy",
"(",
"zeroValue",
")",
"return",
"self",
".",
"combineByKey",
"(",
"lambda",
"v",
":",
"seqFunc",
"(",
"createZero",
"(",
")",
",",
"v",
")",
",",
"seqFunc",
",",
"combFunc",
",",
"numPartitions",
",",
"partitionFunc",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | RDD.foldByKey | Merge the values for each key using an associative function "func"
and a neutral "zeroValue" which may be added to the result an
arbitrary number of times, and must not change the result
(e.g., 0 for addition, or 1 for multiplication.).
>>> rdd = sc.parallelize([("a", 1), ("b", 1), ("a", 1)])
>>> from operator import add
>>> sorted(rdd.foldByKey(0, add).collect())
[('a', 2), ('b', 1)] | python/pyspark/rdd.py | def foldByKey(self, zeroValue, func, numPartitions=None, partitionFunc=portable_hash):
"""
Merge the values for each key using an associative function "func"
and a neutral "zeroValue" which may be added to the result an
arbitrary number of times, and must not change the result
(e.g., 0 for addition, or 1 for multiplication.).
>>> rdd = sc.parallelize([("a", 1), ("b", 1), ("a", 1)])
>>> from operator import add
>>> sorted(rdd.foldByKey(0, add).collect())
[('a', 2), ('b', 1)]
"""
def createZero():
return copy.deepcopy(zeroValue)
return self.combineByKey(lambda v: func(createZero(), v), func, func, numPartitions,
partitionFunc) | def foldByKey(self, zeroValue, func, numPartitions=None, partitionFunc=portable_hash):
"""
Merge the values for each key using an associative function "func"
and a neutral "zeroValue" which may be added to the result an
arbitrary number of times, and must not change the result
(e.g., 0 for addition, or 1 for multiplication.).
>>> rdd = sc.parallelize([("a", 1), ("b", 1), ("a", 1)])
>>> from operator import add
>>> sorted(rdd.foldByKey(0, add).collect())
[('a', 2), ('b', 1)]
"""
def createZero():
return copy.deepcopy(zeroValue)
return self.combineByKey(lambda v: func(createZero(), v), func, func, numPartitions,
partitionFunc) | [
"Merge",
"the",
"values",
"for",
"each",
"key",
"using",
"an",
"associative",
"function",
"func",
"and",
"a",
"neutral",
"zeroValue",
"which",
"may",
"be",
"added",
"to",
"the",
"result",
"an",
"arbitrary",
"number",
"of",
"times",
"and",
"must",
"not",
"change",
"the",
"result",
"(",
"e",
".",
"g",
".",
"0",
"for",
"addition",
"or",
"1",
"for",
"multiplication",
".",
")",
"."
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L1893-L1909 | [
"def",
"foldByKey",
"(",
"self",
",",
"zeroValue",
",",
"func",
",",
"numPartitions",
"=",
"None",
",",
"partitionFunc",
"=",
"portable_hash",
")",
":",
"def",
"createZero",
"(",
")",
":",
"return",
"copy",
".",
"deepcopy",
"(",
"zeroValue",
")",
"return",
"self",
".",
"combineByKey",
"(",
"lambda",
"v",
":",
"func",
"(",
"createZero",
"(",
")",
",",
"v",
")",
",",
"func",
",",
"func",
",",
"numPartitions",
",",
"partitionFunc",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | RDD.groupByKey | Group the values for each key in the RDD into a single sequence.
Hash-partitions the resulting RDD with numPartitions partitions.
.. note:: If you are grouping in order to perform an aggregation (such as a
sum or average) over each key, using reduceByKey or aggregateByKey will
provide much better performance.
>>> rdd = sc.parallelize([("a", 1), ("b", 1), ("a", 1)])
>>> sorted(rdd.groupByKey().mapValues(len).collect())
[('a', 2), ('b', 1)]
>>> sorted(rdd.groupByKey().mapValues(list).collect())
[('a', [1, 1]), ('b', [1])] | python/pyspark/rdd.py | def groupByKey(self, numPartitions=None, partitionFunc=portable_hash):
"""
Group the values for each key in the RDD into a single sequence.
Hash-partitions the resulting RDD with numPartitions partitions.
.. note:: If you are grouping in order to perform an aggregation (such as a
sum or average) over each key, using reduceByKey or aggregateByKey will
provide much better performance.
>>> rdd = sc.parallelize([("a", 1), ("b", 1), ("a", 1)])
>>> sorted(rdd.groupByKey().mapValues(len).collect())
[('a', 2), ('b', 1)]
>>> sorted(rdd.groupByKey().mapValues(list).collect())
[('a', [1, 1]), ('b', [1])]
"""
def createCombiner(x):
return [x]
def mergeValue(xs, x):
xs.append(x)
return xs
def mergeCombiners(a, b):
a.extend(b)
return a
memory = self._memory_limit()
serializer = self._jrdd_deserializer
agg = Aggregator(createCombiner, mergeValue, mergeCombiners)
def combine(iterator):
merger = ExternalMerger(agg, memory * 0.9, serializer)
merger.mergeValues(iterator)
return merger.items()
locally_combined = self.mapPartitions(combine, preservesPartitioning=True)
shuffled = locally_combined.partitionBy(numPartitions, partitionFunc)
def groupByKey(it):
merger = ExternalGroupBy(agg, memory, serializer)
merger.mergeCombiners(it)
return merger.items()
return shuffled.mapPartitions(groupByKey, True).mapValues(ResultIterable) | def groupByKey(self, numPartitions=None, partitionFunc=portable_hash):
"""
Group the values for each key in the RDD into a single sequence.
Hash-partitions the resulting RDD with numPartitions partitions.
.. note:: If you are grouping in order to perform an aggregation (such as a
sum or average) over each key, using reduceByKey or aggregateByKey will
provide much better performance.
>>> rdd = sc.parallelize([("a", 1), ("b", 1), ("a", 1)])
>>> sorted(rdd.groupByKey().mapValues(len).collect())
[('a', 2), ('b', 1)]
>>> sorted(rdd.groupByKey().mapValues(list).collect())
[('a', [1, 1]), ('b', [1])]
"""
def createCombiner(x):
return [x]
def mergeValue(xs, x):
xs.append(x)
return xs
def mergeCombiners(a, b):
a.extend(b)
return a
memory = self._memory_limit()
serializer = self._jrdd_deserializer
agg = Aggregator(createCombiner, mergeValue, mergeCombiners)
def combine(iterator):
merger = ExternalMerger(agg, memory * 0.9, serializer)
merger.mergeValues(iterator)
return merger.items()
locally_combined = self.mapPartitions(combine, preservesPartitioning=True)
shuffled = locally_combined.partitionBy(numPartitions, partitionFunc)
def groupByKey(it):
merger = ExternalGroupBy(agg, memory, serializer)
merger.mergeCombiners(it)
return merger.items()
return shuffled.mapPartitions(groupByKey, True).mapValues(ResultIterable) | [
"Group",
"the",
"values",
"for",
"each",
"key",
"in",
"the",
"RDD",
"into",
"a",
"single",
"sequence",
".",
"Hash",
"-",
"partitions",
"the",
"resulting",
"RDD",
"with",
"numPartitions",
"partitions",
"."
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L1915-L1958 | [
"def",
"groupByKey",
"(",
"self",
",",
"numPartitions",
"=",
"None",
",",
"partitionFunc",
"=",
"portable_hash",
")",
":",
"def",
"createCombiner",
"(",
"x",
")",
":",
"return",
"[",
"x",
"]",
"def",
"mergeValue",
"(",
"xs",
",",
"x",
")",
":",
"xs",
".",
"append",
"(",
"x",
")",
"return",
"xs",
"def",
"mergeCombiners",
"(",
"a",
",",
"b",
")",
":",
"a",
".",
"extend",
"(",
"b",
")",
"return",
"a",
"memory",
"=",
"self",
".",
"_memory_limit",
"(",
")",
"serializer",
"=",
"self",
".",
"_jrdd_deserializer",
"agg",
"=",
"Aggregator",
"(",
"createCombiner",
",",
"mergeValue",
",",
"mergeCombiners",
")",
"def",
"combine",
"(",
"iterator",
")",
":",
"merger",
"=",
"ExternalMerger",
"(",
"agg",
",",
"memory",
"*",
"0.9",
",",
"serializer",
")",
"merger",
".",
"mergeValues",
"(",
"iterator",
")",
"return",
"merger",
".",
"items",
"(",
")",
"locally_combined",
"=",
"self",
".",
"mapPartitions",
"(",
"combine",
",",
"preservesPartitioning",
"=",
"True",
")",
"shuffled",
"=",
"locally_combined",
".",
"partitionBy",
"(",
"numPartitions",
",",
"partitionFunc",
")",
"def",
"groupByKey",
"(",
"it",
")",
":",
"merger",
"=",
"ExternalGroupBy",
"(",
"agg",
",",
"memory",
",",
"serializer",
")",
"merger",
".",
"mergeCombiners",
"(",
"it",
")",
"return",
"merger",
".",
"items",
"(",
")",
"return",
"shuffled",
".",
"mapPartitions",
"(",
"groupByKey",
",",
"True",
")",
".",
"mapValues",
"(",
"ResultIterable",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | RDD.flatMapValues | Pass each value in the key-value pair RDD through a flatMap function
without changing the keys; this also retains the original RDD's
partitioning.
>>> x = sc.parallelize([("a", ["x", "y", "z"]), ("b", ["p", "r"])])
>>> def f(x): return x
>>> x.flatMapValues(f).collect()
[('a', 'x'), ('a', 'y'), ('a', 'z'), ('b', 'p'), ('b', 'r')] | python/pyspark/rdd.py | def flatMapValues(self, f):
"""
Pass each value in the key-value pair RDD through a flatMap function
without changing the keys; this also retains the original RDD's
partitioning.
>>> x = sc.parallelize([("a", ["x", "y", "z"]), ("b", ["p", "r"])])
>>> def f(x): return x
>>> x.flatMapValues(f).collect()
[('a', 'x'), ('a', 'y'), ('a', 'z'), ('b', 'p'), ('b', 'r')]
"""
flat_map_fn = lambda kv: ((kv[0], x) for x in f(kv[1]))
return self.flatMap(flat_map_fn, preservesPartitioning=True) | def flatMapValues(self, f):
"""
Pass each value in the key-value pair RDD through a flatMap function
without changing the keys; this also retains the original RDD's
partitioning.
>>> x = sc.parallelize([("a", ["x", "y", "z"]), ("b", ["p", "r"])])
>>> def f(x): return x
>>> x.flatMapValues(f).collect()
[('a', 'x'), ('a', 'y'), ('a', 'z'), ('b', 'p'), ('b', 'r')]
"""
flat_map_fn = lambda kv: ((kv[0], x) for x in f(kv[1]))
return self.flatMap(flat_map_fn, preservesPartitioning=True) | [
"Pass",
"each",
"value",
"in",
"the",
"key",
"-",
"value",
"pair",
"RDD",
"through",
"a",
"flatMap",
"function",
"without",
"changing",
"the",
"keys",
";",
"this",
"also",
"retains",
"the",
"original",
"RDD",
"s",
"partitioning",
"."
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L1960-L1972 | [
"def",
"flatMapValues",
"(",
"self",
",",
"f",
")",
":",
"flat_map_fn",
"=",
"lambda",
"kv",
":",
"(",
"(",
"kv",
"[",
"0",
"]",
",",
"x",
")",
"for",
"x",
"in",
"f",
"(",
"kv",
"[",
"1",
"]",
")",
")",
"return",
"self",
".",
"flatMap",
"(",
"flat_map_fn",
",",
"preservesPartitioning",
"=",
"True",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | RDD.mapValues | Pass each value in the key-value pair RDD through a map function
without changing the keys; this also retains the original RDD's
partitioning.
>>> x = sc.parallelize([("a", ["apple", "banana", "lemon"]), ("b", ["grapes"])])
>>> def f(x): return len(x)
>>> x.mapValues(f).collect()
[('a', 3), ('b', 1)] | python/pyspark/rdd.py | def mapValues(self, f):
"""
Pass each value in the key-value pair RDD through a map function
without changing the keys; this also retains the original RDD's
partitioning.
>>> x = sc.parallelize([("a", ["apple", "banana", "lemon"]), ("b", ["grapes"])])
>>> def f(x): return len(x)
>>> x.mapValues(f).collect()
[('a', 3), ('b', 1)]
"""
map_values_fn = lambda kv: (kv[0], f(kv[1]))
return self.map(map_values_fn, preservesPartitioning=True) | def mapValues(self, f):
"""
Pass each value in the key-value pair RDD through a map function
without changing the keys; this also retains the original RDD's
partitioning.
>>> x = sc.parallelize([("a", ["apple", "banana", "lemon"]), ("b", ["grapes"])])
>>> def f(x): return len(x)
>>> x.mapValues(f).collect()
[('a', 3), ('b', 1)]
"""
map_values_fn = lambda kv: (kv[0], f(kv[1]))
return self.map(map_values_fn, preservesPartitioning=True) | [
"Pass",
"each",
"value",
"in",
"the",
"key",
"-",
"value",
"pair",
"RDD",
"through",
"a",
"map",
"function",
"without",
"changing",
"the",
"keys",
";",
"this",
"also",
"retains",
"the",
"original",
"RDD",
"s",
"partitioning",
"."
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L1974-L1986 | [
"def",
"mapValues",
"(",
"self",
",",
"f",
")",
":",
"map_values_fn",
"=",
"lambda",
"kv",
":",
"(",
"kv",
"[",
"0",
"]",
",",
"f",
"(",
"kv",
"[",
"1",
"]",
")",
")",
"return",
"self",
".",
"map",
"(",
"map_values_fn",
",",
"preservesPartitioning",
"=",
"True",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | RDD.sampleByKey | Return a subset of this RDD sampled by key (via stratified sampling).
Create a sample of this RDD using variable sampling rates for
different keys as specified by fractions, a key to sampling rate map.
>>> fractions = {"a": 0.2, "b": 0.1}
>>> rdd = sc.parallelize(fractions.keys()).cartesian(sc.parallelize(range(0, 1000)))
>>> sample = dict(rdd.sampleByKey(False, fractions, 2).groupByKey().collect())
>>> 100 < len(sample["a"]) < 300 and 50 < len(sample["b"]) < 150
True
>>> max(sample["a"]) <= 999 and min(sample["a"]) >= 0
True
>>> max(sample["b"]) <= 999 and min(sample["b"]) >= 0
True | python/pyspark/rdd.py | def sampleByKey(self, withReplacement, fractions, seed=None):
"""
Return a subset of this RDD sampled by key (via stratified sampling).
Create a sample of this RDD using variable sampling rates for
different keys as specified by fractions, a key to sampling rate map.
>>> fractions = {"a": 0.2, "b": 0.1}
>>> rdd = sc.parallelize(fractions.keys()).cartesian(sc.parallelize(range(0, 1000)))
>>> sample = dict(rdd.sampleByKey(False, fractions, 2).groupByKey().collect())
>>> 100 < len(sample["a"]) < 300 and 50 < len(sample["b"]) < 150
True
>>> max(sample["a"]) <= 999 and min(sample["a"]) >= 0
True
>>> max(sample["b"]) <= 999 and min(sample["b"]) >= 0
True
"""
for fraction in fractions.values():
assert fraction >= 0.0, "Negative fraction value: %s" % fraction
return self.mapPartitionsWithIndex(
RDDStratifiedSampler(withReplacement, fractions, seed).func, True) | def sampleByKey(self, withReplacement, fractions, seed=None):
"""
Return a subset of this RDD sampled by key (via stratified sampling).
Create a sample of this RDD using variable sampling rates for
different keys as specified by fractions, a key to sampling rate map.
>>> fractions = {"a": 0.2, "b": 0.1}
>>> rdd = sc.parallelize(fractions.keys()).cartesian(sc.parallelize(range(0, 1000)))
>>> sample = dict(rdd.sampleByKey(False, fractions, 2).groupByKey().collect())
>>> 100 < len(sample["a"]) < 300 and 50 < len(sample["b"]) < 150
True
>>> max(sample["a"]) <= 999 and min(sample["a"]) >= 0
True
>>> max(sample["b"]) <= 999 and min(sample["b"]) >= 0
True
"""
for fraction in fractions.values():
assert fraction >= 0.0, "Negative fraction value: %s" % fraction
return self.mapPartitionsWithIndex(
RDDStratifiedSampler(withReplacement, fractions, seed).func, True) | [
"Return",
"a",
"subset",
"of",
"this",
"RDD",
"sampled",
"by",
"key",
"(",
"via",
"stratified",
"sampling",
")",
".",
"Create",
"a",
"sample",
"of",
"this",
"RDD",
"using",
"variable",
"sampling",
"rates",
"for",
"different",
"keys",
"as",
"specified",
"by",
"fractions",
"a",
"key",
"to",
"sampling",
"rate",
"map",
"."
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L2016-L2035 | [
"def",
"sampleByKey",
"(",
"self",
",",
"withReplacement",
",",
"fractions",
",",
"seed",
"=",
"None",
")",
":",
"for",
"fraction",
"in",
"fractions",
".",
"values",
"(",
")",
":",
"assert",
"fraction",
">=",
"0.0",
",",
"\"Negative fraction value: %s\"",
"%",
"fraction",
"return",
"self",
".",
"mapPartitionsWithIndex",
"(",
"RDDStratifiedSampler",
"(",
"withReplacement",
",",
"fractions",
",",
"seed",
")",
".",
"func",
",",
"True",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | RDD.subtractByKey | Return each (key, value) pair in C{self} that has no pair with matching
key in C{other}.
>>> x = sc.parallelize([("a", 1), ("b", 4), ("b", 5), ("a", 2)])
>>> y = sc.parallelize([("a", 3), ("c", None)])
>>> sorted(x.subtractByKey(y).collect())
[('b', 4), ('b', 5)] | python/pyspark/rdd.py | def subtractByKey(self, other, numPartitions=None):
"""
Return each (key, value) pair in C{self} that has no pair with matching
key in C{other}.
>>> x = sc.parallelize([("a", 1), ("b", 4), ("b", 5), ("a", 2)])
>>> y = sc.parallelize([("a", 3), ("c", None)])
>>> sorted(x.subtractByKey(y).collect())
[('b', 4), ('b', 5)]
"""
def filter_func(pair):
key, (val1, val2) = pair
return val1 and not val2
return self.cogroup(other, numPartitions).filter(filter_func).flatMapValues(lambda x: x[0]) | def subtractByKey(self, other, numPartitions=None):
"""
Return each (key, value) pair in C{self} that has no pair with matching
key in C{other}.
>>> x = sc.parallelize([("a", 1), ("b", 4), ("b", 5), ("a", 2)])
>>> y = sc.parallelize([("a", 3), ("c", None)])
>>> sorted(x.subtractByKey(y).collect())
[('b', 4), ('b', 5)]
"""
def filter_func(pair):
key, (val1, val2) = pair
return val1 and not val2
return self.cogroup(other, numPartitions).filter(filter_func).flatMapValues(lambda x: x[0]) | [
"Return",
"each",
"(",
"key",
"value",
")",
"pair",
"in",
"C",
"{",
"self",
"}",
"that",
"has",
"no",
"pair",
"with",
"matching",
"key",
"in",
"C",
"{",
"other",
"}",
"."
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L2037-L2050 | [
"def",
"subtractByKey",
"(",
"self",
",",
"other",
",",
"numPartitions",
"=",
"None",
")",
":",
"def",
"filter_func",
"(",
"pair",
")",
":",
"key",
",",
"(",
"val1",
",",
"val2",
")",
"=",
"pair",
"return",
"val1",
"and",
"not",
"val2",
"return",
"self",
".",
"cogroup",
"(",
"other",
",",
"numPartitions",
")",
".",
"filter",
"(",
"filter_func",
")",
".",
"flatMapValues",
"(",
"lambda",
"x",
":",
"x",
"[",
"0",
"]",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | RDD.subtract | Return each value in C{self} that is not contained in C{other}.
>>> x = sc.parallelize([("a", 1), ("b", 4), ("b", 5), ("a", 3)])
>>> y = sc.parallelize([("a", 3), ("c", None)])
>>> sorted(x.subtract(y).collect())
[('a', 1), ('b', 4), ('b', 5)] | python/pyspark/rdd.py | def subtract(self, other, numPartitions=None):
"""
Return each value in C{self} that is not contained in C{other}.
>>> x = sc.parallelize([("a", 1), ("b", 4), ("b", 5), ("a", 3)])
>>> y = sc.parallelize([("a", 3), ("c", None)])
>>> sorted(x.subtract(y).collect())
[('a', 1), ('b', 4), ('b', 5)]
"""
# note: here 'True' is just a placeholder
rdd = other.map(lambda x: (x, True))
return self.map(lambda x: (x, True)).subtractByKey(rdd, numPartitions).keys() | def subtract(self, other, numPartitions=None):
"""
Return each value in C{self} that is not contained in C{other}.
>>> x = sc.parallelize([("a", 1), ("b", 4), ("b", 5), ("a", 3)])
>>> y = sc.parallelize([("a", 3), ("c", None)])
>>> sorted(x.subtract(y).collect())
[('a', 1), ('b', 4), ('b', 5)]
"""
# note: here 'True' is just a placeholder
rdd = other.map(lambda x: (x, True))
return self.map(lambda x: (x, True)).subtractByKey(rdd, numPartitions).keys() | [
"Return",
"each",
"value",
"in",
"C",
"{",
"self",
"}",
"that",
"is",
"not",
"contained",
"in",
"C",
"{",
"other",
"}",
"."
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L2052-L2063 | [
"def",
"subtract",
"(",
"self",
",",
"other",
",",
"numPartitions",
"=",
"None",
")",
":",
"# note: here 'True' is just a placeholder",
"rdd",
"=",
"other",
".",
"map",
"(",
"lambda",
"x",
":",
"(",
"x",
",",
"True",
")",
")",
"return",
"self",
".",
"map",
"(",
"lambda",
"x",
":",
"(",
"x",
",",
"True",
")",
")",
".",
"subtractByKey",
"(",
"rdd",
",",
"numPartitions",
")",
".",
"keys",
"(",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | RDD.coalesce | Return a new RDD that is reduced into `numPartitions` partitions.
>>> sc.parallelize([1, 2, 3, 4, 5], 3).glom().collect()
[[1], [2, 3], [4, 5]]
>>> sc.parallelize([1, 2, 3, 4, 5], 3).coalesce(1).glom().collect()
[[1, 2, 3, 4, 5]] | python/pyspark/rdd.py | def coalesce(self, numPartitions, shuffle=False):
"""
Return a new RDD that is reduced into `numPartitions` partitions.
>>> sc.parallelize([1, 2, 3, 4, 5], 3).glom().collect()
[[1], [2, 3], [4, 5]]
>>> sc.parallelize([1, 2, 3, 4, 5], 3).coalesce(1).glom().collect()
[[1, 2, 3, 4, 5]]
"""
if shuffle:
# Decrease the batch size in order to distribute evenly the elements across output
# partitions. Otherwise, repartition will possibly produce highly skewed partitions.
batchSize = min(10, self.ctx._batchSize or 1024)
ser = BatchedSerializer(PickleSerializer(), batchSize)
selfCopy = self._reserialize(ser)
jrdd_deserializer = selfCopy._jrdd_deserializer
jrdd = selfCopy._jrdd.coalesce(numPartitions, shuffle)
else:
jrdd_deserializer = self._jrdd_deserializer
jrdd = self._jrdd.coalesce(numPartitions, shuffle)
return RDD(jrdd, self.ctx, jrdd_deserializer) | def coalesce(self, numPartitions, shuffle=False):
"""
Return a new RDD that is reduced into `numPartitions` partitions.
>>> sc.parallelize([1, 2, 3, 4, 5], 3).glom().collect()
[[1], [2, 3], [4, 5]]
>>> sc.parallelize([1, 2, 3, 4, 5], 3).coalesce(1).glom().collect()
[[1, 2, 3, 4, 5]]
"""
if shuffle:
# Decrease the batch size in order to distribute evenly the elements across output
# partitions. Otherwise, repartition will possibly produce highly skewed partitions.
batchSize = min(10, self.ctx._batchSize or 1024)
ser = BatchedSerializer(PickleSerializer(), batchSize)
selfCopy = self._reserialize(ser)
jrdd_deserializer = selfCopy._jrdd_deserializer
jrdd = selfCopy._jrdd.coalesce(numPartitions, shuffle)
else:
jrdd_deserializer = self._jrdd_deserializer
jrdd = self._jrdd.coalesce(numPartitions, shuffle)
return RDD(jrdd, self.ctx, jrdd_deserializer) | [
"Return",
"a",
"new",
"RDD",
"that",
"is",
"reduced",
"into",
"numPartitions",
"partitions",
"."
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L2095-L2115 | [
"def",
"coalesce",
"(",
"self",
",",
"numPartitions",
",",
"shuffle",
"=",
"False",
")",
":",
"if",
"shuffle",
":",
"# Decrease the batch size in order to distribute evenly the elements across output",
"# partitions. Otherwise, repartition will possibly produce highly skewed partitions.",
"batchSize",
"=",
"min",
"(",
"10",
",",
"self",
".",
"ctx",
".",
"_batchSize",
"or",
"1024",
")",
"ser",
"=",
"BatchedSerializer",
"(",
"PickleSerializer",
"(",
")",
",",
"batchSize",
")",
"selfCopy",
"=",
"self",
".",
"_reserialize",
"(",
"ser",
")",
"jrdd_deserializer",
"=",
"selfCopy",
".",
"_jrdd_deserializer",
"jrdd",
"=",
"selfCopy",
".",
"_jrdd",
".",
"coalesce",
"(",
"numPartitions",
",",
"shuffle",
")",
"else",
":",
"jrdd_deserializer",
"=",
"self",
".",
"_jrdd_deserializer",
"jrdd",
"=",
"self",
".",
"_jrdd",
".",
"coalesce",
"(",
"numPartitions",
",",
"shuffle",
")",
"return",
"RDD",
"(",
"jrdd",
",",
"self",
".",
"ctx",
",",
"jrdd_deserializer",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | RDD.zip | Zips this RDD with another one, returning key-value pairs with the
first element in each RDD second element in each RDD, etc. Assumes
that the two RDDs have the same number of partitions and the same
number of elements in each partition (e.g. one was made through
a map on the other).
>>> x = sc.parallelize(range(0,5))
>>> y = sc.parallelize(range(1000, 1005))
>>> x.zip(y).collect()
[(0, 1000), (1, 1001), (2, 1002), (3, 1003), (4, 1004)] | python/pyspark/rdd.py | def zip(self, other):
"""
Zips this RDD with another one, returning key-value pairs with the
first element in each RDD second element in each RDD, etc. Assumes
that the two RDDs have the same number of partitions and the same
number of elements in each partition (e.g. one was made through
a map on the other).
>>> x = sc.parallelize(range(0,5))
>>> y = sc.parallelize(range(1000, 1005))
>>> x.zip(y).collect()
[(0, 1000), (1, 1001), (2, 1002), (3, 1003), (4, 1004)]
"""
def get_batch_size(ser):
if isinstance(ser, BatchedSerializer):
return ser.batchSize
return 1 # not batched
def batch_as(rdd, batchSize):
return rdd._reserialize(BatchedSerializer(PickleSerializer(), batchSize))
my_batch = get_batch_size(self._jrdd_deserializer)
other_batch = get_batch_size(other._jrdd_deserializer)
if my_batch != other_batch or not my_batch:
# use the smallest batchSize for both of them
batchSize = min(my_batch, other_batch)
if batchSize <= 0:
# auto batched or unlimited
batchSize = 100
other = batch_as(other, batchSize)
self = batch_as(self, batchSize)
if self.getNumPartitions() != other.getNumPartitions():
raise ValueError("Can only zip with RDD which has the same number of partitions")
# There will be an Exception in JVM if there are different number
# of items in each partitions.
pairRDD = self._jrdd.zip(other._jrdd)
deserializer = PairDeserializer(self._jrdd_deserializer,
other._jrdd_deserializer)
return RDD(pairRDD, self.ctx, deserializer) | def zip(self, other):
"""
Zips this RDD with another one, returning key-value pairs with the
first element in each RDD second element in each RDD, etc. Assumes
that the two RDDs have the same number of partitions and the same
number of elements in each partition (e.g. one was made through
a map on the other).
>>> x = sc.parallelize(range(0,5))
>>> y = sc.parallelize(range(1000, 1005))
>>> x.zip(y).collect()
[(0, 1000), (1, 1001), (2, 1002), (3, 1003), (4, 1004)]
"""
def get_batch_size(ser):
if isinstance(ser, BatchedSerializer):
return ser.batchSize
return 1 # not batched
def batch_as(rdd, batchSize):
return rdd._reserialize(BatchedSerializer(PickleSerializer(), batchSize))
my_batch = get_batch_size(self._jrdd_deserializer)
other_batch = get_batch_size(other._jrdd_deserializer)
if my_batch != other_batch or not my_batch:
# use the smallest batchSize for both of them
batchSize = min(my_batch, other_batch)
if batchSize <= 0:
# auto batched or unlimited
batchSize = 100
other = batch_as(other, batchSize)
self = batch_as(self, batchSize)
if self.getNumPartitions() != other.getNumPartitions():
raise ValueError("Can only zip with RDD which has the same number of partitions")
# There will be an Exception in JVM if there are different number
# of items in each partitions.
pairRDD = self._jrdd.zip(other._jrdd)
deserializer = PairDeserializer(self._jrdd_deserializer,
other._jrdd_deserializer)
return RDD(pairRDD, self.ctx, deserializer) | [
"Zips",
"this",
"RDD",
"with",
"another",
"one",
"returning",
"key",
"-",
"value",
"pairs",
"with",
"the",
"first",
"element",
"in",
"each",
"RDD",
"second",
"element",
"in",
"each",
"RDD",
"etc",
".",
"Assumes",
"that",
"the",
"two",
"RDDs",
"have",
"the",
"same",
"number",
"of",
"partitions",
"and",
"the",
"same",
"number",
"of",
"elements",
"in",
"each",
"partition",
"(",
"e",
".",
"g",
".",
"one",
"was",
"made",
"through",
"a",
"map",
"on",
"the",
"other",
")",
"."
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L2117-L2157 | [
"def",
"zip",
"(",
"self",
",",
"other",
")",
":",
"def",
"get_batch_size",
"(",
"ser",
")",
":",
"if",
"isinstance",
"(",
"ser",
",",
"BatchedSerializer",
")",
":",
"return",
"ser",
".",
"batchSize",
"return",
"1",
"# not batched",
"def",
"batch_as",
"(",
"rdd",
",",
"batchSize",
")",
":",
"return",
"rdd",
".",
"_reserialize",
"(",
"BatchedSerializer",
"(",
"PickleSerializer",
"(",
")",
",",
"batchSize",
")",
")",
"my_batch",
"=",
"get_batch_size",
"(",
"self",
".",
"_jrdd_deserializer",
")",
"other_batch",
"=",
"get_batch_size",
"(",
"other",
".",
"_jrdd_deserializer",
")",
"if",
"my_batch",
"!=",
"other_batch",
"or",
"not",
"my_batch",
":",
"# use the smallest batchSize for both of them",
"batchSize",
"=",
"min",
"(",
"my_batch",
",",
"other_batch",
")",
"if",
"batchSize",
"<=",
"0",
":",
"# auto batched or unlimited",
"batchSize",
"=",
"100",
"other",
"=",
"batch_as",
"(",
"other",
",",
"batchSize",
")",
"self",
"=",
"batch_as",
"(",
"self",
",",
"batchSize",
")",
"if",
"self",
".",
"getNumPartitions",
"(",
")",
"!=",
"other",
".",
"getNumPartitions",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Can only zip with RDD which has the same number of partitions\"",
")",
"# There will be an Exception in JVM if there are different number",
"# of items in each partitions.",
"pairRDD",
"=",
"self",
".",
"_jrdd",
".",
"zip",
"(",
"other",
".",
"_jrdd",
")",
"deserializer",
"=",
"PairDeserializer",
"(",
"self",
".",
"_jrdd_deserializer",
",",
"other",
".",
"_jrdd_deserializer",
")",
"return",
"RDD",
"(",
"pairRDD",
",",
"self",
".",
"ctx",
",",
"deserializer",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | RDD.zipWithIndex | Zips this RDD with its element indices.
The ordering is first based on the partition index and then the
ordering of items within each partition. So the first item in
the first partition gets index 0, and the last item in the last
partition receives the largest index.
This method needs to trigger a spark job when this RDD contains
more than one partitions.
>>> sc.parallelize(["a", "b", "c", "d"], 3).zipWithIndex().collect()
[('a', 0), ('b', 1), ('c', 2), ('d', 3)] | python/pyspark/rdd.py | def zipWithIndex(self):
"""
Zips this RDD with its element indices.
The ordering is first based on the partition index and then the
ordering of items within each partition. So the first item in
the first partition gets index 0, and the last item in the last
partition receives the largest index.
This method needs to trigger a spark job when this RDD contains
more than one partitions.
>>> sc.parallelize(["a", "b", "c", "d"], 3).zipWithIndex().collect()
[('a', 0), ('b', 1), ('c', 2), ('d', 3)]
"""
starts = [0]
if self.getNumPartitions() > 1:
nums = self.mapPartitions(lambda it: [sum(1 for i in it)]).collect()
for i in range(len(nums) - 1):
starts.append(starts[-1] + nums[i])
def func(k, it):
for i, v in enumerate(it, starts[k]):
yield v, i
return self.mapPartitionsWithIndex(func) | def zipWithIndex(self):
"""
Zips this RDD with its element indices.
The ordering is first based on the partition index and then the
ordering of items within each partition. So the first item in
the first partition gets index 0, and the last item in the last
partition receives the largest index.
This method needs to trigger a spark job when this RDD contains
more than one partitions.
>>> sc.parallelize(["a", "b", "c", "d"], 3).zipWithIndex().collect()
[('a', 0), ('b', 1), ('c', 2), ('d', 3)]
"""
starts = [0]
if self.getNumPartitions() > 1:
nums = self.mapPartitions(lambda it: [sum(1 for i in it)]).collect()
for i in range(len(nums) - 1):
starts.append(starts[-1] + nums[i])
def func(k, it):
for i, v in enumerate(it, starts[k]):
yield v, i
return self.mapPartitionsWithIndex(func) | [
"Zips",
"this",
"RDD",
"with",
"its",
"element",
"indices",
"."
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L2159-L2184 | [
"def",
"zipWithIndex",
"(",
"self",
")",
":",
"starts",
"=",
"[",
"0",
"]",
"if",
"self",
".",
"getNumPartitions",
"(",
")",
">",
"1",
":",
"nums",
"=",
"self",
".",
"mapPartitions",
"(",
"lambda",
"it",
":",
"[",
"sum",
"(",
"1",
"for",
"i",
"in",
"it",
")",
"]",
")",
".",
"collect",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"nums",
")",
"-",
"1",
")",
":",
"starts",
".",
"append",
"(",
"starts",
"[",
"-",
"1",
"]",
"+",
"nums",
"[",
"i",
"]",
")",
"def",
"func",
"(",
"k",
",",
"it",
")",
":",
"for",
"i",
",",
"v",
"in",
"enumerate",
"(",
"it",
",",
"starts",
"[",
"k",
"]",
")",
":",
"yield",
"v",
",",
"i",
"return",
"self",
".",
"mapPartitionsWithIndex",
"(",
"func",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | RDD.zipWithUniqueId | Zips this RDD with generated unique Long ids.
Items in the kth partition will get ids k, n+k, 2*n+k, ..., where
n is the number of partitions. So there may exist gaps, but this
method won't trigger a spark job, which is different from
L{zipWithIndex}
>>> sc.parallelize(["a", "b", "c", "d", "e"], 3).zipWithUniqueId().collect()
[('a', 0), ('b', 1), ('c', 4), ('d', 2), ('e', 5)] | python/pyspark/rdd.py | def zipWithUniqueId(self):
"""
Zips this RDD with generated unique Long ids.
Items in the kth partition will get ids k, n+k, 2*n+k, ..., where
n is the number of partitions. So there may exist gaps, but this
method won't trigger a spark job, which is different from
L{zipWithIndex}
>>> sc.parallelize(["a", "b", "c", "d", "e"], 3).zipWithUniqueId().collect()
[('a', 0), ('b', 1), ('c', 4), ('d', 2), ('e', 5)]
"""
n = self.getNumPartitions()
def func(k, it):
for i, v in enumerate(it):
yield v, i * n + k
return self.mapPartitionsWithIndex(func) | def zipWithUniqueId(self):
"""
Zips this RDD with generated unique Long ids.
Items in the kth partition will get ids k, n+k, 2*n+k, ..., where
n is the number of partitions. So there may exist gaps, but this
method won't trigger a spark job, which is different from
L{zipWithIndex}
>>> sc.parallelize(["a", "b", "c", "d", "e"], 3).zipWithUniqueId().collect()
[('a', 0), ('b', 1), ('c', 4), ('d', 2), ('e', 5)]
"""
n = self.getNumPartitions()
def func(k, it):
for i, v in enumerate(it):
yield v, i * n + k
return self.mapPartitionsWithIndex(func) | [
"Zips",
"this",
"RDD",
"with",
"generated",
"unique",
"Long",
"ids",
"."
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L2186-L2204 | [
"def",
"zipWithUniqueId",
"(",
"self",
")",
":",
"n",
"=",
"self",
".",
"getNumPartitions",
"(",
")",
"def",
"func",
"(",
"k",
",",
"it",
")",
":",
"for",
"i",
",",
"v",
"in",
"enumerate",
"(",
"it",
")",
":",
"yield",
"v",
",",
"i",
"*",
"n",
"+",
"k",
"return",
"self",
".",
"mapPartitionsWithIndex",
"(",
"func",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | RDD.getStorageLevel | Get the RDD's current storage level.
>>> rdd1 = sc.parallelize([1,2])
>>> rdd1.getStorageLevel()
StorageLevel(False, False, False, False, 1)
>>> print(rdd1.getStorageLevel())
Serialized 1x Replicated | python/pyspark/rdd.py | def getStorageLevel(self):
"""
Get the RDD's current storage level.
>>> rdd1 = sc.parallelize([1,2])
>>> rdd1.getStorageLevel()
StorageLevel(False, False, False, False, 1)
>>> print(rdd1.getStorageLevel())
Serialized 1x Replicated
"""
java_storage_level = self._jrdd.getStorageLevel()
storage_level = StorageLevel(java_storage_level.useDisk(),
java_storage_level.useMemory(),
java_storage_level.useOffHeap(),
java_storage_level.deserialized(),
java_storage_level.replication())
return storage_level | def getStorageLevel(self):
"""
Get the RDD's current storage level.
>>> rdd1 = sc.parallelize([1,2])
>>> rdd1.getStorageLevel()
StorageLevel(False, False, False, False, 1)
>>> print(rdd1.getStorageLevel())
Serialized 1x Replicated
"""
java_storage_level = self._jrdd.getStorageLevel()
storage_level = StorageLevel(java_storage_level.useDisk(),
java_storage_level.useMemory(),
java_storage_level.useOffHeap(),
java_storage_level.deserialized(),
java_storage_level.replication())
return storage_level | [
"Get",
"the",
"RDD",
"s",
"current",
"storage",
"level",
"."
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L2234-L2250 | [
"def",
"getStorageLevel",
"(",
"self",
")",
":",
"java_storage_level",
"=",
"self",
".",
"_jrdd",
".",
"getStorageLevel",
"(",
")",
"storage_level",
"=",
"StorageLevel",
"(",
"java_storage_level",
".",
"useDisk",
"(",
")",
",",
"java_storage_level",
".",
"useMemory",
"(",
")",
",",
"java_storage_level",
".",
"useOffHeap",
"(",
")",
",",
"java_storage_level",
".",
"deserialized",
"(",
")",
",",
"java_storage_level",
".",
"replication",
"(",
")",
")",
"return",
"storage_level"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | RDD._defaultReducePartitions | Returns the default number of partitions to use during reduce tasks (e.g., groupBy).
If spark.default.parallelism is set, then we'll use the value from SparkContext
defaultParallelism, otherwise we'll use the number of partitions in this RDD.
This mirrors the behavior of the Scala Partitioner#defaultPartitioner, intended to reduce
the likelihood of OOMs. Once PySpark adopts Partitioner-based APIs, this behavior will
be inherent. | python/pyspark/rdd.py | def _defaultReducePartitions(self):
"""
Returns the default number of partitions to use during reduce tasks (e.g., groupBy).
If spark.default.parallelism is set, then we'll use the value from SparkContext
defaultParallelism, otherwise we'll use the number of partitions in this RDD.
This mirrors the behavior of the Scala Partitioner#defaultPartitioner, intended to reduce
the likelihood of OOMs. Once PySpark adopts Partitioner-based APIs, this behavior will
be inherent.
"""
if self.ctx._conf.contains("spark.default.parallelism"):
return self.ctx.defaultParallelism
else:
return self.getNumPartitions() | def _defaultReducePartitions(self):
"""
Returns the default number of partitions to use during reduce tasks (e.g., groupBy).
If spark.default.parallelism is set, then we'll use the value from SparkContext
defaultParallelism, otherwise we'll use the number of partitions in this RDD.
This mirrors the behavior of the Scala Partitioner#defaultPartitioner, intended to reduce
the likelihood of OOMs. Once PySpark adopts Partitioner-based APIs, this behavior will
be inherent.
"""
if self.ctx._conf.contains("spark.default.parallelism"):
return self.ctx.defaultParallelism
else:
return self.getNumPartitions() | [
"Returns",
"the",
"default",
"number",
"of",
"partitions",
"to",
"use",
"during",
"reduce",
"tasks",
"(",
"e",
".",
"g",
".",
"groupBy",
")",
".",
"If",
"spark",
".",
"default",
".",
"parallelism",
"is",
"set",
"then",
"we",
"ll",
"use",
"the",
"value",
"from",
"SparkContext",
"defaultParallelism",
"otherwise",
"we",
"ll",
"use",
"the",
"number",
"of",
"partitions",
"in",
"this",
"RDD",
"."
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L2252-L2265 | [
"def",
"_defaultReducePartitions",
"(",
"self",
")",
":",
"if",
"self",
".",
"ctx",
".",
"_conf",
".",
"contains",
"(",
"\"spark.default.parallelism\"",
")",
":",
"return",
"self",
".",
"ctx",
".",
"defaultParallelism",
"else",
":",
"return",
"self",
".",
"getNumPartitions",
"(",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | RDD.lookup | Return the list of values in the RDD for key `key`. This operation
is done efficiently if the RDD has a known partitioner by only
searching the partition that the key maps to.
>>> l = range(1000)
>>> rdd = sc.parallelize(zip(l, l), 10)
>>> rdd.lookup(42) # slow
[42]
>>> sorted = rdd.sortByKey()
>>> sorted.lookup(42) # fast
[42]
>>> sorted.lookup(1024)
[]
>>> rdd2 = sc.parallelize([(('a', 'b'), 'c')]).groupByKey()
>>> list(rdd2.lookup(('a', 'b'))[0])
['c'] | python/pyspark/rdd.py | def lookup(self, key):
"""
Return the list of values in the RDD for key `key`. This operation
is done efficiently if the RDD has a known partitioner by only
searching the partition that the key maps to.
>>> l = range(1000)
>>> rdd = sc.parallelize(zip(l, l), 10)
>>> rdd.lookup(42) # slow
[42]
>>> sorted = rdd.sortByKey()
>>> sorted.lookup(42) # fast
[42]
>>> sorted.lookup(1024)
[]
>>> rdd2 = sc.parallelize([(('a', 'b'), 'c')]).groupByKey()
>>> list(rdd2.lookup(('a', 'b'))[0])
['c']
"""
values = self.filter(lambda kv: kv[0] == key).values()
if self.partitioner is not None:
return self.ctx.runJob(values, lambda x: x, [self.partitioner(key)])
return values.collect() | def lookup(self, key):
"""
Return the list of values in the RDD for key `key`. This operation
is done efficiently if the RDD has a known partitioner by only
searching the partition that the key maps to.
>>> l = range(1000)
>>> rdd = sc.parallelize(zip(l, l), 10)
>>> rdd.lookup(42) # slow
[42]
>>> sorted = rdd.sortByKey()
>>> sorted.lookup(42) # fast
[42]
>>> sorted.lookup(1024)
[]
>>> rdd2 = sc.parallelize([(('a', 'b'), 'c')]).groupByKey()
>>> list(rdd2.lookup(('a', 'b'))[0])
['c']
"""
values = self.filter(lambda kv: kv[0] == key).values()
if self.partitioner is not None:
return self.ctx.runJob(values, lambda x: x, [self.partitioner(key)])
return values.collect() | [
"Return",
"the",
"list",
"of",
"values",
"in",
"the",
"RDD",
"for",
"key",
"key",
".",
"This",
"operation",
"is",
"done",
"efficiently",
"if",
"the",
"RDD",
"has",
"a",
"known",
"partitioner",
"by",
"only",
"searching",
"the",
"partition",
"that",
"the",
"key",
"maps",
"to",
"."
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L2267-L2291 | [
"def",
"lookup",
"(",
"self",
",",
"key",
")",
":",
"values",
"=",
"self",
".",
"filter",
"(",
"lambda",
"kv",
":",
"kv",
"[",
"0",
"]",
"==",
"key",
")",
".",
"values",
"(",
")",
"if",
"self",
".",
"partitioner",
"is",
"not",
"None",
":",
"return",
"self",
".",
"ctx",
".",
"runJob",
"(",
"values",
",",
"lambda",
"x",
":",
"x",
",",
"[",
"self",
".",
"partitioner",
"(",
"key",
")",
"]",
")",
"return",
"values",
".",
"collect",
"(",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | RDD._to_java_object_rdd | Return a JavaRDD of Object by unpickling
It will convert each Python object into Java object by Pyrolite, whenever the
RDD is serialized in batch or not. | python/pyspark/rdd.py | def _to_java_object_rdd(self):
""" Return a JavaRDD of Object by unpickling
It will convert each Python object into Java object by Pyrolite, whenever the
RDD is serialized in batch or not.
"""
rdd = self._pickled()
return self.ctx._jvm.SerDeUtil.pythonToJava(rdd._jrdd, True) | def _to_java_object_rdd(self):
""" Return a JavaRDD of Object by unpickling
It will convert each Python object into Java object by Pyrolite, whenever the
RDD is serialized in batch or not.
"""
rdd = self._pickled()
return self.ctx._jvm.SerDeUtil.pythonToJava(rdd._jrdd, True) | [
"Return",
"a",
"JavaRDD",
"of",
"Object",
"by",
"unpickling"
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L2293-L2300 | [
"def",
"_to_java_object_rdd",
"(",
"self",
")",
":",
"rdd",
"=",
"self",
".",
"_pickled",
"(",
")",
"return",
"self",
".",
"ctx",
".",
"_jvm",
".",
"SerDeUtil",
".",
"pythonToJava",
"(",
"rdd",
".",
"_jrdd",
",",
"True",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | RDD.countApprox | .. note:: Experimental
Approximate version of count() that returns a potentially incomplete
result within a timeout, even if not all tasks have finished.
>>> rdd = sc.parallelize(range(1000), 10)
>>> rdd.countApprox(1000, 1.0)
1000 | python/pyspark/rdd.py | def countApprox(self, timeout, confidence=0.95):
"""
.. note:: Experimental
Approximate version of count() that returns a potentially incomplete
result within a timeout, even if not all tasks have finished.
>>> rdd = sc.parallelize(range(1000), 10)
>>> rdd.countApprox(1000, 1.0)
1000
"""
drdd = self.mapPartitions(lambda it: [float(sum(1 for i in it))])
return int(drdd.sumApprox(timeout, confidence)) | def countApprox(self, timeout, confidence=0.95):
"""
.. note:: Experimental
Approximate version of count() that returns a potentially incomplete
result within a timeout, even if not all tasks have finished.
>>> rdd = sc.parallelize(range(1000), 10)
>>> rdd.countApprox(1000, 1.0)
1000
"""
drdd = self.mapPartitions(lambda it: [float(sum(1 for i in it))])
return int(drdd.sumApprox(timeout, confidence)) | [
"..",
"note",
"::",
"Experimental"
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L2302-L2314 | [
"def",
"countApprox",
"(",
"self",
",",
"timeout",
",",
"confidence",
"=",
"0.95",
")",
":",
"drdd",
"=",
"self",
".",
"mapPartitions",
"(",
"lambda",
"it",
":",
"[",
"float",
"(",
"sum",
"(",
"1",
"for",
"i",
"in",
"it",
")",
")",
"]",
")",
"return",
"int",
"(",
"drdd",
".",
"sumApprox",
"(",
"timeout",
",",
"confidence",
")",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | RDD.sumApprox | .. note:: Experimental
Approximate operation to return the sum within a timeout
or meet the confidence.
>>> rdd = sc.parallelize(range(1000), 10)
>>> r = sum(range(1000))
>>> abs(rdd.sumApprox(1000) - r) / r < 0.05
True | python/pyspark/rdd.py | def sumApprox(self, timeout, confidence=0.95):
"""
.. note:: Experimental
Approximate operation to return the sum within a timeout
or meet the confidence.
>>> rdd = sc.parallelize(range(1000), 10)
>>> r = sum(range(1000))
>>> abs(rdd.sumApprox(1000) - r) / r < 0.05
True
"""
jrdd = self.mapPartitions(lambda it: [float(sum(it))])._to_java_object_rdd()
jdrdd = self.ctx._jvm.JavaDoubleRDD.fromRDD(jrdd.rdd())
r = jdrdd.sumApprox(timeout, confidence).getFinalValue()
return BoundedFloat(r.mean(), r.confidence(), r.low(), r.high()) | def sumApprox(self, timeout, confidence=0.95):
"""
.. note:: Experimental
Approximate operation to return the sum within a timeout
or meet the confidence.
>>> rdd = sc.parallelize(range(1000), 10)
>>> r = sum(range(1000))
>>> abs(rdd.sumApprox(1000) - r) / r < 0.05
True
"""
jrdd = self.mapPartitions(lambda it: [float(sum(it))])._to_java_object_rdd()
jdrdd = self.ctx._jvm.JavaDoubleRDD.fromRDD(jrdd.rdd())
r = jdrdd.sumApprox(timeout, confidence).getFinalValue()
return BoundedFloat(r.mean(), r.confidence(), r.low(), r.high()) | [
"..",
"note",
"::",
"Experimental"
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L2316-L2331 | [
"def",
"sumApprox",
"(",
"self",
",",
"timeout",
",",
"confidence",
"=",
"0.95",
")",
":",
"jrdd",
"=",
"self",
".",
"mapPartitions",
"(",
"lambda",
"it",
":",
"[",
"float",
"(",
"sum",
"(",
"it",
")",
")",
"]",
")",
".",
"_to_java_object_rdd",
"(",
")",
"jdrdd",
"=",
"self",
".",
"ctx",
".",
"_jvm",
".",
"JavaDoubleRDD",
".",
"fromRDD",
"(",
"jrdd",
".",
"rdd",
"(",
")",
")",
"r",
"=",
"jdrdd",
".",
"sumApprox",
"(",
"timeout",
",",
"confidence",
")",
".",
"getFinalValue",
"(",
")",
"return",
"BoundedFloat",
"(",
"r",
".",
"mean",
"(",
")",
",",
"r",
".",
"confidence",
"(",
")",
",",
"r",
".",
"low",
"(",
")",
",",
"r",
".",
"high",
"(",
")",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | RDD.meanApprox | .. note:: Experimental
Approximate operation to return the mean within a timeout
or meet the confidence.
>>> rdd = sc.parallelize(range(1000), 10)
>>> r = sum(range(1000)) / 1000.0
>>> abs(rdd.meanApprox(1000) - r) / r < 0.05
True | python/pyspark/rdd.py | def meanApprox(self, timeout, confidence=0.95):
"""
.. note:: Experimental
Approximate operation to return the mean within a timeout
or meet the confidence.
>>> rdd = sc.parallelize(range(1000), 10)
>>> r = sum(range(1000)) / 1000.0
>>> abs(rdd.meanApprox(1000) - r) / r < 0.05
True
"""
jrdd = self.map(float)._to_java_object_rdd()
jdrdd = self.ctx._jvm.JavaDoubleRDD.fromRDD(jrdd.rdd())
r = jdrdd.meanApprox(timeout, confidence).getFinalValue()
return BoundedFloat(r.mean(), r.confidence(), r.low(), r.high()) | def meanApprox(self, timeout, confidence=0.95):
"""
.. note:: Experimental
Approximate operation to return the mean within a timeout
or meet the confidence.
>>> rdd = sc.parallelize(range(1000), 10)
>>> r = sum(range(1000)) / 1000.0
>>> abs(rdd.meanApprox(1000) - r) / r < 0.05
True
"""
jrdd = self.map(float)._to_java_object_rdd()
jdrdd = self.ctx._jvm.JavaDoubleRDD.fromRDD(jrdd.rdd())
r = jdrdd.meanApprox(timeout, confidence).getFinalValue()
return BoundedFloat(r.mean(), r.confidence(), r.low(), r.high()) | [
"..",
"note",
"::",
"Experimental"
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L2333-L2348 | [
"def",
"meanApprox",
"(",
"self",
",",
"timeout",
",",
"confidence",
"=",
"0.95",
")",
":",
"jrdd",
"=",
"self",
".",
"map",
"(",
"float",
")",
".",
"_to_java_object_rdd",
"(",
")",
"jdrdd",
"=",
"self",
".",
"ctx",
".",
"_jvm",
".",
"JavaDoubleRDD",
".",
"fromRDD",
"(",
"jrdd",
".",
"rdd",
"(",
")",
")",
"r",
"=",
"jdrdd",
".",
"meanApprox",
"(",
"timeout",
",",
"confidence",
")",
".",
"getFinalValue",
"(",
")",
"return",
"BoundedFloat",
"(",
"r",
".",
"mean",
"(",
")",
",",
"r",
".",
"confidence",
"(",
")",
",",
"r",
".",
"low",
"(",
")",
",",
"r",
".",
"high",
"(",
")",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | RDD.countApproxDistinct | .. note:: Experimental
Return approximate number of distinct elements in the RDD.
The algorithm used is based on streamlib's implementation of
`"HyperLogLog in Practice: Algorithmic Engineering of a State
of The Art Cardinality Estimation Algorithm", available here
<https://doi.org/10.1145/2452376.2452456>`_.
:param relativeSD: Relative accuracy. Smaller values create
counters that require more space.
It must be greater than 0.000017.
>>> n = sc.parallelize(range(1000)).map(str).countApproxDistinct()
>>> 900 < n < 1100
True
>>> n = sc.parallelize([i % 20 for i in range(1000)]).countApproxDistinct()
>>> 16 < n < 24
True | python/pyspark/rdd.py | def countApproxDistinct(self, relativeSD=0.05):
"""
.. note:: Experimental
Return approximate number of distinct elements in the RDD.
The algorithm used is based on streamlib's implementation of
`"HyperLogLog in Practice: Algorithmic Engineering of a State
of The Art Cardinality Estimation Algorithm", available here
<https://doi.org/10.1145/2452376.2452456>`_.
:param relativeSD: Relative accuracy. Smaller values create
counters that require more space.
It must be greater than 0.000017.
>>> n = sc.parallelize(range(1000)).map(str).countApproxDistinct()
>>> 900 < n < 1100
True
>>> n = sc.parallelize([i % 20 for i in range(1000)]).countApproxDistinct()
>>> 16 < n < 24
True
"""
if relativeSD < 0.000017:
raise ValueError("relativeSD should be greater than 0.000017")
# the hash space in Java is 2^32
hashRDD = self.map(lambda x: portable_hash(x) & 0xFFFFFFFF)
return hashRDD._to_java_object_rdd().countApproxDistinct(relativeSD) | def countApproxDistinct(self, relativeSD=0.05):
"""
.. note:: Experimental
Return approximate number of distinct elements in the RDD.
The algorithm used is based on streamlib's implementation of
`"HyperLogLog in Practice: Algorithmic Engineering of a State
of The Art Cardinality Estimation Algorithm", available here
<https://doi.org/10.1145/2452376.2452456>`_.
:param relativeSD: Relative accuracy. Smaller values create
counters that require more space.
It must be greater than 0.000017.
>>> n = sc.parallelize(range(1000)).map(str).countApproxDistinct()
>>> 900 < n < 1100
True
>>> n = sc.parallelize([i % 20 for i in range(1000)]).countApproxDistinct()
>>> 16 < n < 24
True
"""
if relativeSD < 0.000017:
raise ValueError("relativeSD should be greater than 0.000017")
# the hash space in Java is 2^32
hashRDD = self.map(lambda x: portable_hash(x) & 0xFFFFFFFF)
return hashRDD._to_java_object_rdd().countApproxDistinct(relativeSD) | [
"..",
"note",
"::",
"Experimental"
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L2350-L2376 | [
"def",
"countApproxDistinct",
"(",
"self",
",",
"relativeSD",
"=",
"0.05",
")",
":",
"if",
"relativeSD",
"<",
"0.000017",
":",
"raise",
"ValueError",
"(",
"\"relativeSD should be greater than 0.000017\"",
")",
"# the hash space in Java is 2^32",
"hashRDD",
"=",
"self",
".",
"map",
"(",
"lambda",
"x",
":",
"portable_hash",
"(",
"x",
")",
"&",
"0xFFFFFFFF",
")",
"return",
"hashRDD",
".",
"_to_java_object_rdd",
"(",
")",
".",
"countApproxDistinct",
"(",
"relativeSD",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | RDD.toLocalIterator | Return an iterator that contains all of the elements in this RDD.
The iterator will consume as much memory as the largest partition in this RDD.
>>> rdd = sc.parallelize(range(10))
>>> [x for x in rdd.toLocalIterator()]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] | python/pyspark/rdd.py | def toLocalIterator(self):
"""
Return an iterator that contains all of the elements in this RDD.
The iterator will consume as much memory as the largest partition in this RDD.
>>> rdd = sc.parallelize(range(10))
>>> [x for x in rdd.toLocalIterator()]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
"""
with SCCallSiteSync(self.context) as css:
sock_info = self.ctx._jvm.PythonRDD.toLocalIteratorAndServe(self._jrdd.rdd())
return _load_from_socket(sock_info, self._jrdd_deserializer) | def toLocalIterator(self):
"""
Return an iterator that contains all of the elements in this RDD.
The iterator will consume as much memory as the largest partition in this RDD.
>>> rdd = sc.parallelize(range(10))
>>> [x for x in rdd.toLocalIterator()]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
"""
with SCCallSiteSync(self.context) as css:
sock_info = self.ctx._jvm.PythonRDD.toLocalIteratorAndServe(self._jrdd.rdd())
return _load_from_socket(sock_info, self._jrdd_deserializer) | [
"Return",
"an",
"iterator",
"that",
"contains",
"all",
"of",
"the",
"elements",
"in",
"this",
"RDD",
".",
"The",
"iterator",
"will",
"consume",
"as",
"much",
"memory",
"as",
"the",
"largest",
"partition",
"in",
"this",
"RDD",
"."
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L2378-L2389 | [
"def",
"toLocalIterator",
"(",
"self",
")",
":",
"with",
"SCCallSiteSync",
"(",
"self",
".",
"context",
")",
"as",
"css",
":",
"sock_info",
"=",
"self",
".",
"ctx",
".",
"_jvm",
".",
"PythonRDD",
".",
"toLocalIteratorAndServe",
"(",
"self",
".",
"_jrdd",
".",
"rdd",
"(",
")",
")",
"return",
"_load_from_socket",
"(",
"sock_info",
",",
"self",
".",
"_jrdd_deserializer",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | RDDBarrier.mapPartitions | .. note:: Experimental
Returns a new RDD by applying a function to each partition of the wrapped RDD,
where tasks are launched together in a barrier stage.
The interface is the same as :func:`RDD.mapPartitions`.
Please see the API doc there.
.. versionadded:: 2.4.0 | python/pyspark/rdd.py | def mapPartitions(self, f, preservesPartitioning=False):
"""
.. note:: Experimental
Returns a new RDD by applying a function to each partition of the wrapped RDD,
where tasks are launched together in a barrier stage.
The interface is the same as :func:`RDD.mapPartitions`.
Please see the API doc there.
.. versionadded:: 2.4.0
"""
def func(s, iterator):
return f(iterator)
return PipelinedRDD(self.rdd, func, preservesPartitioning, isFromBarrier=True) | def mapPartitions(self, f, preservesPartitioning=False):
"""
.. note:: Experimental
Returns a new RDD by applying a function to each partition of the wrapped RDD,
where tasks are launched together in a barrier stage.
The interface is the same as :func:`RDD.mapPartitions`.
Please see the API doc there.
.. versionadded:: 2.4.0
"""
def func(s, iterator):
return f(iterator)
return PipelinedRDD(self.rdd, func, preservesPartitioning, isFromBarrier=True) | [
"..",
"note",
"::",
"Experimental"
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L2455-L2468 | [
"def",
"mapPartitions",
"(",
"self",
",",
"f",
",",
"preservesPartitioning",
"=",
"False",
")",
":",
"def",
"func",
"(",
"s",
",",
"iterator",
")",
":",
"return",
"f",
"(",
"iterator",
")",
"return",
"PipelinedRDD",
"(",
"self",
".",
"rdd",
",",
"func",
",",
"preservesPartitioning",
",",
"isFromBarrier",
"=",
"True",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | _to_seq | Convert a list of Column (or names) into a JVM Seq of Column.
An optional `converter` could be used to convert items in `cols`
into JVM Column objects. | python/pyspark/sql/column.py | def _to_seq(sc, cols, converter=None):
"""
Convert a list of Column (or names) into a JVM Seq of Column.
An optional `converter` could be used to convert items in `cols`
into JVM Column objects.
"""
if converter:
cols = [converter(c) for c in cols]
return sc._jvm.PythonUtils.toSeq(cols) | def _to_seq(sc, cols, converter=None):
"""
Convert a list of Column (or names) into a JVM Seq of Column.
An optional `converter` could be used to convert items in `cols`
into JVM Column objects.
"""
if converter:
cols = [converter(c) for c in cols]
return sc._jvm.PythonUtils.toSeq(cols) | [
"Convert",
"a",
"list",
"of",
"Column",
"(",
"or",
"names",
")",
"into",
"a",
"JVM",
"Seq",
"of",
"Column",
"."
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/sql/column.py#L57-L66 | [
"def",
"_to_seq",
"(",
"sc",
",",
"cols",
",",
"converter",
"=",
"None",
")",
":",
"if",
"converter",
":",
"cols",
"=",
"[",
"converter",
"(",
"c",
")",
"for",
"c",
"in",
"cols",
"]",
"return",
"sc",
".",
"_jvm",
".",
"PythonUtils",
".",
"toSeq",
"(",
"cols",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | _to_list | Convert a list of Column (or names) into a JVM (Scala) List of Column.
An optional `converter` could be used to convert items in `cols`
into JVM Column objects. | python/pyspark/sql/column.py | def _to_list(sc, cols, converter=None):
"""
Convert a list of Column (or names) into a JVM (Scala) List of Column.
An optional `converter` could be used to convert items in `cols`
into JVM Column objects.
"""
if converter:
cols = [converter(c) for c in cols]
return sc._jvm.PythonUtils.toList(cols) | def _to_list(sc, cols, converter=None):
"""
Convert a list of Column (or names) into a JVM (Scala) List of Column.
An optional `converter` could be used to convert items in `cols`
into JVM Column objects.
"""
if converter:
cols = [converter(c) for c in cols]
return sc._jvm.PythonUtils.toList(cols) | [
"Convert",
"a",
"list",
"of",
"Column",
"(",
"or",
"names",
")",
"into",
"a",
"JVM",
"(",
"Scala",
")",
"List",
"of",
"Column",
"."
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/sql/column.py#L69-L78 | [
"def",
"_to_list",
"(",
"sc",
",",
"cols",
",",
"converter",
"=",
"None",
")",
":",
"if",
"converter",
":",
"cols",
"=",
"[",
"converter",
"(",
"c",
")",
"for",
"c",
"in",
"cols",
"]",
"return",
"sc",
".",
"_jvm",
".",
"PythonUtils",
".",
"toList",
"(",
"cols",
")"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | _unary_op | Create a method for given unary operator | python/pyspark/sql/column.py | def _unary_op(name, doc="unary operator"):
""" Create a method for given unary operator """
def _(self):
jc = getattr(self._jc, name)()
return Column(jc)
_.__doc__ = doc
return _ | def _unary_op(name, doc="unary operator"):
""" Create a method for given unary operator """
def _(self):
jc = getattr(self._jc, name)()
return Column(jc)
_.__doc__ = doc
return _ | [
"Create",
"a",
"method",
"for",
"given",
"unary",
"operator"
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/sql/column.py#L81-L87 | [
"def",
"_unary_op",
"(",
"name",
",",
"doc",
"=",
"\"unary operator\"",
")",
":",
"def",
"_",
"(",
"self",
")",
":",
"jc",
"=",
"getattr",
"(",
"self",
".",
"_jc",
",",
"name",
")",
"(",
")",
"return",
"Column",
"(",
"jc",
")",
"_",
".",
"__doc__",
"=",
"doc",
"return",
"_"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
train | _bin_op | Create a method for given binary operator | python/pyspark/sql/column.py | def _bin_op(name, doc="binary operator"):
""" Create a method for given binary operator
"""
def _(self, other):
jc = other._jc if isinstance(other, Column) else other
njc = getattr(self._jc, name)(jc)
return Column(njc)
_.__doc__ = doc
return _ | def _bin_op(name, doc="binary operator"):
""" Create a method for given binary operator
"""
def _(self, other):
jc = other._jc if isinstance(other, Column) else other
njc = getattr(self._jc, name)(jc)
return Column(njc)
_.__doc__ = doc
return _ | [
"Create",
"a",
"method",
"for",
"given",
"binary",
"operator"
] | apache/spark | python | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/sql/column.py#L110-L118 | [
"def",
"_bin_op",
"(",
"name",
",",
"doc",
"=",
"\"binary operator\"",
")",
":",
"def",
"_",
"(",
"self",
",",
"other",
")",
":",
"jc",
"=",
"other",
".",
"_jc",
"if",
"isinstance",
"(",
"other",
",",
"Column",
")",
"else",
"other",
"njc",
"=",
"getattr",
"(",
"self",
".",
"_jc",
",",
"name",
")",
"(",
"jc",
")",
"return",
"Column",
"(",
"njc",
")",
"_",
".",
"__doc__",
"=",
"doc",
"return",
"_"
] | 618d6bff71073c8c93501ab7392c3cc579730f0b |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.