Code
stringlengths 103
85.9k
| Summary
sequencelengths 0
94
|
---|---|
Please provide a description of the function:def array_repeat(col, count):
sc = SparkContext._active_spark_context
return Column(sc._jvm.functions.array_repeat(_to_java_column(col), count)) | [
"\n Collection function: creates an array containing a column repeated count times.\n\n >>> df = spark.createDataFrame([('ab',)], ['data'])\n >>> df.select(array_repeat(df.data, 3).alias('r')).collect()\n [Row(r=[u'ab', u'ab', u'ab'])]\n "
] |
Please provide a description of the function:def map_concat(*cols):
sc = SparkContext._active_spark_context
if len(cols) == 1 and isinstance(cols[0], (list, set)):
cols = cols[0]
jc = sc._jvm.functions.map_concat(_to_seq(sc, cols, _to_java_column))
return Column(jc) | [
"Returns the union of all the given maps.\n\n :param cols: list of column names (string) or list of :class:`Column` expressions\n\n >>> from pyspark.sql.functions import map_concat\n >>> df = spark.sql(\"SELECT map(1, 'a', 2, 'b') as map1, map(3, 'c', 1, 'd') as map2\")\n >>> df.select(map_concat(\"map1\", \"map2\").alias(\"map3\")).show(truncate=False)\n +------------------------+\n |map3 |\n +------------------------+\n |[1 -> d, 2 -> b, 3 -> c]|\n +------------------------+\n "
] |
Please provide a description of the function:def sequence(start, stop, step=None):
sc = SparkContext._active_spark_context
if step is None:
return Column(sc._jvm.functions.sequence(_to_java_column(start), _to_java_column(stop)))
else:
return Column(sc._jvm.functions.sequence(
_to_java_column(start), _to_java_column(stop), _to_java_column(step))) | [
"\n Generate a sequence of integers from `start` to `stop`, incrementing by `step`.\n If `step` is not set, incrementing by 1 if `start` is less than or equal to `stop`,\n otherwise -1.\n\n >>> df1 = spark.createDataFrame([(-2, 2)], ('C1', 'C2'))\n >>> df1.select(sequence('C1', 'C2').alias('r')).collect()\n [Row(r=[-2, -1, 0, 1, 2])]\n >>> df2 = spark.createDataFrame([(4, -4, -2)], ('C1', 'C2', 'C3'))\n >>> df2.select(sequence('C1', 'C2', 'C3').alias('r')).collect()\n [Row(r=[4, 2, 0, -2, -4])]\n "
] |
Please provide a description of the function:def from_csv(col, schema, options={}):
sc = SparkContext._active_spark_context
if isinstance(schema, basestring):
schema = _create_column_from_literal(schema)
elif isinstance(schema, Column):
schema = _to_java_column(schema)
else:
raise TypeError("schema argument should be a column or string")
jc = sc._jvm.functions.from_csv(_to_java_column(col), schema, options)
return Column(jc) | [
"\n Parses a column containing a CSV string to a row with the specified schema.\n Returns `null`, in the case of an unparseable string.\n\n :param col: string column in CSV format\n :param schema: a string with schema in DDL format to use when parsing the CSV column.\n :param options: options to control parsing. accepts the same options as the CSV datasource\n\n >>> data = [(\"1,2,3\",)]\n >>> df = spark.createDataFrame(data, (\"value\",))\n >>> df.select(from_csv(df.value, \"a INT, b INT, c INT\").alias(\"csv\")).collect()\n [Row(csv=Row(a=1, b=2, c=3))]\n >>> value = data[0][0]\n >>> df.select(from_csv(df.value, schema_of_csv(value)).alias(\"csv\")).collect()\n [Row(csv=Row(_c0=1, _c1=2, _c2=3))]\n "
] |
Please provide a description of the function:def udf(f=None, returnType=StringType()):
# The following table shows most of Python data and SQL type conversions in normal UDFs that
# are not yet visible to the user. Some of behaviors are buggy and might be changed in the near
# future. The table might have to be eventually documented externally.
# Please see SPARK-25666's PR to see the codes in order to generate the table below.
#
# +-----------------------------+--------------+----------+------+-------+---------------+---------------+--------------------+-----------------------------+----------+----------------------+---------+--------------------+-----------------+------------+--------------+------------------+----------------------+ # noqa
# |SQL Type \ Python Value(Type)|None(NoneType)|True(bool)|1(int)|1(long)| a(str)| a(unicode)| 1970-01-01(date)|1970-01-01 00:00:00(datetime)|1.0(float)|array('i', [1])(array)|[1](list)| (1,)(tuple)| ABC(bytearray)| 1(Decimal)|{'a': 1}(dict)|Row(kwargs=1)(Row)|Row(namedtuple=1)(Row)| # noqa
# +-----------------------------+--------------+----------+------+-------+---------------+---------------+--------------------+-----------------------------+----------+----------------------+---------+--------------------+-----------------+------------+--------------+------------------+----------------------+ # noqa
# | boolean| None| True| None| None| None| None| None| None| None| None| None| None| None| None| None| X| X| # noqa
# | tinyint| None| None| 1| 1| None| None| None| None| None| None| None| None| None| None| None| X| X| # noqa
# | smallint| None| None| 1| 1| None| None| None| None| None| None| None| None| None| None| None| X| X| # noqa
# | int| None| None| 1| 1| None| None| None| None| None| None| None| None| None| None| None| X| X| # noqa
# | bigint| None| None| 1| 1| None| None| None| None| None| None| None| None| None| None| None| X| X| # noqa
# | string| None| u'true'| u'1'| u'1'| u'a'| u'a'|u'java.util.Grego...| u'java.util.Grego...| u'1.0'| u'[I@24a83055'| u'[1]'|u'[Ljava.lang.Obj...| u'[B@49093632'| u'1'| u'{a=1}'| X| X| # noqa
# | date| None| X| X| X| X| X|datetime.date(197...| datetime.date(197...| X| X| X| X| X| X| X| X| X| # noqa
# | timestamp| None| X| X| X| X| X| X| datetime.datetime...| X| X| X| X| X| X| X| X| X| # noqa
# | float| None| None| None| None| None| None| None| None| 1.0| None| None| None| None| None| None| X| X| # noqa
# | double| None| None| None| None| None| None| None| None| 1.0| None| None| None| None| None| None| X| X| # noqa
# | array<int>| None| None| None| None| None| None| None| None| None| [1]| [1]| [1]| [65, 66, 67]| None| None| X| X| # noqa
# | binary| None| None| None| None|bytearray(b'a')|bytearray(b'a')| None| None| None| None| None| None|bytearray(b'ABC')| None| None| X| X| # noqa
# | decimal(10,0)| None| None| None| None| None| None| None| None| None| None| None| None| None|Decimal('1')| None| X| X| # noqa
# | map<string,int>| None| None| None| None| None| None| None| None| None| None| None| None| None| None| {u'a': 1}| X| X| # noqa
# | struct<_1:int>| None| X| X| X| X| X| X| X| X| X|Row(_1=1)| Row(_1=1)| X| X| Row(_1=None)| Row(_1=1)| Row(_1=1)| # noqa
# +-----------------------------+--------------+----------+------+-------+---------------+---------------+--------------------+-----------------------------+----------+----------------------+---------+--------------------+-----------------+------------+--------------+------------------+----------------------+ # noqa
#
# Note: DDL formatted string is used for 'SQL Type' for simplicity. This string can be
# used in `returnType`.
# Note: The values inside of the table are generated by `repr`.
# Note: Python 2 is used to generate this table since it is used to check the backward
# compatibility often in practice.
# Note: 'X' means it throws an exception during the conversion.
# decorator @udf, @udf(), @udf(dataType())
if f is None or isinstance(f, (str, DataType)):
# If DataType has been passed as a positional argument
# for decorator use it as a returnType
return_type = f or returnType
return functools.partial(_create_udf, returnType=return_type,
evalType=PythonEvalType.SQL_BATCHED_UDF)
else:
return _create_udf(f=f, returnType=returnType,
evalType=PythonEvalType.SQL_BATCHED_UDF) | [
"Creates a user defined function (UDF).\n\n .. note:: The user-defined functions are considered deterministic by default. Due to\n optimization, duplicate invocations may be eliminated or the function may even be invoked\n more times than it is present in the query. If your function is not deterministic, call\n `asNondeterministic` on the user defined function. E.g.:\n\n >>> from pyspark.sql.types import IntegerType\n >>> import random\n >>> random_udf = udf(lambda: int(random.random() * 100), IntegerType()).asNondeterministic()\n\n .. note:: The user-defined functions do not support conditional expressions or short circuiting\n in boolean expressions and it ends up with being executed all internally. If the functions\n can fail on special rows, the workaround is to incorporate the condition into the functions.\n\n .. note:: The user-defined functions do not take keyword arguments on the calling side.\n\n :param f: python function if used as a standalone function\n :param returnType: the return type of the user-defined function. The value can be either a\n :class:`pyspark.sql.types.DataType` object or a DDL-formatted type string.\n\n >>> from pyspark.sql.types import IntegerType\n >>> slen = udf(lambda s: len(s), IntegerType())\n >>> @udf\n ... def to_upper(s):\n ... if s is not None:\n ... return s.upper()\n ...\n >>> @udf(returnType=IntegerType())\n ... def add_one(x):\n ... if x is not None:\n ... return x + 1\n ...\n >>> df = spark.createDataFrame([(1, \"John Doe\", 21)], (\"id\", \"name\", \"age\"))\n >>> df.select(slen(\"name\").alias(\"slen(name)\"), to_upper(\"name\"), add_one(\"age\")).show()\n +----------+--------------+------------+\n |slen(name)|to_upper(name)|add_one(age)|\n +----------+--------------+------------+\n | 8| JOHN DOE| 22|\n +----------+--------------+------------+\n "
] |
Please provide a description of the function:def pandas_udf(f=None, returnType=None, functionType=None):
# The following table shows most of Pandas data and SQL type conversions in Pandas UDFs that
# are not yet visible to the user. Some of behaviors are buggy and might be changed in the near
# future. The table might have to be eventually documented externally.
# Please see SPARK-25798's PR to see the codes in order to generate the table below.
#
# +-----------------------------+----------------------+----------+-------+--------+--------------------+--------------------+--------+---------+---------+---------+------------+------------+------------+-----------------------------------+-----------------------------------------------------+-----------------+--------------------+-----------------------------+-------------+-----------------+------------------+-----------+--------------------------------+ # noqa
# |SQL Type \ Pandas Value(Type)|None(object(NoneType))|True(bool)|1(int8)|1(int16)| 1(int32)| 1(int64)|1(uint8)|1(uint16)|1(uint32)|1(uint64)|1.0(float16)|1.0(float32)|1.0(float64)|1970-01-01 00:00:00(datetime64[ns])|1970-01-01 00:00:00-05:00(datetime64[ns, US/Eastern])|a(object(string))| 1(object(Decimal))|[1 2 3](object(array[int32]))|1.0(float128)|(1+0j)(complex64)|(1+0j)(complex128)|A(category)|1 days 00:00:00(timedelta64[ns])| # noqa
# +-----------------------------+----------------------+----------+-------+--------+--------------------+--------------------+--------+---------+---------+---------+------------+------------+------------+-----------------------------------+-----------------------------------------------------+-----------------+--------------------+-----------------------------+-------------+-----------------+------------------+-----------+--------------------------------+ # noqa
# | boolean| None| True| True| True| True| True| True| True| True| True| False| False| False| False| False| X| X| X| False| False| False| X| False| # noqa
# | tinyint| None| 1| 1| 1| 1| 1| X| X| X| X| 1| 1| 1| X| X| X| X| X| X| X| X| 0| X| # noqa
# | smallint| None| 1| 1| 1| 1| 1| 1| X| X| X| 1| 1| 1| X| X| X| X| X| X| X| X| X| X| # noqa
# | int| None| 1| 1| 1| 1| 1| 1| 1| X| X| 1| 1| 1| X| X| X| X| X| X| X| X| X| X| # noqa
# | bigint| None| 1| 1| 1| 1| 1| 1| 1| 1| X| 1| 1| 1| 0| 18000000000000| X| X| X| X| X| X| X| X| # noqa
# | float| None| 1.0| 1.0| 1.0| 1.0| 1.0| 1.0| 1.0| 1.0| 1.0| 1.0| 1.0| 1.0| X| X| X|1.401298464324817...| X| X| X| X| X| X| # noqa
# | double| None| 1.0| 1.0| 1.0| 1.0| 1.0| 1.0| 1.0| 1.0| 1.0| 1.0| 1.0| 1.0| X| X| X| X| X| X| X| X| X| X| # noqa
# | date| None| X| X| X|datetime.date(197...| X| X| X| X| X| X| X| X| datetime.date(197...| X| X| X| X| X| X| X| X| X| # noqa
# | timestamp| None| X| X| X| X|datetime.datetime...| X| X| X| X| X| X| X| datetime.datetime...| datetime.datetime...| X| X| X| X| X| X| X| X| # noqa
# | string| None| u''|u'\x01'| u'\x01'| u'\x01'| u'\x01'| u'\x01'| u'\x01'| u'\x01'| u'\x01'| u''| u''| u''| X| X| u'a'| X| X| u''| u''| u''| X| X| # noqa
# | decimal(10,0)| None| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| Decimal('1')| X| X| X| X| X| X| # noqa
# | array<int>| None| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| [1, 2, 3]| X| X| X| X| X| # noqa
# | map<string,int>| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| # noqa
# | struct<_1:int>| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| # noqa
# | binary| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| # noqa
# +-----------------------------+----------------------+----------+-------+--------+--------------------+--------------------+--------+---------+---------+---------+------------+------------+------------+-----------------------------------+-----------------------------------------------------+-----------------+--------------------+-----------------------------+-------------+-----------------+------------------+-----------+--------------------------------+ # noqa
#
# Note: DDL formatted string is used for 'SQL Type' for simplicity. This string can be
# used in `returnType`.
# Note: The values inside of the table are generated by `repr`.
# Note: Python 2 is used to generate this table since it is used to check the backward
# compatibility often in practice.
# Note: Pandas 0.19.2 and PyArrow 0.9.0 are used.
# Note: Timezone is Singapore timezone.
# Note: 'X' means it throws an exception during the conversion.
# Note: 'binary' type is only supported with PyArrow 0.10.0+ (SPARK-23555).
# decorator @pandas_udf(returnType, functionType)
is_decorator = f is None or isinstance(f, (str, DataType))
if is_decorator:
# If DataType has been passed as a positional argument
# for decorator use it as a returnType
return_type = f or returnType
if functionType is not None:
# @pandas_udf(dataType, functionType=functionType)
# @pandas_udf(returnType=dataType, functionType=functionType)
eval_type = functionType
elif returnType is not None and isinstance(returnType, int):
# @pandas_udf(dataType, functionType)
eval_type = returnType
else:
# @pandas_udf(dataType) or @pandas_udf(returnType=dataType)
eval_type = PythonEvalType.SQL_SCALAR_PANDAS_UDF
else:
return_type = returnType
if functionType is not None:
eval_type = functionType
else:
eval_type = PythonEvalType.SQL_SCALAR_PANDAS_UDF
if return_type is None:
raise ValueError("Invalid returnType: returnType can not be None")
if eval_type not in [PythonEvalType.SQL_SCALAR_PANDAS_UDF,
PythonEvalType.SQL_GROUPED_MAP_PANDAS_UDF,
PythonEvalType.SQL_GROUPED_AGG_PANDAS_UDF]:
raise ValueError("Invalid functionType: "
"functionType must be one the values from PandasUDFType")
if is_decorator:
return functools.partial(_create_udf, returnType=return_type, evalType=eval_type)
else:
return _create_udf(f=f, returnType=return_type, evalType=eval_type) | [
"\n Creates a vectorized user defined function (UDF).\n\n :param f: user-defined function. A python function if used as a standalone function\n :param returnType: the return type of the user-defined function. The value can be either a\n :class:`pyspark.sql.types.DataType` object or a DDL-formatted type string.\n :param functionType: an enum value in :class:`pyspark.sql.functions.PandasUDFType`.\n Default: SCALAR.\n\n .. note:: Experimental\n\n The function type of the UDF can be one of the following:\n\n 1. SCALAR\n\n A scalar UDF defines a transformation: One or more `pandas.Series` -> A `pandas.Series`.\n The length of the returned `pandas.Series` must be of the same as the input `pandas.Series`.\n If the return type is :class:`StructType`, the returned value should be a `pandas.DataFrame`.\n\n :class:`MapType`, nested :class:`StructType` are currently not supported as output types.\n\n Scalar UDFs are used with :meth:`pyspark.sql.DataFrame.withColumn` and\n :meth:`pyspark.sql.DataFrame.select`.\n\n >>> from pyspark.sql.functions import pandas_udf, PandasUDFType\n >>> from pyspark.sql.types import IntegerType, StringType\n >>> slen = pandas_udf(lambda s: s.str.len(), IntegerType()) # doctest: +SKIP\n >>> @pandas_udf(StringType()) # doctest: +SKIP\n ... def to_upper(s):\n ... return s.str.upper()\n ...\n >>> @pandas_udf(\"integer\", PandasUDFType.SCALAR) # doctest: +SKIP\n ... def add_one(x):\n ... return x + 1\n ...\n >>> df = spark.createDataFrame([(1, \"John Doe\", 21)],\n ... (\"id\", \"name\", \"age\")) # doctest: +SKIP\n >>> df.select(slen(\"name\").alias(\"slen(name)\"), to_upper(\"name\"), add_one(\"age\")) \\\\\n ... .show() # doctest: +SKIP\n +----------+--------------+------------+\n |slen(name)|to_upper(name)|add_one(age)|\n +----------+--------------+------------+\n | 8| JOHN DOE| 22|\n +----------+--------------+------------+\n >>> @pandas_udf(\"first string, last string\") # doctest: +SKIP\n ... def split_expand(n):\n ... return n.str.split(expand=True)\n >>> df.select(split_expand(\"name\")).show() # doctest: +SKIP\n +------------------+\n |split_expand(name)|\n +------------------+\n | [John, Doe]|\n +------------------+\n\n .. note:: The length of `pandas.Series` within a scalar UDF is not that of the whole input\n column, but is the length of an internal batch used for each call to the function.\n Therefore, this can be used, for example, to ensure the length of each returned\n `pandas.Series`, and can not be used as the column length.\n\n 2. GROUPED_MAP\n\n A grouped map UDF defines transformation: A `pandas.DataFrame` -> A `pandas.DataFrame`\n The returnType should be a :class:`StructType` describing the schema of the returned\n `pandas.DataFrame`. The column labels of the returned `pandas.DataFrame` must either match\n the field names in the defined returnType schema if specified as strings, or match the\n field data types by position if not strings, e.g. integer indices.\n The length of the returned `pandas.DataFrame` can be arbitrary.\n\n Grouped map UDFs are used with :meth:`pyspark.sql.GroupedData.apply`.\n\n >>> from pyspark.sql.functions import pandas_udf, PandasUDFType\n >>> df = spark.createDataFrame(\n ... [(1, 1.0), (1, 2.0), (2, 3.0), (2, 5.0), (2, 10.0)],\n ... (\"id\", \"v\")) # doctest: +SKIP\n >>> @pandas_udf(\"id long, v double\", PandasUDFType.GROUPED_MAP) # doctest: +SKIP\n ... def normalize(pdf):\n ... v = pdf.v\n ... return pdf.assign(v=(v - v.mean()) / v.std())\n >>> df.groupby(\"id\").apply(normalize).show() # doctest: +SKIP\n +---+-------------------+\n | id| v|\n +---+-------------------+\n | 1|-0.7071067811865475|\n | 1| 0.7071067811865475|\n | 2|-0.8320502943378437|\n | 2|-0.2773500981126146|\n | 2| 1.1094003924504583|\n +---+-------------------+\n\n Alternatively, the user can define a function that takes two arguments.\n In this case, the grouping key(s) will be passed as the first argument and the data will\n be passed as the second argument. The grouping key(s) will be passed as a tuple of numpy\n data types, e.g., `numpy.int32` and `numpy.float64`. The data will still be passed in\n as a `pandas.DataFrame` containing all columns from the original Spark DataFrame.\n This is useful when the user does not want to hardcode grouping key(s) in the function.\n\n >>> import pandas as pd # doctest: +SKIP\n >>> from pyspark.sql.functions import pandas_udf, PandasUDFType\n >>> df = spark.createDataFrame(\n ... [(1, 1.0), (1, 2.0), (2, 3.0), (2, 5.0), (2, 10.0)],\n ... (\"id\", \"v\")) # doctest: +SKIP\n >>> @pandas_udf(\"id long, v double\", PandasUDFType.GROUPED_MAP) # doctest: +SKIP\n ... def mean_udf(key, pdf):\n ... # key is a tuple of one numpy.int64, which is the value\n ... # of 'id' for the current group\n ... return pd.DataFrame([key + (pdf.v.mean(),)])\n >>> df.groupby('id').apply(mean_udf).show() # doctest: +SKIP\n +---+---+\n | id| v|\n +---+---+\n | 1|1.5|\n | 2|6.0|\n +---+---+\n >>> @pandas_udf(\n ... \"id long, `ceil(v / 2)` long, v double\",\n ... PandasUDFType.GROUPED_MAP) # doctest: +SKIP\n >>> def sum_udf(key, pdf):\n ... # key is a tuple of two numpy.int64s, which is the values\n ... # of 'id' and 'ceil(df.v / 2)' for the current group\n ... return pd.DataFrame([key + (pdf.v.sum(),)])\n >>> df.groupby(df.id, ceil(df.v / 2)).apply(sum_udf).show() # doctest: +SKIP\n +---+-----------+----+\n | id|ceil(v / 2)| v|\n +---+-----------+----+\n | 2| 5|10.0|\n | 1| 1| 3.0|\n | 2| 3| 5.0|\n | 2| 2| 3.0|\n +---+-----------+----+\n\n .. note:: If returning a new `pandas.DataFrame` constructed with a dictionary, it is\n recommended to explicitly index the columns by name to ensure the positions are correct,\n or alternatively use an `OrderedDict`.\n For example, `pd.DataFrame({'id': ids, 'a': data}, columns=['id', 'a'])` or\n `pd.DataFrame(OrderedDict([('id', ids), ('a', data)]))`.\n\n .. seealso:: :meth:`pyspark.sql.GroupedData.apply`\n\n 3. GROUPED_AGG\n\n A grouped aggregate UDF defines a transformation: One or more `pandas.Series` -> A scalar\n The `returnType` should be a primitive data type, e.g., :class:`DoubleType`.\n The returned scalar can be either a python primitive type, e.g., `int` or `float`\n or a numpy data type, e.g., `numpy.int64` or `numpy.float64`.\n\n :class:`MapType` and :class:`StructType` are currently not supported as output types.\n\n Group aggregate UDFs are used with :meth:`pyspark.sql.GroupedData.agg` and\n :class:`pyspark.sql.Window`\n\n This example shows using grouped aggregated UDFs with groupby:\n\n >>> from pyspark.sql.functions import pandas_udf, PandasUDFType\n >>> df = spark.createDataFrame(\n ... [(1, 1.0), (1, 2.0), (2, 3.0), (2, 5.0), (2, 10.0)],\n ... (\"id\", \"v\"))\n >>> @pandas_udf(\"double\", PandasUDFType.GROUPED_AGG) # doctest: +SKIP\n ... def mean_udf(v):\n ... return v.mean()\n >>> df.groupby(\"id\").agg(mean_udf(df['v'])).show() # doctest: +SKIP\n +---+-----------+\n | id|mean_udf(v)|\n +---+-----------+\n | 1| 1.5|\n | 2| 6.0|\n +---+-----------+\n\n This example shows using grouped aggregated UDFs as window functions.\n\n >>> from pyspark.sql.functions import pandas_udf, PandasUDFType\n >>> from pyspark.sql import Window\n >>> df = spark.createDataFrame(\n ... [(1, 1.0), (1, 2.0), (2, 3.0), (2, 5.0), (2, 10.0)],\n ... (\"id\", \"v\"))\n >>> @pandas_udf(\"double\", PandasUDFType.GROUPED_AGG) # doctest: +SKIP\n ... def mean_udf(v):\n ... return v.mean()\n >>> w = (Window.partitionBy('id')\n ... .orderBy('v')\n ... .rowsBetween(-1, 0))\n >>> df.withColumn('mean_v', mean_udf(df['v']).over(w)).show() # doctest: +SKIP\n +---+----+------+\n | id| v|mean_v|\n +---+----+------+\n | 1| 1.0| 1.0|\n | 1| 2.0| 1.5|\n | 2| 3.0| 3.0|\n | 2| 5.0| 4.0|\n | 2|10.0| 7.5|\n +---+----+------+\n\n .. note:: For performance reasons, the input series to window functions are not copied.\n Therefore, mutating the input series is not allowed and will cause incorrect results.\n For the same reason, users should also not rely on the index of the input series.\n\n .. seealso:: :meth:`pyspark.sql.GroupedData.agg` and :class:`pyspark.sql.Window`\n\n .. note:: The user-defined functions are considered deterministic by default. Due to\n optimization, duplicate invocations may be eliminated or the function may even be invoked\n more times than it is present in the query. If your function is not deterministic, call\n `asNondeterministic` on the user defined function. E.g.:\n\n >>> @pandas_udf('double', PandasUDFType.SCALAR) # doctest: +SKIP\n ... def random(v):\n ... import numpy as np\n ... import pandas as pd\n ... return pd.Series(np.random.randn(len(v))\n >>> random = random.asNondeterministic() # doctest: +SKIP\n\n .. note:: The user-defined functions do not support conditional expressions or short circuiting\n in boolean expressions and it ends up with being executed all internally. If the functions\n can fail on special rows, the workaround is to incorporate the condition into the functions.\n\n .. note:: The user-defined functions do not take keyword arguments on the calling side.\n\n .. note:: The data type of returned `pandas.Series` from the user-defined functions should be\n matched with defined returnType (see :meth:`types.to_arrow_type` and\n :meth:`types.from_arrow_type`). When there is mismatch between them, Spark might do\n conversion on returned data. The conversion is not guaranteed to be correct and results\n should be checked for accuracy by users.\n "
] |
Please provide a description of the function:def to_str(value):
if isinstance(value, bool):
return str(value).lower()
elif value is None:
return value
else:
return str(value) | [
"\n A wrapper over str(), but converts bool values to lower case strings.\n If None is given, just returns None, instead of converting it to string \"None\".\n "
] |
Please provide a description of the function:def _set_opts(self, schema=None, **options):
if schema is not None:
self.schema(schema)
for k, v in options.items():
if v is not None:
self.option(k, v) | [
"\n Set named options (filter out those the value is None)\n "
] |
Please provide a description of the function:def format(self, source):
self._jreader = self._jreader.format(source)
return self | [
"Specifies the input data source format.\n\n :param source: string, name of the data source, e.g. 'json', 'parquet'.\n\n >>> df = spark.read.format('json').load('python/test_support/sql/people.json')\n >>> df.dtypes\n [('age', 'bigint'), ('name', 'string')]\n\n "
] |
Please provide a description of the function:def schema(self, schema):
from pyspark.sql import SparkSession
spark = SparkSession.builder.getOrCreate()
if isinstance(schema, StructType):
jschema = spark._jsparkSession.parseDataType(schema.json())
self._jreader = self._jreader.schema(jschema)
elif isinstance(schema, basestring):
self._jreader = self._jreader.schema(schema)
else:
raise TypeError("schema should be StructType or string")
return self | [
"Specifies the input schema.\n\n Some data sources (e.g. JSON) can infer the input schema automatically from data.\n By specifying the schema here, the underlying data source can skip the schema\n inference step, and thus speed up data loading.\n\n :param schema: a :class:`pyspark.sql.types.StructType` object or a DDL-formatted string\n (For example ``col0 INT, col1 DOUBLE``).\n\n >>> s = spark.read.schema(\"col0 INT, col1 DOUBLE\")\n "
] |
Please provide a description of the function:def option(self, key, value):
self._jreader = self._jreader.option(key, to_str(value))
return self | [
"Adds an input option for the underlying data source.\n\n You can set the following option(s) for reading files:\n * ``timeZone``: sets the string that indicates a timezone to be used to parse timestamps\n in the JSON/CSV datasources or partition values.\n If it isn't set, it uses the default value, session local timezone.\n "
] |
Please provide a description of the function:def options(self, **options):
for k in options:
self._jreader = self._jreader.option(k, to_str(options[k]))
return self | [
"Adds input options for the underlying data source.\n\n You can set the following option(s) for reading files:\n * ``timeZone``: sets the string that indicates a timezone to be used to parse timestamps\n in the JSON/CSV datasources or partition values.\n If it isn't set, it uses the default value, session local timezone.\n "
] |
Please provide a description of the function:def load(self, path=None, format=None, schema=None, **options):
if format is not None:
self.format(format)
if schema is not None:
self.schema(schema)
self.options(**options)
if isinstance(path, basestring):
return self._df(self._jreader.load(path))
elif path is not None:
if type(path) != list:
path = [path]
return self._df(self._jreader.load(self._spark._sc._jvm.PythonUtils.toSeq(path)))
else:
return self._df(self._jreader.load()) | [
"Loads data from a data source and returns it as a :class`DataFrame`.\n\n :param path: optional string or a list of string for file-system backed data sources.\n :param format: optional string for format of the data source. Default to 'parquet'.\n :param schema: optional :class:`pyspark.sql.types.StructType` for the input schema\n or a DDL-formatted string (For example ``col0 INT, col1 DOUBLE``).\n :param options: all other string options\n\n >>> df = spark.read.format(\"parquet\").load('python/test_support/sql/parquet_partitioned',\n ... opt1=True, opt2=1, opt3='str')\n >>> df.dtypes\n [('name', 'string'), ('year', 'int'), ('month', 'int'), ('day', 'int')]\n\n >>> df = spark.read.format('json').load(['python/test_support/sql/people.json',\n ... 'python/test_support/sql/people1.json'])\n >>> df.dtypes\n [('age', 'bigint'), ('aka', 'string'), ('name', 'string')]\n "
] |
Please provide a description of the function:def json(self, path, schema=None, primitivesAsString=None, prefersDecimal=None,
allowComments=None, allowUnquotedFieldNames=None, allowSingleQuotes=None,
allowNumericLeadingZero=None, allowBackslashEscapingAnyCharacter=None,
mode=None, columnNameOfCorruptRecord=None, dateFormat=None, timestampFormat=None,
multiLine=None, allowUnquotedControlChars=None, lineSep=None, samplingRatio=None,
dropFieldIfAllNull=None, encoding=None, locale=None):
self._set_opts(
schema=schema, primitivesAsString=primitivesAsString, prefersDecimal=prefersDecimal,
allowComments=allowComments, allowUnquotedFieldNames=allowUnquotedFieldNames,
allowSingleQuotes=allowSingleQuotes, allowNumericLeadingZero=allowNumericLeadingZero,
allowBackslashEscapingAnyCharacter=allowBackslashEscapingAnyCharacter,
mode=mode, columnNameOfCorruptRecord=columnNameOfCorruptRecord, dateFormat=dateFormat,
timestampFormat=timestampFormat, multiLine=multiLine,
allowUnquotedControlChars=allowUnquotedControlChars, lineSep=lineSep,
samplingRatio=samplingRatio, dropFieldIfAllNull=dropFieldIfAllNull, encoding=encoding,
locale=locale)
if isinstance(path, basestring):
path = [path]
if type(path) == list:
return self._df(self._jreader.json(self._spark._sc._jvm.PythonUtils.toSeq(path)))
elif isinstance(path, RDD):
def func(iterator):
for x in iterator:
if not isinstance(x, basestring):
x = unicode(x)
if isinstance(x, unicode):
x = x.encode("utf-8")
yield x
keyed = path.mapPartitions(func)
keyed._bypass_serializer = True
jrdd = keyed._jrdd.map(self._spark._jvm.BytesToString())
return self._df(self._jreader.json(jrdd))
else:
raise TypeError("path can be only string, list or RDD") | [
"\n Loads JSON files and returns the results as a :class:`DataFrame`.\n\n `JSON Lines <http://jsonlines.org/>`_ (newline-delimited JSON) is supported by default.\n For JSON (one record per file), set the ``multiLine`` parameter to ``true``.\n\n If the ``schema`` parameter is not specified, this function goes\n through the input once to determine the input schema.\n\n :param path: string represents path to the JSON dataset, or a list of paths,\n or RDD of Strings storing JSON objects.\n :param schema: an optional :class:`pyspark.sql.types.StructType` for the input schema or\n a DDL-formatted string (For example ``col0 INT, col1 DOUBLE``).\n :param primitivesAsString: infers all primitive values as a string type. If None is set,\n it uses the default value, ``false``.\n :param prefersDecimal: infers all floating-point values as a decimal type. If the values\n do not fit in decimal, then it infers them as doubles. If None is\n set, it uses the default value, ``false``.\n :param allowComments: ignores Java/C++ style comment in JSON records. If None is set,\n it uses the default value, ``false``.\n :param allowUnquotedFieldNames: allows unquoted JSON field names. If None is set,\n it uses the default value, ``false``.\n :param allowSingleQuotes: allows single quotes in addition to double quotes. If None is\n set, it uses the default value, ``true``.\n :param allowNumericLeadingZero: allows leading zeros in numbers (e.g. 00012). If None is\n set, it uses the default value, ``false``.\n :param allowBackslashEscapingAnyCharacter: allows accepting quoting of all character\n using backslash quoting mechanism. If None is\n set, it uses the default value, ``false``.\n :param mode: allows a mode for dealing with corrupt records during parsing. If None is\n set, it uses the default value, ``PERMISSIVE``.\n\n * ``PERMISSIVE`` : when it meets a corrupted record, puts the malformed string \\\n into a field configured by ``columnNameOfCorruptRecord``, and sets malformed \\\n fields to ``null``. To keep corrupt records, an user can set a string type \\\n field named ``columnNameOfCorruptRecord`` in an user-defined schema. If a \\\n schema does not have the field, it drops corrupt records during parsing. \\\n When inferring a schema, it implicitly adds a ``columnNameOfCorruptRecord`` \\\n field in an output schema.\n * ``DROPMALFORMED`` : ignores the whole corrupted records.\n * ``FAILFAST`` : throws an exception when it meets corrupted records.\n\n :param columnNameOfCorruptRecord: allows renaming the new field having malformed string\n created by ``PERMISSIVE`` mode. This overrides\n ``spark.sql.columnNameOfCorruptRecord``. If None is set,\n it uses the value specified in\n ``spark.sql.columnNameOfCorruptRecord``.\n :param dateFormat: sets the string that indicates a date format. Custom date formats\n follow the formats at ``java.time.format.DateTimeFormatter``. This\n applies to date type. If None is set, it uses the\n default value, ``yyyy-MM-dd``.\n :param timestampFormat: sets the string that indicates a timestamp format.\n Custom date formats follow the formats at\n ``java.time.format.DateTimeFormatter``.\n This applies to timestamp type. If None is set, it uses the\n default value, ``yyyy-MM-dd'T'HH:mm:ss.SSSXXX``.\n :param multiLine: parse one record, which may span multiple lines, per file. If None is\n set, it uses the default value, ``false``.\n :param allowUnquotedControlChars: allows JSON Strings to contain unquoted control\n characters (ASCII characters with value less than 32,\n including tab and line feed characters) or not.\n :param encoding: allows to forcibly set one of standard basic or extended encoding for\n the JSON files. For example UTF-16BE, UTF-32LE. If None is set,\n the encoding of input JSON will be detected automatically\n when the multiLine option is set to ``true``.\n :param lineSep: defines the line separator that should be used for parsing. If None is\n set, it covers all ``\\\\r``, ``\\\\r\\\\n`` and ``\\\\n``.\n :param samplingRatio: defines fraction of input JSON objects used for schema inferring.\n If None is set, it uses the default value, ``1.0``.\n :param dropFieldIfAllNull: whether to ignore column of all null values or empty\n array/struct during schema inference. If None is set, it\n uses the default value, ``false``.\n :param locale: sets a locale as language tag in IETF BCP 47 format. If None is set,\n it uses the default value, ``en-US``. For instance, ``locale`` is used while\n parsing dates and timestamps.\n\n >>> df1 = spark.read.json('python/test_support/sql/people.json')\n >>> df1.dtypes\n [('age', 'bigint'), ('name', 'string')]\n >>> rdd = sc.textFile('python/test_support/sql/people.json')\n >>> df2 = spark.read.json(rdd)\n >>> df2.dtypes\n [('age', 'bigint'), ('name', 'string')]\n\n "
] |
Please provide a description of the function:def parquet(self, *paths):
return self._df(self._jreader.parquet(_to_seq(self._spark._sc, paths))) | [
"Loads Parquet files, returning the result as a :class:`DataFrame`.\n\n You can set the following Parquet-specific option(s) for reading Parquet files:\n * ``mergeSchema``: sets whether we should merge schemas collected from all \\\n Parquet part-files. This will override ``spark.sql.parquet.mergeSchema``. \\\n The default value is specified in ``spark.sql.parquet.mergeSchema``.\n\n >>> df = spark.read.parquet('python/test_support/sql/parquet_partitioned')\n >>> df.dtypes\n [('name', 'string'), ('year', 'int'), ('month', 'int'), ('day', 'int')]\n "
] |
Please provide a description of the function:def text(self, paths, wholetext=False, lineSep=None):
self._set_opts(wholetext=wholetext, lineSep=lineSep)
if isinstance(paths, basestring):
paths = [paths]
return self._df(self._jreader.text(self._spark._sc._jvm.PythonUtils.toSeq(paths))) | [
"\n Loads text files and returns a :class:`DataFrame` whose schema starts with a\n string column named \"value\", and followed by partitioned columns if there\n are any.\n The text files must be encoded as UTF-8.\n\n By default, each line in the text file is a new row in the resulting DataFrame.\n\n :param paths: string, or list of strings, for input path(s).\n :param wholetext: if true, read each file from input path(s) as a single row.\n :param lineSep: defines the line separator that should be used for parsing. If None is\n set, it covers all ``\\\\r``, ``\\\\r\\\\n`` and ``\\\\n``.\n\n >>> df = spark.read.text('python/test_support/sql/text-test.txt')\n >>> df.collect()\n [Row(value=u'hello'), Row(value=u'this')]\n >>> df = spark.read.text('python/test_support/sql/text-test.txt', wholetext=True)\n >>> df.collect()\n [Row(value=u'hello\\\\nthis')]\n "
] |
Please provide a description of the function:def csv(self, path, schema=None, sep=None, encoding=None, quote=None, escape=None,
comment=None, header=None, inferSchema=None, ignoreLeadingWhiteSpace=None,
ignoreTrailingWhiteSpace=None, nullValue=None, nanValue=None, positiveInf=None,
negativeInf=None, dateFormat=None, timestampFormat=None, maxColumns=None,
maxCharsPerColumn=None, maxMalformedLogPerPartition=None, mode=None,
columnNameOfCorruptRecord=None, multiLine=None, charToEscapeQuoteEscaping=None,
samplingRatio=None, enforceSchema=None, emptyValue=None, locale=None, lineSep=None):
r
self._set_opts(
schema=schema, sep=sep, encoding=encoding, quote=quote, escape=escape, comment=comment,
header=header, inferSchema=inferSchema, ignoreLeadingWhiteSpace=ignoreLeadingWhiteSpace,
ignoreTrailingWhiteSpace=ignoreTrailingWhiteSpace, nullValue=nullValue,
nanValue=nanValue, positiveInf=positiveInf, negativeInf=negativeInf,
dateFormat=dateFormat, timestampFormat=timestampFormat, maxColumns=maxColumns,
maxCharsPerColumn=maxCharsPerColumn,
maxMalformedLogPerPartition=maxMalformedLogPerPartition, mode=mode,
columnNameOfCorruptRecord=columnNameOfCorruptRecord, multiLine=multiLine,
charToEscapeQuoteEscaping=charToEscapeQuoteEscaping, samplingRatio=samplingRatio,
enforceSchema=enforceSchema, emptyValue=emptyValue, locale=locale, lineSep=lineSep)
if isinstance(path, basestring):
path = [path]
if type(path) == list:
return self._df(self._jreader.csv(self._spark._sc._jvm.PythonUtils.toSeq(path)))
elif isinstance(path, RDD):
def func(iterator):
for x in iterator:
if not isinstance(x, basestring):
x = unicode(x)
if isinstance(x, unicode):
x = x.encode("utf-8")
yield x
keyed = path.mapPartitions(func)
keyed._bypass_serializer = True
jrdd = keyed._jrdd.map(self._spark._jvm.BytesToString())
# see SPARK-22112
# There aren't any jvm api for creating a dataframe from rdd storing csv.
# We can do it through creating a jvm dataset firstly and using the jvm api
# for creating a dataframe from dataset storing csv.
jdataset = self._spark._ssql_ctx.createDataset(
jrdd.rdd(),
self._spark._jvm.Encoders.STRING())
return self._df(self._jreader.csv(jdataset))
else:
raise TypeError("path can be only string, list or RDD") | [
"Loads a CSV file and returns the result as a :class:`DataFrame`.\n\n This function will go through the input once to determine the input schema if\n ``inferSchema`` is enabled. To avoid going through the entire data once, disable\n ``inferSchema`` option or specify the schema explicitly using ``schema``.\n\n :param path: string, or list of strings, for input path(s),\n or RDD of Strings storing CSV rows.\n :param schema: an optional :class:`pyspark.sql.types.StructType` for the input schema\n or a DDL-formatted string (For example ``col0 INT, col1 DOUBLE``).\n :param sep: sets a single character as a separator for each field and value.\n If None is set, it uses the default value, ``,``.\n :param encoding: decodes the CSV files by the given encoding type. If None is set,\n it uses the default value, ``UTF-8``.\n :param quote: sets a single character used for escaping quoted values where the\n separator can be part of the value. If None is set, it uses the default\n value, ``\"``. If you would like to turn off quotations, you need to set an\n empty string.\n :param escape: sets a single character used for escaping quotes inside an already\n quoted value. If None is set, it uses the default value, ``\\``.\n :param comment: sets a single character used for skipping lines beginning with this\n character. By default (None), it is disabled.\n :param header: uses the first line as names of columns. If None is set, it uses the\n default value, ``false``.\n :param inferSchema: infers the input schema automatically from data. It requires one extra\n pass over the data. If None is set, it uses the default value, ``false``.\n :param enforceSchema: If it is set to ``true``, the specified or inferred schema will be\n forcibly applied to datasource files, and headers in CSV files will be\n ignored. If the option is set to ``false``, the schema will be\n validated against all headers in CSV files or the first header in RDD\n if the ``header`` option is set to ``true``. Field names in the schema\n and column names in CSV headers are checked by their positions\n taking into account ``spark.sql.caseSensitive``. If None is set,\n ``true`` is used by default. Though the default value is ``true``,\n it is recommended to disable the ``enforceSchema`` option\n to avoid incorrect results.\n :param ignoreLeadingWhiteSpace: A flag indicating whether or not leading whitespaces from\n values being read should be skipped. If None is set, it\n uses the default value, ``false``.\n :param ignoreTrailingWhiteSpace: A flag indicating whether or not trailing whitespaces from\n values being read should be skipped. If None is set, it\n uses the default value, ``false``.\n :param nullValue: sets the string representation of a null value. If None is set, it uses\n the default value, empty string. Since 2.0.1, this ``nullValue`` param\n applies to all supported types including the string type.\n :param nanValue: sets the string representation of a non-number value. If None is set, it\n uses the default value, ``NaN``.\n :param positiveInf: sets the string representation of a positive infinity value. If None\n is set, it uses the default value, ``Inf``.\n :param negativeInf: sets the string representation of a negative infinity value. If None\n is set, it uses the default value, ``Inf``.\n :param dateFormat: sets the string that indicates a date format. Custom date formats\n follow the formats at ``java.time.format.DateTimeFormatter``. This\n applies to date type. If None is set, it uses the\n default value, ``yyyy-MM-dd``.\n :param timestampFormat: sets the string that indicates a timestamp format.\n Custom date formats follow the formats at\n ``java.time.format.DateTimeFormatter``.\n This applies to timestamp type. If None is set, it uses the\n default value, ``yyyy-MM-dd'T'HH:mm:ss.SSSXXX``.\n :param maxColumns: defines a hard limit of how many columns a record can have. If None is\n set, it uses the default value, ``20480``.\n :param maxCharsPerColumn: defines the maximum number of characters allowed for any given\n value being read. If None is set, it uses the default value,\n ``-1`` meaning unlimited length.\n :param maxMalformedLogPerPartition: this parameter is no longer used since Spark 2.2.0.\n If specified, it is ignored.\n :param mode: allows a mode for dealing with corrupt records during parsing. If None is\n set, it uses the default value, ``PERMISSIVE``.\n\n * ``PERMISSIVE`` : when it meets a corrupted record, puts the malformed string \\\n into a field configured by ``columnNameOfCorruptRecord``, and sets malformed \\\n fields to ``null``. To keep corrupt records, an user can set a string type \\\n field named ``columnNameOfCorruptRecord`` in an user-defined schema. If a \\\n schema does not have the field, it drops corrupt records during parsing. \\\n A record with less/more tokens than schema is not a corrupted record to CSV. \\\n When it meets a record having fewer tokens than the length of the schema, \\\n sets ``null`` to extra fields. When the record has more tokens than the \\\n length of the schema, it drops extra tokens.\n * ``DROPMALFORMED`` : ignores the whole corrupted records.\n * ``FAILFAST`` : throws an exception when it meets corrupted records.\n\n :param columnNameOfCorruptRecord: allows renaming the new field having malformed string\n created by ``PERMISSIVE`` mode. This overrides\n ``spark.sql.columnNameOfCorruptRecord``. If None is set,\n it uses the value specified in\n ``spark.sql.columnNameOfCorruptRecord``.\n :param multiLine: parse records, which may span multiple lines. If None is\n set, it uses the default value, ``false``.\n :param charToEscapeQuoteEscaping: sets a single character used for escaping the escape for\n the quote character. If None is set, the default value is\n escape character when escape and quote characters are\n different, ``\\0`` otherwise.\n :param samplingRatio: defines fraction of rows used for schema inferring.\n If None is set, it uses the default value, ``1.0``.\n :param emptyValue: sets the string representation of an empty value. If None is set, it uses\n the default value, empty string.\n :param locale: sets a locale as language tag in IETF BCP 47 format. If None is set,\n it uses the default value, ``en-US``. For instance, ``locale`` is used while\n parsing dates and timestamps.\n :param lineSep: defines the line separator that should be used for parsing. If None is\n set, it covers all ``\\\\r``, ``\\\\r\\\\n`` and ``\\\\n``.\n Maximum length is 1 character.\n\n >>> df = spark.read.csv('python/test_support/sql/ages.csv')\n >>> df.dtypes\n [('_c0', 'string'), ('_c1', 'string')]\n >>> rdd = sc.textFile('python/test_support/sql/ages.csv')\n >>> df2 = spark.read.csv(rdd)\n >>> df2.dtypes\n [('_c0', 'string'), ('_c1', 'string')]\n "
] |
Please provide a description of the function:def orc(self, path):
if isinstance(path, basestring):
path = [path]
return self._df(self._jreader.orc(_to_seq(self._spark._sc, path))) | [
"Loads ORC files, returning the result as a :class:`DataFrame`.\n\n >>> df = spark.read.orc('python/test_support/sql/orc_partitioned')\n >>> df.dtypes\n [('a', 'bigint'), ('b', 'int'), ('c', 'int')]\n "
] |
Please provide a description of the function:def jdbc(self, url, table, column=None, lowerBound=None, upperBound=None, numPartitions=None,
predicates=None, properties=None):
if properties is None:
properties = dict()
jprop = JavaClass("java.util.Properties", self._spark._sc._gateway._gateway_client)()
for k in properties:
jprop.setProperty(k, properties[k])
if column is not None:
assert lowerBound is not None, "lowerBound can not be None when ``column`` is specified"
assert upperBound is not None, "upperBound can not be None when ``column`` is specified"
assert numPartitions is not None, \
"numPartitions can not be None when ``column`` is specified"
return self._df(self._jreader.jdbc(url, table, column, int(lowerBound), int(upperBound),
int(numPartitions), jprop))
if predicates is not None:
gateway = self._spark._sc._gateway
jpredicates = utils.toJArray(gateway, gateway.jvm.java.lang.String, predicates)
return self._df(self._jreader.jdbc(url, table, jpredicates, jprop))
return self._df(self._jreader.jdbc(url, table, jprop)) | [
"\n Construct a :class:`DataFrame` representing the database table named ``table``\n accessible via JDBC URL ``url`` and connection ``properties``.\n\n Partitions of the table will be retrieved in parallel if either ``column`` or\n ``predicates`` is specified. ``lowerBound`, ``upperBound`` and ``numPartitions``\n is needed when ``column`` is specified.\n\n If both ``column`` and ``predicates`` are specified, ``column`` will be used.\n\n .. note:: Don't create too many partitions in parallel on a large cluster;\n otherwise Spark might crash your external database systems.\n\n :param url: a JDBC URL of the form ``jdbc:subprotocol:subname``\n :param table: the name of the table\n :param column: the name of an integer column that will be used for partitioning;\n if this parameter is specified, then ``numPartitions``, ``lowerBound``\n (inclusive), and ``upperBound`` (exclusive) will form partition strides\n for generated WHERE clause expressions used to split the column\n ``column`` evenly\n :param lowerBound: the minimum value of ``column`` used to decide partition stride\n :param upperBound: the maximum value of ``column`` used to decide partition stride\n :param numPartitions: the number of partitions\n :param predicates: a list of expressions suitable for inclusion in WHERE clauses;\n each one defines one partition of the :class:`DataFrame`\n :param properties: a dictionary of JDBC database connection arguments. Normally at\n least properties \"user\" and \"password\" with their corresponding values.\n For example { 'user' : 'SYSTEM', 'password' : 'mypassword' }\n :return: a DataFrame\n "
] |
Please provide a description of the function:def mode(self, saveMode):
# At the JVM side, the default value of mode is already set to "error".
# So, if the given saveMode is None, we will not call JVM-side's mode method.
if saveMode is not None:
self._jwrite = self._jwrite.mode(saveMode)
return self | [
"Specifies the behavior when data or table already exists.\n\n Options include:\n\n * `append`: Append contents of this :class:`DataFrame` to existing data.\n * `overwrite`: Overwrite existing data.\n * `error` or `errorifexists`: Throw an exception if data already exists.\n * `ignore`: Silently ignore this operation if data already exists.\n\n >>> df.write.mode('append').parquet(os.path.join(tempfile.mkdtemp(), 'data'))\n "
] |
Please provide a description of the function:def format(self, source):
self._jwrite = self._jwrite.format(source)
return self | [
"Specifies the underlying output data source.\n\n :param source: string, name of the data source, e.g. 'json', 'parquet'.\n\n >>> df.write.format('json').save(os.path.join(tempfile.mkdtemp(), 'data'))\n "
] |
Please provide a description of the function:def option(self, key, value):
self._jwrite = self._jwrite.option(key, to_str(value))
return self | [
"Adds an output option for the underlying data source.\n\n You can set the following option(s) for writing files:\n * ``timeZone``: sets the string that indicates a timezone to be used to format\n timestamps in the JSON/CSV datasources or partition values.\n If it isn't set, it uses the default value, session local timezone.\n "
] |
Please provide a description of the function:def options(self, **options):
for k in options:
self._jwrite = self._jwrite.option(k, to_str(options[k]))
return self | [
"Adds output options for the underlying data source.\n\n You can set the following option(s) for writing files:\n * ``timeZone``: sets the string that indicates a timezone to be used to format\n timestamps in the JSON/CSV datasources or partition values.\n If it isn't set, it uses the default value, session local timezone.\n "
] |
Please provide a description of the function:def partitionBy(self, *cols):
if len(cols) == 1 and isinstance(cols[0], (list, tuple)):
cols = cols[0]
self._jwrite = self._jwrite.partitionBy(_to_seq(self._spark._sc, cols))
return self | [
"Partitions the output by the given columns on the file system.\n\n If specified, the output is laid out on the file system similar\n to Hive's partitioning scheme.\n\n :param cols: name of columns\n\n >>> df.write.partitionBy('year', 'month').parquet(os.path.join(tempfile.mkdtemp(), 'data'))\n "
] |
Please provide a description of the function:def sortBy(self, col, *cols):
if isinstance(col, (list, tuple)):
if cols:
raise ValueError("col is a {0} but cols are not empty".format(type(col)))
col, cols = col[0], col[1:]
if not all(isinstance(c, basestring) for c in cols) or not(isinstance(col, basestring)):
raise TypeError("all names should be `str`")
self._jwrite = self._jwrite.sortBy(col, _to_seq(self._spark._sc, cols))
return self | [
"Sorts the output in each bucket by the given columns on the file system.\n\n :param col: a name of a column, or a list of names.\n :param cols: additional names (optional). If `col` is a list it should be empty.\n\n >>> (df.write.format('parquet') # doctest: +SKIP\n ... .bucketBy(100, 'year', 'month')\n ... .sortBy('day')\n ... .mode(\"overwrite\")\n ... .saveAsTable('sorted_bucketed_table'))\n "
] |
Please provide a description of the function:def save(self, path=None, format=None, mode=None, partitionBy=None, **options):
self.mode(mode).options(**options)
if partitionBy is not None:
self.partitionBy(partitionBy)
if format is not None:
self.format(format)
if path is None:
self._jwrite.save()
else:
self._jwrite.save(path) | [
"Saves the contents of the :class:`DataFrame` to a data source.\n\n The data source is specified by the ``format`` and a set of ``options``.\n If ``format`` is not specified, the default data source configured by\n ``spark.sql.sources.default`` will be used.\n\n :param path: the path in a Hadoop supported file system\n :param format: the format used to save\n :param mode: specifies the behavior of the save operation when data already exists.\n\n * ``append``: Append contents of this :class:`DataFrame` to existing data.\n * ``overwrite``: Overwrite existing data.\n * ``ignore``: Silently ignore this operation if data already exists.\n * ``error`` or ``errorifexists`` (default case): Throw an exception if data already \\\n exists.\n :param partitionBy: names of partitioning columns\n :param options: all other string options\n\n >>> df.write.mode('append').parquet(os.path.join(tempfile.mkdtemp(), 'data'))\n "
] |
Please provide a description of the function:def insertInto(self, tableName, overwrite=False):
self._jwrite.mode("overwrite" if overwrite else "append").insertInto(tableName) | [
"Inserts the content of the :class:`DataFrame` to the specified table.\n\n It requires that the schema of the class:`DataFrame` is the same as the\n schema of the table.\n\n Optionally overwriting any existing data.\n "
] |
Please provide a description of the function:def saveAsTable(self, name, format=None, mode=None, partitionBy=None, **options):
self.mode(mode).options(**options)
if partitionBy is not None:
self.partitionBy(partitionBy)
if format is not None:
self.format(format)
self._jwrite.saveAsTable(name) | [
"Saves the content of the :class:`DataFrame` as the specified table.\n\n In the case the table already exists, behavior of this function depends on the\n save mode, specified by the `mode` function (default to throwing an exception).\n When `mode` is `Overwrite`, the schema of the :class:`DataFrame` does not need to be\n the same as that of the existing table.\n\n * `append`: Append contents of this :class:`DataFrame` to existing data.\n * `overwrite`: Overwrite existing data.\n * `error` or `errorifexists`: Throw an exception if data already exists.\n * `ignore`: Silently ignore this operation if data already exists.\n\n :param name: the table name\n :param format: the format used to save\n :param mode: one of `append`, `overwrite`, `error`, `errorifexists`, `ignore` \\\n (default: error)\n :param partitionBy: names of partitioning columns\n :param options: all other string options\n "
] |
Please provide a description of the function:def json(self, path, mode=None, compression=None, dateFormat=None, timestampFormat=None,
lineSep=None, encoding=None):
self.mode(mode)
self._set_opts(
compression=compression, dateFormat=dateFormat, timestampFormat=timestampFormat,
lineSep=lineSep, encoding=encoding)
self._jwrite.json(path) | [
"Saves the content of the :class:`DataFrame` in JSON format\n (`JSON Lines text format or newline-delimited JSON <http://jsonlines.org/>`_) at the\n specified path.\n\n :param path: the path in any Hadoop supported file system\n :param mode: specifies the behavior of the save operation when data already exists.\n\n * ``append``: Append contents of this :class:`DataFrame` to existing data.\n * ``overwrite``: Overwrite existing data.\n * ``ignore``: Silently ignore this operation if data already exists.\n * ``error`` or ``errorifexists`` (default case): Throw an exception if data already \\\n exists.\n :param compression: compression codec to use when saving to file. This can be one of the\n known case-insensitive shorten names (none, bzip2, gzip, lz4,\n snappy and deflate).\n :param dateFormat: sets the string that indicates a date format. Custom date formats\n follow the formats at ``java.time.format.DateTimeFormatter``. This\n applies to date type. If None is set, it uses the\n default value, ``yyyy-MM-dd``.\n :param timestampFormat: sets the string that indicates a timestamp format.\n Custom date formats follow the formats at\n ``java.time.format.DateTimeFormatter``.\n This applies to timestamp type. If None is set, it uses the\n default value, ``yyyy-MM-dd'T'HH:mm:ss.SSSXXX``.\n :param encoding: specifies encoding (charset) of saved json files. If None is set,\n the default UTF-8 charset will be used.\n :param lineSep: defines the line separator that should be used for writing. If None is\n set, it uses the default value, ``\\\\n``.\n\n >>> df.write.json(os.path.join(tempfile.mkdtemp(), 'data'))\n "
] |
Please provide a description of the function:def parquet(self, path, mode=None, partitionBy=None, compression=None):
self.mode(mode)
if partitionBy is not None:
self.partitionBy(partitionBy)
self._set_opts(compression=compression)
self._jwrite.parquet(path) | [
"Saves the content of the :class:`DataFrame` in Parquet format at the specified path.\n\n :param path: the path in any Hadoop supported file system\n :param mode: specifies the behavior of the save operation when data already exists.\n\n * ``append``: Append contents of this :class:`DataFrame` to existing data.\n * ``overwrite``: Overwrite existing data.\n * ``ignore``: Silently ignore this operation if data already exists.\n * ``error`` or ``errorifexists`` (default case): Throw an exception if data already \\\n exists.\n :param partitionBy: names of partitioning columns\n :param compression: compression codec to use when saving to file. This can be one of the\n known case-insensitive shorten names (none, uncompressed, snappy, gzip,\n lzo, brotli, lz4, and zstd). This will override\n ``spark.sql.parquet.compression.codec``. If None is set, it uses the\n value specified in ``spark.sql.parquet.compression.codec``.\n\n >>> df.write.parquet(os.path.join(tempfile.mkdtemp(), 'data'))\n "
] |
Please provide a description of the function:def text(self, path, compression=None, lineSep=None):
self._set_opts(compression=compression, lineSep=lineSep)
self._jwrite.text(path) | [
"Saves the content of the DataFrame in a text file at the specified path.\n The text files will be encoded as UTF-8.\n\n :param path: the path in any Hadoop supported file system\n :param compression: compression codec to use when saving to file. This can be one of the\n known case-insensitive shorten names (none, bzip2, gzip, lz4,\n snappy and deflate).\n :param lineSep: defines the line separator that should be used for writing. If None is\n set, it uses the default value, ``\\\\n``.\n\n The DataFrame must have only one column that is of string type.\n Each row becomes a new line in the output file.\n "
] |
Please provide a description of the function:def csv(self, path, mode=None, compression=None, sep=None, quote=None, escape=None,
header=None, nullValue=None, escapeQuotes=None, quoteAll=None, dateFormat=None,
timestampFormat=None, ignoreLeadingWhiteSpace=None, ignoreTrailingWhiteSpace=None,
charToEscapeQuoteEscaping=None, encoding=None, emptyValue=None, lineSep=None):
r
self.mode(mode)
self._set_opts(compression=compression, sep=sep, quote=quote, escape=escape, header=header,
nullValue=nullValue, escapeQuotes=escapeQuotes, quoteAll=quoteAll,
dateFormat=dateFormat, timestampFormat=timestampFormat,
ignoreLeadingWhiteSpace=ignoreLeadingWhiteSpace,
ignoreTrailingWhiteSpace=ignoreTrailingWhiteSpace,
charToEscapeQuoteEscaping=charToEscapeQuoteEscaping,
encoding=encoding, emptyValue=emptyValue, lineSep=lineSep)
self._jwrite.csv(path) | [
"Saves the content of the :class:`DataFrame` in CSV format at the specified path.\n\n :param path: the path in any Hadoop supported file system\n :param mode: specifies the behavior of the save operation when data already exists.\n\n * ``append``: Append contents of this :class:`DataFrame` to existing data.\n * ``overwrite``: Overwrite existing data.\n * ``ignore``: Silently ignore this operation if data already exists.\n * ``error`` or ``errorifexists`` (default case): Throw an exception if data already \\\n exists.\n\n :param compression: compression codec to use when saving to file. This can be one of the\n known case-insensitive shorten names (none, bzip2, gzip, lz4,\n snappy and deflate).\n :param sep: sets a single character as a separator for each field and value. If None is\n set, it uses the default value, ``,``.\n :param quote: sets a single character used for escaping quoted values where the\n separator can be part of the value. If None is set, it uses the default\n value, ``\"``. If an empty string is set, it uses ``u0000`` (null character).\n :param escape: sets a single character used for escaping quotes inside an already\n quoted value. If None is set, it uses the default value, ``\\``\n :param escapeQuotes: a flag indicating whether values containing quotes should always\n be enclosed in quotes. If None is set, it uses the default value\n ``true``, escaping all values containing a quote character.\n :param quoteAll: a flag indicating whether all values should always be enclosed in\n quotes. If None is set, it uses the default value ``false``,\n only escaping values containing a quote character.\n :param header: writes the names of columns as the first line. If None is set, it uses\n the default value, ``false``.\n :param nullValue: sets the string representation of a null value. If None is set, it uses\n the default value, empty string.\n :param dateFormat: sets the string that indicates a date format. Custom date formats\n follow the formats at ``java.time.format.DateTimeFormatter``. This\n applies to date type. If None is set, it uses the\n default value, ``yyyy-MM-dd``.\n :param timestampFormat: sets the string that indicates a timestamp format.\n Custom date formats follow the formats at\n ``java.time.format.DateTimeFormatter``.\n This applies to timestamp type. If None is set, it uses the\n default value, ``yyyy-MM-dd'T'HH:mm:ss.SSSXXX``.\n :param ignoreLeadingWhiteSpace: a flag indicating whether or not leading whitespaces from\n values being written should be skipped. If None is set, it\n uses the default value, ``true``.\n :param ignoreTrailingWhiteSpace: a flag indicating whether or not trailing whitespaces from\n values being written should be skipped. If None is set, it\n uses the default value, ``true``.\n :param charToEscapeQuoteEscaping: sets a single character used for escaping the escape for\n the quote character. If None is set, the default value is\n escape character when escape and quote characters are\n different, ``\\0`` otherwise..\n :param encoding: sets the encoding (charset) of saved csv files. If None is set,\n the default UTF-8 charset will be used.\n :param emptyValue: sets the string representation of an empty value. If None is set, it uses\n the default value, ``\"\"``.\n :param lineSep: defines the line separator that should be used for writing. If None is\n set, it uses the default value, ``\\\\n``. Maximum length is 1 character.\n\n >>> df.write.csv(os.path.join(tempfile.mkdtemp(), 'data'))\n "
] |
Please provide a description of the function:def orc(self, path, mode=None, partitionBy=None, compression=None):
self.mode(mode)
if partitionBy is not None:
self.partitionBy(partitionBy)
self._set_opts(compression=compression)
self._jwrite.orc(path) | [
"Saves the content of the :class:`DataFrame` in ORC format at the specified path.\n\n :param path: the path in any Hadoop supported file system\n :param mode: specifies the behavior of the save operation when data already exists.\n\n * ``append``: Append contents of this :class:`DataFrame` to existing data.\n * ``overwrite``: Overwrite existing data.\n * ``ignore``: Silently ignore this operation if data already exists.\n * ``error`` or ``errorifexists`` (default case): Throw an exception if data already \\\n exists.\n :param partitionBy: names of partitioning columns\n :param compression: compression codec to use when saving to file. This can be one of the\n known case-insensitive shorten names (none, snappy, zlib, and lzo).\n This will override ``orc.compress`` and\n ``spark.sql.orc.compression.codec``. If None is set, it uses the value\n specified in ``spark.sql.orc.compression.codec``.\n\n >>> orc_df = spark.read.orc('python/test_support/sql/orc_partitioned')\n >>> orc_df.write.orc(os.path.join(tempfile.mkdtemp(), 'data'))\n "
] |
Please provide a description of the function:def jdbc(self, url, table, mode=None, properties=None):
if properties is None:
properties = dict()
jprop = JavaClass("java.util.Properties", self._spark._sc._gateway._gateway_client)()
for k in properties:
jprop.setProperty(k, properties[k])
self.mode(mode)._jwrite.jdbc(url, table, jprop) | [
"Saves the content of the :class:`DataFrame` to an external database table via JDBC.\n\n .. note:: Don't create too many partitions in parallel on a large cluster;\n otherwise Spark might crash your external database systems.\n\n :param url: a JDBC URL of the form ``jdbc:subprotocol:subname``\n :param table: Name of the table in the external database.\n :param mode: specifies the behavior of the save operation when data already exists.\n\n * ``append``: Append contents of this :class:`DataFrame` to existing data.\n * ``overwrite``: Overwrite existing data.\n * ``ignore``: Silently ignore this operation if data already exists.\n * ``error`` or ``errorifexists`` (default case): Throw an exception if data already \\\n exists.\n :param properties: a dictionary of JDBC database connection arguments. Normally at\n least properties \"user\" and \"password\" with their corresponding values.\n For example { 'user' : 'SYSTEM', 'password' : 'mypassword' }\n "
] |
Please provide a description of the function:def createStream(ssc, kinesisAppName, streamName, endpointUrl, regionName,
initialPositionInStream, checkpointInterval,
storageLevel=StorageLevel.MEMORY_AND_DISK_2,
awsAccessKeyId=None, awsSecretKey=None, decoder=utf8_decoder,
stsAssumeRoleArn=None, stsSessionName=None, stsExternalId=None):
jlevel = ssc._sc._getJavaStorageLevel(storageLevel)
jduration = ssc._jduration(checkpointInterval)
try:
# Use KinesisUtilsPythonHelper to access Scala's KinesisUtils
helper = ssc._jvm.org.apache.spark.streaming.kinesis.KinesisUtilsPythonHelper()
except TypeError as e:
if str(e) == "'JavaPackage' object is not callable":
_print_missing_jar(
"Streaming's Kinesis",
"streaming-kinesis-asl",
"streaming-kinesis-asl-assembly",
ssc.sparkContext.version)
raise
jstream = helper.createStream(ssc._jssc, kinesisAppName, streamName, endpointUrl,
regionName, initialPositionInStream, jduration, jlevel,
awsAccessKeyId, awsSecretKey, stsAssumeRoleArn,
stsSessionName, stsExternalId)
stream = DStream(jstream, ssc, NoOpSerializer())
return stream.map(lambda v: decoder(v)) | [
"\n Create an input stream that pulls messages from a Kinesis stream. This uses the\n Kinesis Client Library (KCL) to pull messages from Kinesis.\n\n .. note:: The given AWS credentials will get saved in DStream checkpoints if checkpointing\n is enabled. Make sure that your checkpoint directory is secure.\n\n :param ssc: StreamingContext object\n :param kinesisAppName: Kinesis application name used by the Kinesis Client Library (KCL) to\n update DynamoDB\n :param streamName: Kinesis stream name\n :param endpointUrl: Url of Kinesis service (e.g., https://kinesis.us-east-1.amazonaws.com)\n :param regionName: Name of region used by the Kinesis Client Library (KCL) to update\n DynamoDB (lease coordination and checkpointing) and CloudWatch (metrics)\n :param initialPositionInStream: In the absence of Kinesis checkpoint info, this is the\n worker's initial starting position in the stream. The\n values are either the beginning of the stream per Kinesis'\n limit of 24 hours (InitialPositionInStream.TRIM_HORIZON) or\n the tip of the stream (InitialPositionInStream.LATEST).\n :param checkpointInterval: Checkpoint interval for Kinesis checkpointing. See the Kinesis\n Spark Streaming documentation for more details on the different\n types of checkpoints.\n :param storageLevel: Storage level to use for storing the received objects (default is\n StorageLevel.MEMORY_AND_DISK_2)\n :param awsAccessKeyId: AWS AccessKeyId (default is None. If None, will use\n DefaultAWSCredentialsProviderChain)\n :param awsSecretKey: AWS SecretKey (default is None. If None, will use\n DefaultAWSCredentialsProviderChain)\n :param decoder: A function used to decode value (default is utf8_decoder)\n :param stsAssumeRoleArn: ARN of IAM role to assume when using STS sessions to read from\n the Kinesis stream (default is None).\n :param stsSessionName: Name to uniquely identify STS sessions used to read from Kinesis\n stream, if STS is being used (default is None).\n :param stsExternalId: External ID that can be used to validate against the assumed IAM\n role's trust policy, if STS is being used (default is None).\n :return: A DStream object\n "
] |
Please provide a description of the function:def choose_jira_assignee(issue, asf_jira):
while True:
try:
reporter = issue.fields.reporter
commentors = map(lambda x: x.author, issue.fields.comment.comments)
candidates = set(commentors)
candidates.add(reporter)
candidates = list(candidates)
print("JIRA is unassigned, choose assignee")
for idx, author in enumerate(candidates):
if author.key == "apachespark":
continue
annotations = ["Reporter"] if author == reporter else []
if author in commentors:
annotations.append("Commentor")
print("[%d] %s (%s)" % (idx, author.displayName, ",".join(annotations)))
raw_assignee = input(
"Enter number of user, or userid, to assign to (blank to leave unassigned):")
if raw_assignee == "":
return None
else:
try:
id = int(raw_assignee)
assignee = candidates[id]
except:
# assume it's a user id, and try to assign (might fail, we just prompt again)
assignee = asf_jira.user(raw_assignee)
asf_jira.assign_issue(issue.key, assignee.key)
return assignee
except KeyboardInterrupt:
raise
except:
traceback.print_exc()
print("Error assigning JIRA, try again (or leave blank and fix manually)") | [
"\n Prompt the user to choose who to assign the issue to in jira, given a list of candidates,\n including the original reporter and all commentors\n "
] |
Please provide a description of the function:def standardize_jira_ref(text):
jira_refs = []
components = []
# If the string is compliant, no need to process any further
if (re.search(r'^\[SPARK-[0-9]{3,6}\](\[[A-Z0-9_\s,]+\] )+\S+', text)):
return text
# Extract JIRA ref(s):
pattern = re.compile(r'(SPARK[-\s]*[0-9]{3,6})+', re.IGNORECASE)
for ref in pattern.findall(text):
# Add brackets, replace spaces with a dash, & convert to uppercase
jira_refs.append('[' + re.sub(r'\s+', '-', ref.upper()) + ']')
text = text.replace(ref, '')
# Extract spark component(s):
# Look for alphanumeric chars, spaces, dashes, periods, and/or commas
pattern = re.compile(r'(\[[\w\s,.-]+\])', re.IGNORECASE)
for component in pattern.findall(text):
components.append(component.upper())
text = text.replace(component, '')
# Cleanup any remaining symbols:
pattern = re.compile(r'^\W+(.*)', re.IGNORECASE)
if (pattern.search(text) is not None):
text = pattern.search(text).groups()[0]
# Assemble full text (JIRA ref(s), module(s), remaining text)
clean_text = ''.join(jira_refs).strip() + ''.join(components).strip() + " " + text.strip()
# Replace multiple spaces with a single space, e.g. if no jira refs and/or components were
# included
clean_text = re.sub(r'\s+', ' ', clean_text.strip())
return clean_text | [
"\n Standardize the [SPARK-XXXXX] [MODULE] prefix\n Converts \"[SPARK-XXX][mllib] Issue\", \"[MLLib] SPARK-XXX. Issue\" or \"SPARK XXX [MLLIB]: Issue\" to\n \"[SPARK-XXX][MLLIB] Issue\"\n\n >>> standardize_jira_ref(\n ... \"[SPARK-5821] [SQL] ParquetRelation2 CTAS should check if delete is successful\")\n '[SPARK-5821][SQL] ParquetRelation2 CTAS should check if delete is successful'\n >>> standardize_jira_ref(\n ... \"[SPARK-4123][Project Infra][WIP]: Show new dependencies added in pull requests\")\n '[SPARK-4123][PROJECT INFRA][WIP] Show new dependencies added in pull requests'\n >>> standardize_jira_ref(\"[MLlib] Spark 5954: Top by key\")\n '[SPARK-5954][MLLIB] Top by key'\n >>> standardize_jira_ref(\"[SPARK-979] a LRU scheduler for load balancing in TaskSchedulerImpl\")\n '[SPARK-979] a LRU scheduler for load balancing in TaskSchedulerImpl'\n >>> standardize_jira_ref(\n ... \"SPARK-1094 Support MiMa for reporting binary compatibility across versions.\")\n '[SPARK-1094] Support MiMa for reporting binary compatibility across versions.'\n >>> standardize_jira_ref(\"[WIP] [SPARK-1146] Vagrant support for Spark\")\n '[SPARK-1146][WIP] Vagrant support for Spark'\n >>> standardize_jira_ref(\n ... \"SPARK-1032. If Yarn app fails before registering, app master stays aroun...\")\n '[SPARK-1032] If Yarn app fails before registering, app master stays aroun...'\n >>> standardize_jira_ref(\n ... \"[SPARK-6250][SPARK-6146][SPARK-5911][SQL] Types are now reserved words in DDL parser.\")\n '[SPARK-6250][SPARK-6146][SPARK-5911][SQL] Types are now reserved words in DDL parser.'\n >>> standardize_jira_ref(\"Additional information for users building from source code\")\n 'Additional information for users building from source code'\n "
] |
Please provide a description of the function:def _parse_libsvm_line(line):
items = line.split(None)
label = float(items[0])
nnz = len(items) - 1
indices = np.zeros(nnz, dtype=np.int32)
values = np.zeros(nnz)
for i in xrange(nnz):
index, value = items[1 + i].split(":")
indices[i] = int(index) - 1
values[i] = float(value)
return label, indices, values | [
"\n Parses a line in LIBSVM format into (label, indices, values).\n "
] |
Please provide a description of the function:def _convert_labeled_point_to_libsvm(p):
from pyspark.mllib.regression import LabeledPoint
assert isinstance(p, LabeledPoint)
items = [str(p.label)]
v = _convert_to_vector(p.features)
if isinstance(v, SparseVector):
nnz = len(v.indices)
for i in xrange(nnz):
items.append(str(v.indices[i] + 1) + ":" + str(v.values[i]))
else:
for i in xrange(len(v)):
items.append(str(i + 1) + ":" + str(v[i]))
return " ".join(items) | [
"Converts a LabeledPoint to a string in LIBSVM format."
] |
Please provide a description of the function:def loadLibSVMFile(sc, path, numFeatures=-1, minPartitions=None):
from pyspark.mllib.regression import LabeledPoint
lines = sc.textFile(path, minPartitions)
parsed = lines.map(lambda l: MLUtils._parse_libsvm_line(l))
if numFeatures <= 0:
parsed.cache()
numFeatures = parsed.map(lambda x: -1 if x[1].size == 0 else x[1][-1]).reduce(max) + 1
return parsed.map(lambda x: LabeledPoint(x[0], Vectors.sparse(numFeatures, x[1], x[2]))) | [
"\n Loads labeled data in the LIBSVM format into an RDD of\n LabeledPoint. The LIBSVM format is a text-based format used by\n LIBSVM and LIBLINEAR. Each line represents a labeled sparse\n feature vector using the following format:\n\n label index1:value1 index2:value2 ...\n\n where the indices are one-based and in ascending order. This\n method parses each line into a LabeledPoint, where the feature\n indices are converted to zero-based.\n\n :param sc: Spark context\n :param path: file or directory path in any Hadoop-supported file\n system URI\n :param numFeatures: number of features, which will be determined\n from the input data if a nonpositive value\n is given. This is useful when the dataset is\n already split into multiple files and you\n want to load them separately, because some\n features may not present in certain files,\n which leads to inconsistent feature\n dimensions.\n :param minPartitions: min number of partitions\n @return: labeled data stored as an RDD of LabeledPoint\n\n >>> from tempfile import NamedTemporaryFile\n >>> from pyspark.mllib.util import MLUtils\n >>> from pyspark.mllib.regression import LabeledPoint\n >>> tempFile = NamedTemporaryFile(delete=True)\n >>> _ = tempFile.write(b\"+1 1:1.0 3:2.0 5:3.0\\\\n-1\\\\n-1 2:4.0 4:5.0 6:6.0\")\n >>> tempFile.flush()\n >>> examples = MLUtils.loadLibSVMFile(sc, tempFile.name).collect()\n >>> tempFile.close()\n >>> examples[0]\n LabeledPoint(1.0, (6,[0,2,4],[1.0,2.0,3.0]))\n >>> examples[1]\n LabeledPoint(-1.0, (6,[],[]))\n >>> examples[2]\n LabeledPoint(-1.0, (6,[1,3,5],[4.0,5.0,6.0]))\n "
] |
Please provide a description of the function:def saveAsLibSVMFile(data, dir):
lines = data.map(lambda p: MLUtils._convert_labeled_point_to_libsvm(p))
lines.saveAsTextFile(dir) | [
"\n Save labeled data in LIBSVM format.\n\n :param data: an RDD of LabeledPoint to be saved\n :param dir: directory to save the data\n\n >>> from tempfile import NamedTemporaryFile\n >>> from fileinput import input\n >>> from pyspark.mllib.regression import LabeledPoint\n >>> from glob import glob\n >>> from pyspark.mllib.util import MLUtils\n >>> examples = [LabeledPoint(1.1, Vectors.sparse(3, [(0, 1.23), (2, 4.56)])),\n ... LabeledPoint(0.0, Vectors.dense([1.01, 2.02, 3.03]))]\n >>> tempFile = NamedTemporaryFile(delete=True)\n >>> tempFile.close()\n >>> MLUtils.saveAsLibSVMFile(sc.parallelize(examples), tempFile.name)\n >>> ''.join(sorted(input(glob(tempFile.name + \"/part-0000*\"))))\n '0.0 1:1.01 2:2.02 3:3.03\\\\n1.1 1:1.23 3:4.56\\\\n'\n "
] |
Please provide a description of the function:def loadLabeledPoints(sc, path, minPartitions=None):
minPartitions = minPartitions or min(sc.defaultParallelism, 2)
return callMLlibFunc("loadLabeledPoints", sc, path, minPartitions) | [
"\n Load labeled points saved using RDD.saveAsTextFile.\n\n :param sc: Spark context\n :param path: file or directory path in any Hadoop-supported file\n system URI\n :param minPartitions: min number of partitions\n @return: labeled data stored as an RDD of LabeledPoint\n\n >>> from tempfile import NamedTemporaryFile\n >>> from pyspark.mllib.util import MLUtils\n >>> from pyspark.mllib.regression import LabeledPoint\n >>> examples = [LabeledPoint(1.1, Vectors.sparse(3, [(0, -1.23), (2, 4.56e-7)])),\n ... LabeledPoint(0.0, Vectors.dense([1.01, 2.02, 3.03]))]\n >>> tempFile = NamedTemporaryFile(delete=True)\n >>> tempFile.close()\n >>> sc.parallelize(examples, 1).saveAsTextFile(tempFile.name)\n >>> MLUtils.loadLabeledPoints(sc, tempFile.name).collect()\n [LabeledPoint(1.1, (3,[0,2],[-1.23,4.56e-07])), LabeledPoint(0.0, [1.01,2.02,3.03])]\n "
] |
Please provide a description of the function:def appendBias(data):
vec = _convert_to_vector(data)
if isinstance(vec, SparseVector):
newIndices = np.append(vec.indices, len(vec))
newValues = np.append(vec.values, 1.0)
return SparseVector(len(vec) + 1, newIndices, newValues)
else:
return _convert_to_vector(np.append(vec.toArray(), 1.0)) | [
"\n Returns a new vector with `1.0` (bias) appended to\n the end of the input vector.\n "
] |
Please provide a description of the function:def convertVectorColumnsToML(dataset, *cols):
if not isinstance(dataset, DataFrame):
raise TypeError("Input dataset must be a DataFrame but got {}.".format(type(dataset)))
return callMLlibFunc("convertVectorColumnsToML", dataset, list(cols)) | [
"\n Converts vector columns in an input DataFrame from the\n :py:class:`pyspark.mllib.linalg.Vector` type to the new\n :py:class:`pyspark.ml.linalg.Vector` type under the `spark.ml`\n package.\n\n :param dataset:\n input dataset\n :param cols:\n a list of vector columns to be converted.\n New vector columns will be ignored. If unspecified, all old\n vector columns will be converted excepted nested ones.\n :return:\n the input dataset with old vector columns converted to the\n new vector type\n\n >>> import pyspark\n >>> from pyspark.mllib.linalg import Vectors\n >>> from pyspark.mllib.util import MLUtils\n >>> df = spark.createDataFrame(\n ... [(0, Vectors.sparse(2, [1], [1.0]), Vectors.dense(2.0, 3.0))],\n ... [\"id\", \"x\", \"y\"])\n >>> r1 = MLUtils.convertVectorColumnsToML(df).first()\n >>> isinstance(r1.x, pyspark.ml.linalg.SparseVector)\n True\n >>> isinstance(r1.y, pyspark.ml.linalg.DenseVector)\n True\n >>> r2 = MLUtils.convertVectorColumnsToML(df, \"x\").first()\n >>> isinstance(r2.x, pyspark.ml.linalg.SparseVector)\n True\n >>> isinstance(r2.y, pyspark.mllib.linalg.DenseVector)\n True\n "
] |
Please provide a description of the function:def generateLinearInput(intercept, weights, xMean, xVariance,
nPoints, seed, eps):
weights = [float(weight) for weight in weights]
xMean = [float(mean) for mean in xMean]
xVariance = [float(var) for var in xVariance]
return list(callMLlibFunc(
"generateLinearInputWrapper", float(intercept), weights, xMean,
xVariance, int(nPoints), int(seed), float(eps))) | [
"\n :param: intercept bias factor, the term c in X'w + c\n :param: weights feature vector, the term w in X'w + c\n :param: xMean Point around which the data X is centered.\n :param: xVariance Variance of the given data\n :param: nPoints Number of points to be generated\n :param: seed Random Seed\n :param: eps Used to scale the noise. If eps is set high,\n the amount of gaussian noise added is more.\n\n Returns a list of LabeledPoints of length nPoints\n "
] |
Please provide a description of the function:def generateLinearRDD(sc, nexamples, nfeatures, eps,
nParts=2, intercept=0.0):
return callMLlibFunc(
"generateLinearRDDWrapper", sc, int(nexamples), int(nfeatures),
float(eps), int(nParts), float(intercept)) | [
"\n Generate an RDD of LabeledPoints.\n "
] |
Please provide a description of the function:def train(cls, data, iterations=100, step=1.0, miniBatchFraction=1.0,
initialWeights=None, regParam=0.0, regType=None, intercept=False,
validateData=True, convergenceTol=0.001):
warnings.warn(
"Deprecated in 2.0.0. Use ml.regression.LinearRegression.", DeprecationWarning)
def train(rdd, i):
return callMLlibFunc("trainLinearRegressionModelWithSGD", rdd, int(iterations),
float(step), float(miniBatchFraction), i, float(regParam),
regType, bool(intercept), bool(validateData),
float(convergenceTol))
return _regression_train_wrapper(train, LinearRegressionModel, data, initialWeights) | [
"\n Train a linear regression model using Stochastic Gradient\n Descent (SGD). This solves the least squares regression\n formulation\n\n f(weights) = 1/(2n) ||A weights - y||^2\n\n which is the mean squared error. Here the data matrix has n rows,\n and the input RDD holds the set of rows of A, each with its\n corresponding right hand side label y.\n See also the documentation for the precise formulation.\n\n :param data:\n The training data, an RDD of LabeledPoint.\n :param iterations:\n The number of iterations.\n (default: 100)\n :param step:\n The step parameter used in SGD.\n (default: 1.0)\n :param miniBatchFraction:\n Fraction of data to be used for each SGD iteration.\n (default: 1.0)\n :param initialWeights:\n The initial weights.\n (default: None)\n :param regParam:\n The regularizer parameter.\n (default: 0.0)\n :param regType:\n The type of regularizer used for training our model.\n Supported values:\n\n - \"l1\" for using L1 regularization\n - \"l2\" for using L2 regularization\n - None for no regularization (default)\n :param intercept:\n Boolean parameter which indicates the use or not of the\n augmented representation for training data (i.e., whether bias\n features are activated or not).\n (default: False)\n :param validateData:\n Boolean parameter which indicates if the algorithm should\n validate data before training.\n (default: True)\n :param convergenceTol:\n A condition which decides iteration termination.\n (default: 0.001)\n "
] |
Please provide a description of the function:def predict(self, x):
if isinstance(x, RDD):
return x.map(lambda v: self.predict(v))
return np.interp(x, self.boundaries, self.predictions) | [
"\n Predict labels for provided features.\n Using a piecewise linear function.\n 1) If x exactly matches a boundary then associated prediction\n is returned. In case there are multiple predictions with the\n same boundary then one of them is returned. Which one is\n undefined (same as java.util.Arrays.binarySearch).\n 2) If x is lower or higher than all boundaries then first or\n last prediction is returned respectively. In case there are\n multiple predictions with the same boundary then the lowest\n or highest is returned respectively.\n 3) If x falls between two values in boundary array then\n prediction is treated as piecewise linear function and\n interpolated value is returned. In case there are multiple\n values with the same boundary then the same rules as in 2)\n are used.\n\n :param x:\n Feature or RDD of Features to be labeled.\n "
] |
Please provide a description of the function:def save(self, sc, path):
java_boundaries = _py2java(sc, self.boundaries.tolist())
java_predictions = _py2java(sc, self.predictions.tolist())
java_model = sc._jvm.org.apache.spark.mllib.regression.IsotonicRegressionModel(
java_boundaries, java_predictions, self.isotonic)
java_model.save(sc._jsc.sc(), path) | [
"Save an IsotonicRegressionModel."
] |
Please provide a description of the function:def load(cls, sc, path):
java_model = sc._jvm.org.apache.spark.mllib.regression.IsotonicRegressionModel.load(
sc._jsc.sc(), path)
py_boundaries = _java2py(sc, java_model.boundaryVector()).toArray()
py_predictions = _java2py(sc, java_model.predictionVector()).toArray()
return IsotonicRegressionModel(py_boundaries, py_predictions, java_model.isotonic) | [
"Load an IsotonicRegressionModel."
] |
Please provide a description of the function:def train(cls, data, isotonic=True):
boundaries, predictions = callMLlibFunc("trainIsotonicRegressionModel",
data.map(_convert_to_vector), bool(isotonic))
return IsotonicRegressionModel(boundaries.toArray(), predictions.toArray(), isotonic) | [
"\n Train an isotonic regression model on the given data.\n\n :param data:\n RDD of (label, feature, weight) tuples.\n :param isotonic:\n Whether this is isotonic (which is default) or antitonic.\n (default: True)\n "
] |
Please provide a description of the function:def columnSimilarities(self, threshold=0.0):
java_sims_mat = self._java_matrix_wrapper.call("columnSimilarities", float(threshold))
return CoordinateMatrix(java_sims_mat) | [
"\n Compute similarities between columns of this matrix.\n\n The threshold parameter is a trade-off knob between estimate\n quality and computational cost.\n\n The default threshold setting of 0 guarantees deterministically\n correct results, but uses the brute-force approach of computing\n normalized dot products.\n\n Setting the threshold to positive values uses a sampling\n approach and incurs strictly less computational cost than the\n brute-force approach. However the similarities computed will\n be estimates.\n\n The sampling guarantees relative-error correctness for those\n pairs of columns that have similarity greater than the given\n similarity threshold.\n\n To describe the guarantee, we set some notation:\n * Let A be the smallest in magnitude non-zero element of\n this matrix.\n * Let B be the largest in magnitude non-zero element of\n this matrix.\n * Let L be the maximum number of non-zeros per row.\n\n For example, for {0,1} matrices: A=B=1.\n Another example, for the Netflix matrix: A=1, B=5\n\n For those column pairs that are above the threshold, the\n computed similarity is correct to within 20% relative error\n with probability at least 1 - (0.981)^10/B^\n\n The shuffle size is bounded by the *smaller* of the following\n two expressions:\n\n * O(n log(n) L / (threshold * A))\n * O(m L^2^)\n\n The latter is the cost of the brute-force approach, so for\n non-zero thresholds, the cost is always cheaper than the\n brute-force approach.\n\n :param: threshold: Set to 0 for deterministic guaranteed\n correctness. Similarities above this\n threshold are estimated with the cost vs\n estimate quality trade-off described above.\n :return: An n x n sparse upper-triangular CoordinateMatrix of\n cosine similarities between columns of this matrix.\n\n >>> rows = sc.parallelize([[1, 2], [1, 5]])\n >>> mat = RowMatrix(rows)\n\n >>> sims = mat.columnSimilarities()\n >>> sims.entries.first().value\n 0.91914503...\n "
] |
Please provide a description of the function:def tallSkinnyQR(self, computeQ=False):
decomp = JavaModelWrapper(self._java_matrix_wrapper.call("tallSkinnyQR", computeQ))
if computeQ:
java_Q = decomp.call("Q")
Q = RowMatrix(java_Q)
else:
Q = None
R = decomp.call("R")
return QRDecomposition(Q, R) | [
"\n Compute the QR decomposition of this RowMatrix.\n\n The implementation is designed to optimize the QR decomposition\n (factorization) for the RowMatrix of a tall and skinny shape.\n\n Reference:\n Paul G. Constantine, David F. Gleich. \"Tall and skinny QR\n factorizations in MapReduce architectures\"\n ([[https://doi.org/10.1145/1996092.1996103]])\n\n :param: computeQ: whether to computeQ\n :return: QRDecomposition(Q: RowMatrix, R: Matrix), where\n Q = None if computeQ = false.\n\n >>> rows = sc.parallelize([[3, -6], [4, -8], [0, 1]])\n >>> mat = RowMatrix(rows)\n >>> decomp = mat.tallSkinnyQR(True)\n >>> Q = decomp.Q\n >>> R = decomp.R\n\n >>> # Test with absolute values\n >>> absQRows = Q.rows.map(lambda row: abs(row.toArray()).tolist())\n >>> absQRows.collect()\n [[0.6..., 0.0], [0.8..., 0.0], [0.0, 1.0]]\n\n >>> # Test with absolute values\n >>> abs(R.toArray()).tolist()\n [[5.0, 10.0], [0.0, 1.0]]\n "
] |
Please provide a description of the function:def computeSVD(self, k, computeU=False, rCond=1e-9):
j_model = self._java_matrix_wrapper.call(
"computeSVD", int(k), bool(computeU), float(rCond))
return SingularValueDecomposition(j_model) | [
"\n Computes the singular value decomposition of the RowMatrix.\n\n The given row matrix A of dimension (m X n) is decomposed into\n U * s * V'T where\n\n * U: (m X k) (left singular vectors) is a RowMatrix whose\n columns are the eigenvectors of (A X A')\n * s: DenseVector consisting of square root of the eigenvalues\n (singular values) in descending order.\n * v: (n X k) (right singular vectors) is a Matrix whose columns\n are the eigenvectors of (A' X A)\n\n For more specific details on implementation, please refer\n the Scala documentation.\n\n :param k: Number of leading singular values to keep (`0 < k <= n`).\n It might return less than k if there are numerically zero singular values\n or there are not enough Ritz values converged before the maximum number of\n Arnoldi update iterations is reached (in case that matrix A is ill-conditioned).\n :param computeU: Whether or not to compute U. If set to be\n True, then U is computed by A * V * s^-1\n :param rCond: Reciprocal condition number. All singular values\n smaller than rCond * s[0] are treated as zero\n where s[0] is the largest singular value.\n :returns: :py:class:`SingularValueDecomposition`\n\n >>> rows = sc.parallelize([[3, 1, 1], [-1, 3, 1]])\n >>> rm = RowMatrix(rows)\n\n >>> svd_model = rm.computeSVD(2, True)\n >>> svd_model.U.rows.collect()\n [DenseVector([-0.7071, 0.7071]), DenseVector([-0.7071, -0.7071])]\n >>> svd_model.s\n DenseVector([3.4641, 3.1623])\n >>> svd_model.V\n DenseMatrix(3, 2, [-0.4082, -0.8165, -0.4082, 0.8944, -0.4472, 0.0], 0)\n "
] |
Please provide a description of the function:def multiply(self, matrix):
if not isinstance(matrix, DenseMatrix):
raise ValueError("Only multiplication with DenseMatrix "
"is supported.")
j_model = self._java_matrix_wrapper.call("multiply", matrix)
return RowMatrix(j_model) | [
"\n Multiply this matrix by a local dense matrix on the right.\n\n :param matrix: a local dense matrix whose number of rows must match the number of columns\n of this matrix\n :returns: :py:class:`RowMatrix`\n\n >>> rm = RowMatrix(sc.parallelize([[0, 1], [2, 3]]))\n >>> rm.multiply(DenseMatrix(2, 2, [0, 2, 1, 3])).rows.collect()\n [DenseVector([2.0, 3.0]), DenseVector([6.0, 11.0])]\n "
] |
Please provide a description of the function:def U(self):
u = self.call("U")
if u is not None:
mat_name = u.getClass().getSimpleName()
if mat_name == "RowMatrix":
return RowMatrix(u)
elif mat_name == "IndexedRowMatrix":
return IndexedRowMatrix(u)
else:
raise TypeError("Expected RowMatrix/IndexedRowMatrix got %s" % mat_name) | [
"\n Returns a distributed matrix whose columns are the left\n singular vectors of the SingularValueDecomposition if computeU was set to be True.\n "
] |
Please provide a description of the function:def rows(self):
# We use DataFrames for serialization of IndexedRows from
# Java, so we first convert the RDD of rows to a DataFrame
# on the Scala/Java side. Then we map each Row in the
# DataFrame back to an IndexedRow on this side.
rows_df = callMLlibFunc("getIndexedRows", self._java_matrix_wrapper._java_model)
rows = rows_df.rdd.map(lambda row: IndexedRow(row[0], row[1]))
return rows | [
"\n Rows of the IndexedRowMatrix stored as an RDD of IndexedRows.\n\n >>> mat = IndexedRowMatrix(sc.parallelize([IndexedRow(0, [1, 2, 3]),\n ... IndexedRow(1, [4, 5, 6])]))\n >>> rows = mat.rows\n >>> rows.first()\n IndexedRow(0, [1.0,2.0,3.0])\n "
] |
Please provide a description of the function:def toBlockMatrix(self, rowsPerBlock=1024, colsPerBlock=1024):
java_block_matrix = self._java_matrix_wrapper.call("toBlockMatrix",
rowsPerBlock,
colsPerBlock)
return BlockMatrix(java_block_matrix, rowsPerBlock, colsPerBlock) | [
"\n Convert this matrix to a BlockMatrix.\n\n :param rowsPerBlock: Number of rows that make up each block.\n The blocks forming the final rows are not\n required to have the given number of rows.\n :param colsPerBlock: Number of columns that make up each block.\n The blocks forming the final columns are not\n required to have the given number of columns.\n\n >>> rows = sc.parallelize([IndexedRow(0, [1, 2, 3]),\n ... IndexedRow(6, [4, 5, 6])])\n >>> mat = IndexedRowMatrix(rows).toBlockMatrix()\n\n >>> # This IndexedRowMatrix will have 7 effective rows, due to\n >>> # the highest row index being 6, and the ensuing\n >>> # BlockMatrix will have 7 rows as well.\n >>> print(mat.numRows())\n 7\n\n >>> print(mat.numCols())\n 3\n "
] |
Please provide a description of the function:def multiply(self, matrix):
if not isinstance(matrix, DenseMatrix):
raise ValueError("Only multiplication with DenseMatrix "
"is supported.")
return IndexedRowMatrix(self._java_matrix_wrapper.call("multiply", matrix)) | [
"\n Multiply this matrix by a local dense matrix on the right.\n\n :param matrix: a local dense matrix whose number of rows must match the number of columns\n of this matrix\n :returns: :py:class:`IndexedRowMatrix`\n\n >>> mat = IndexedRowMatrix(sc.parallelize([(0, (0, 1)), (1, (2, 3))]))\n >>> mat.multiply(DenseMatrix(2, 2, [0, 2, 1, 3])).rows.collect()\n [IndexedRow(0, [2.0,3.0]), IndexedRow(1, [6.0,11.0])]\n "
] |
Please provide a description of the function:def entries(self):
# We use DataFrames for serialization of MatrixEntry entries
# from Java, so we first convert the RDD of entries to a
# DataFrame on the Scala/Java side. Then we map each Row in
# the DataFrame back to a MatrixEntry on this side.
entries_df = callMLlibFunc("getMatrixEntries", self._java_matrix_wrapper._java_model)
entries = entries_df.rdd.map(lambda row: MatrixEntry(row[0], row[1], row[2]))
return entries | [
"\n Entries of the CoordinateMatrix stored as an RDD of\n MatrixEntries.\n\n >>> mat = CoordinateMatrix(sc.parallelize([MatrixEntry(0, 0, 1.2),\n ... MatrixEntry(6, 4, 2.1)]))\n >>> entries = mat.entries\n >>> entries.first()\n MatrixEntry(0, 0, 1.2)\n "
] |
Please provide a description of the function:def blocks(self):
# We use DataFrames for serialization of sub-matrix blocks
# from Java, so we first convert the RDD of blocks to a
# DataFrame on the Scala/Java side. Then we map each Row in
# the DataFrame back to a sub-matrix block on this side.
blocks_df = callMLlibFunc("getMatrixBlocks", self._java_matrix_wrapper._java_model)
blocks = blocks_df.rdd.map(lambda row: ((row[0][0], row[0][1]), row[1]))
return blocks | [
"\n The RDD of sub-matrix blocks\n ((blockRowIndex, blockColIndex), sub-matrix) that form this\n distributed matrix.\n\n >>> mat = BlockMatrix(\n ... sc.parallelize([((0, 0), Matrices.dense(3, 2, [1, 2, 3, 4, 5, 6])),\n ... ((1, 0), Matrices.dense(3, 2, [7, 8, 9, 10, 11, 12]))]), 3, 2)\n >>> blocks = mat.blocks\n >>> blocks.first()\n ((0, 0), DenseMatrix(3, 2, [1.0, 2.0, 3.0, 4.0, 5.0, 6.0], 0))\n\n "
] |
Please provide a description of the function:def persist(self, storageLevel):
if not isinstance(storageLevel, StorageLevel):
raise TypeError("`storageLevel` should be a StorageLevel, got %s" % type(storageLevel))
javaStorageLevel = self._java_matrix_wrapper._sc._getJavaStorageLevel(storageLevel)
self._java_matrix_wrapper.call("persist", javaStorageLevel)
return self | [
"\n Persists the underlying RDD with the specified storage level.\n "
] |
Please provide a description of the function:def add(self, other):
if not isinstance(other, BlockMatrix):
raise TypeError("Other should be a BlockMatrix, got %s" % type(other))
other_java_block_matrix = other._java_matrix_wrapper._java_model
java_block_matrix = self._java_matrix_wrapper.call("add", other_java_block_matrix)
return BlockMatrix(java_block_matrix, self.rowsPerBlock, self.colsPerBlock) | [
"\n Adds two block matrices together. The matrices must have the\n same size and matching `rowsPerBlock` and `colsPerBlock` values.\n If one of the sub matrix blocks that are being added is a\n SparseMatrix, the resulting sub matrix block will also be a\n SparseMatrix, even if it is being added to a DenseMatrix. If\n two dense sub matrix blocks are added, the output block will\n also be a DenseMatrix.\n\n >>> dm1 = Matrices.dense(3, 2, [1, 2, 3, 4, 5, 6])\n >>> dm2 = Matrices.dense(3, 2, [7, 8, 9, 10, 11, 12])\n >>> sm = Matrices.sparse(3, 2, [0, 1, 3], [0, 1, 2], [7, 11, 12])\n >>> blocks1 = sc.parallelize([((0, 0), dm1), ((1, 0), dm2)])\n >>> blocks2 = sc.parallelize([((0, 0), dm1), ((1, 0), dm2)])\n >>> blocks3 = sc.parallelize([((0, 0), sm), ((1, 0), dm2)])\n >>> mat1 = BlockMatrix(blocks1, 3, 2)\n >>> mat2 = BlockMatrix(blocks2, 3, 2)\n >>> mat3 = BlockMatrix(blocks3, 3, 2)\n\n >>> mat1.add(mat2).toLocalMatrix()\n DenseMatrix(6, 2, [2.0, 4.0, 6.0, 14.0, 16.0, 18.0, 8.0, 10.0, 12.0, 20.0, 22.0, 24.0], 0)\n\n >>> mat1.add(mat3).toLocalMatrix()\n DenseMatrix(6, 2, [8.0, 2.0, 3.0, 14.0, 16.0, 18.0, 4.0, 16.0, 18.0, 20.0, 22.0, 24.0], 0)\n "
] |
Please provide a description of the function:def transpose(self):
java_transposed_matrix = self._java_matrix_wrapper.call("transpose")
return BlockMatrix(java_transposed_matrix, self.colsPerBlock, self.rowsPerBlock) | [
"\n Transpose this BlockMatrix. Returns a new BlockMatrix\n instance sharing the same underlying data. Is a lazy operation.\n\n >>> blocks = sc.parallelize([((0, 0), Matrices.dense(3, 2, [1, 2, 3, 4, 5, 6])),\n ... ((1, 0), Matrices.dense(3, 2, [7, 8, 9, 10, 11, 12]))])\n >>> mat = BlockMatrix(blocks, 3, 2)\n\n >>> mat_transposed = mat.transpose()\n >>> mat_transposed.toLocalMatrix()\n DenseMatrix(2, 6, [1.0, 4.0, 2.0, 5.0, 3.0, 6.0, 7.0, 10.0, 8.0, 11.0, 9.0, 12.0], 0)\n "
] |
Please provide a description of the function:def _vector_size(v):
if isinstance(v, Vector):
return len(v)
elif type(v) in (array.array, list, tuple, xrange):
return len(v)
elif type(v) == np.ndarray:
if v.ndim == 1 or (v.ndim == 2 and v.shape[1] == 1):
return len(v)
else:
raise ValueError("Cannot treat an ndarray of shape %s as a vector" % str(v.shape))
elif _have_scipy and scipy.sparse.issparse(v):
assert v.shape[1] == 1, "Expected column vector"
return v.shape[0]
else:
raise TypeError("Cannot treat type %s as a vector" % type(v)) | [
"\n Returns the size of the vector.\n\n >>> _vector_size([1., 2., 3.])\n 3\n >>> _vector_size((1., 2., 3.))\n 3\n >>> _vector_size(array.array('d', [1., 2., 3.]))\n 3\n >>> _vector_size(np.zeros(3))\n 3\n >>> _vector_size(np.zeros((3, 1)))\n 3\n >>> _vector_size(np.zeros((1, 3)))\n Traceback (most recent call last):\n ...\n ValueError: Cannot treat an ndarray of shape (1, 3) as a vector\n "
] |
Please provide a description of the function:def parse(s):
start = s.find('[')
if start == -1:
raise ValueError("Array should start with '['.")
end = s.find(']')
if end == -1:
raise ValueError("Array should end with ']'.")
s = s[start + 1: end]
try:
values = [float(val) for val in s.split(',') if val]
except ValueError:
raise ValueError("Unable to parse values from %s" % s)
return DenseVector(values) | [
"\n Parse string representation back into the DenseVector.\n\n >>> DenseVector.parse(' [ 0.0,1.0,2.0, 3.0]')\n DenseVector([0.0, 1.0, 2.0, 3.0])\n "
] |
Please provide a description of the function:def dot(self, other):
if type(other) == np.ndarray:
if other.ndim > 1:
assert len(self) == other.shape[0], "dimension mismatch"
return np.dot(self.array, other)
elif _have_scipy and scipy.sparse.issparse(other):
assert len(self) == other.shape[0], "dimension mismatch"
return other.transpose().dot(self.toArray())
else:
assert len(self) == _vector_size(other), "dimension mismatch"
if isinstance(other, SparseVector):
return other.dot(self)
elif isinstance(other, Vector):
return np.dot(self.toArray(), other.toArray())
else:
return np.dot(self.toArray(), other) | [
"\n Compute the dot product of two Vectors. We support\n (Numpy array, list, SparseVector, or SciPy sparse)\n and a target NumPy array that is either 1- or 2-dimensional.\n Equivalent to calling numpy.dot of the two vectors.\n\n >>> dense = DenseVector(array.array('d', [1., 2.]))\n >>> dense.dot(dense)\n 5.0\n >>> dense.dot(SparseVector(2, [0, 1], [2., 1.]))\n 4.0\n >>> dense.dot(range(1, 3))\n 5.0\n >>> dense.dot(np.array(range(1, 3)))\n 5.0\n >>> dense.dot([1.,])\n Traceback (most recent call last):\n ...\n AssertionError: dimension mismatch\n >>> dense.dot(np.reshape([1., 2., 3., 4.], (2, 2), order='F'))\n array([ 5., 11.])\n >>> dense.dot(np.reshape([1., 2., 3.], (3, 1), order='F'))\n Traceback (most recent call last):\n ...\n AssertionError: dimension mismatch\n "
] |
Please provide a description of the function:def squared_distance(self, other):
assert len(self) == _vector_size(other), "dimension mismatch"
if isinstance(other, SparseVector):
return other.squared_distance(self)
elif _have_scipy and scipy.sparse.issparse(other):
return _convert_to_vector(other).squared_distance(self)
if isinstance(other, Vector):
other = other.toArray()
elif not isinstance(other, np.ndarray):
other = np.array(other)
diff = self.toArray() - other
return np.dot(diff, diff) | [
"\n Squared distance of two Vectors.\n\n >>> dense1 = DenseVector(array.array('d', [1., 2.]))\n >>> dense1.squared_distance(dense1)\n 0.0\n >>> dense2 = np.array([2., 1.])\n >>> dense1.squared_distance(dense2)\n 2.0\n >>> dense3 = [2., 1.]\n >>> dense1.squared_distance(dense3)\n 2.0\n >>> sparse1 = SparseVector(2, [0, 1], [2., 1.])\n >>> dense1.squared_distance(sparse1)\n 2.0\n >>> dense1.squared_distance([1.,])\n Traceback (most recent call last):\n ...\n AssertionError: dimension mismatch\n >>> dense1.squared_distance(SparseVector(1, [0,], [1.,]))\n Traceback (most recent call last):\n ...\n AssertionError: dimension mismatch\n "
] |
Please provide a description of the function:def parse(s):
start = s.find('(')
if start == -1:
raise ValueError("Tuple should start with '('")
end = s.find(')')
if end == -1:
raise ValueError("Tuple should end with ')'")
s = s[start + 1: end].strip()
size = s[: s.find(',')]
try:
size = int(size)
except ValueError:
raise ValueError("Cannot parse size %s." % size)
ind_start = s.find('[')
if ind_start == -1:
raise ValueError("Indices array should start with '['.")
ind_end = s.find(']')
if ind_end == -1:
raise ValueError("Indices array should end with ']'")
new_s = s[ind_start + 1: ind_end]
ind_list = new_s.split(',')
try:
indices = [int(ind) for ind in ind_list if ind]
except ValueError:
raise ValueError("Unable to parse indices from %s." % new_s)
s = s[ind_end + 1:].strip()
val_start = s.find('[')
if val_start == -1:
raise ValueError("Values array should start with '['.")
val_end = s.find(']')
if val_end == -1:
raise ValueError("Values array should end with ']'.")
val_list = s[val_start + 1: val_end].split(',')
try:
values = [float(val) for val in val_list if val]
except ValueError:
raise ValueError("Unable to parse values from %s." % s)
return SparseVector(size, indices, values) | [
"\n Parse string representation back into the SparseVector.\n\n >>> SparseVector.parse(' (4, [0,1 ],[ 4.0,5.0] )')\n SparseVector(4, {0: 4.0, 1: 5.0})\n "
] |
Please provide a description of the function:def dot(self, other):
if isinstance(other, np.ndarray):
if other.ndim not in [2, 1]:
raise ValueError("Cannot call dot with %d-dimensional array" % other.ndim)
assert len(self) == other.shape[0], "dimension mismatch"
return np.dot(self.values, other[self.indices])
assert len(self) == _vector_size(other), "dimension mismatch"
if isinstance(other, DenseVector):
return np.dot(other.array[self.indices], self.values)
elif isinstance(other, SparseVector):
# Find out common indices.
self_cmind = np.in1d(self.indices, other.indices, assume_unique=True)
self_values = self.values[self_cmind]
if self_values.size == 0:
return 0.0
else:
other_cmind = np.in1d(other.indices, self.indices, assume_unique=True)
return np.dot(self_values, other.values[other_cmind])
else:
return self.dot(_convert_to_vector(other)) | [
"\n Dot product with a SparseVector or 1- or 2-dimensional Numpy array.\n\n >>> a = SparseVector(4, [1, 3], [3.0, 4.0])\n >>> a.dot(a)\n 25.0\n >>> a.dot(array.array('d', [1., 2., 3., 4.]))\n 22.0\n >>> b = SparseVector(4, [2], [1.0])\n >>> a.dot(b)\n 0.0\n >>> a.dot(np.array([[1, 1], [2, 2], [3, 3], [4, 4]]))\n array([ 22., 22.])\n >>> a.dot([1., 2., 3.])\n Traceback (most recent call last):\n ...\n AssertionError: dimension mismatch\n >>> a.dot(np.array([1., 2.]))\n Traceback (most recent call last):\n ...\n AssertionError: dimension mismatch\n >>> a.dot(DenseVector([1., 2.]))\n Traceback (most recent call last):\n ...\n AssertionError: dimension mismatch\n >>> a.dot(np.zeros((3, 2)))\n Traceback (most recent call last):\n ...\n AssertionError: dimension mismatch\n "
] |
Please provide a description of the function:def squared_distance(self, other):
assert len(self) == _vector_size(other), "dimension mismatch"
if isinstance(other, np.ndarray) or isinstance(other, DenseVector):
if isinstance(other, np.ndarray) and other.ndim != 1:
raise Exception("Cannot call squared_distance with %d-dimensional array" %
other.ndim)
if isinstance(other, DenseVector):
other = other.array
sparse_ind = np.zeros(other.size, dtype=bool)
sparse_ind[self.indices] = True
dist = other[sparse_ind] - self.values
result = np.dot(dist, dist)
other_ind = other[~sparse_ind]
result += np.dot(other_ind, other_ind)
return result
elif isinstance(other, SparseVector):
result = 0.0
i, j = 0, 0
while i < len(self.indices) and j < len(other.indices):
if self.indices[i] == other.indices[j]:
diff = self.values[i] - other.values[j]
result += diff * diff
i += 1
j += 1
elif self.indices[i] < other.indices[j]:
result += self.values[i] * self.values[i]
i += 1
else:
result += other.values[j] * other.values[j]
j += 1
while i < len(self.indices):
result += self.values[i] * self.values[i]
i += 1
while j < len(other.indices):
result += other.values[j] * other.values[j]
j += 1
return result
else:
return self.squared_distance(_convert_to_vector(other)) | [
"\n Squared distance from a SparseVector or 1-dimensional NumPy array.\n\n >>> a = SparseVector(4, [1, 3], [3.0, 4.0])\n >>> a.squared_distance(a)\n 0.0\n >>> a.squared_distance(array.array('d', [1., 2., 3., 4.]))\n 11.0\n >>> a.squared_distance(np.array([1., 2., 3., 4.]))\n 11.0\n >>> b = SparseVector(4, [2], [1.0])\n >>> a.squared_distance(b)\n 26.0\n >>> b.squared_distance(a)\n 26.0\n >>> b.squared_distance([1., 2.])\n Traceback (most recent call last):\n ...\n AssertionError: dimension mismatch\n >>> b.squared_distance(SparseVector(3, [1,], [1.0,]))\n Traceback (most recent call last):\n ...\n AssertionError: dimension mismatch\n "
] |
Please provide a description of the function:def toArray(self):
arr = np.zeros((self.size,), dtype=np.float64)
arr[self.indices] = self.values
return arr | [
"\n Returns a copy of this SparseVector as a 1-dimensional NumPy array.\n "
] |
Please provide a description of the function:def asML(self):
return newlinalg.SparseVector(self.size, self.indices, self.values) | [
"\n Convert this vector to the new mllib-local representation.\n This does NOT copy the data; it copies references.\n\n :return: :py:class:`pyspark.ml.linalg.SparseVector`\n\n .. versionadded:: 2.0.0\n "
] |
Please provide a description of the function:def dense(*elements):
if len(elements) == 1 and not isinstance(elements[0], (float, int, long)):
# it's list, numpy.array or other iterable object.
elements = elements[0]
return DenseVector(elements) | [
"\n Create a dense vector of 64-bit floats from a Python list or numbers.\n\n >>> Vectors.dense([1, 2, 3])\n DenseVector([1.0, 2.0, 3.0])\n >>> Vectors.dense(1.0, 2.0)\n DenseVector([1.0, 2.0])\n "
] |
Please provide a description of the function:def fromML(vec):
if isinstance(vec, newlinalg.DenseVector):
return DenseVector(vec.array)
elif isinstance(vec, newlinalg.SparseVector):
return SparseVector(vec.size, vec.indices, vec.values)
else:
raise TypeError("Unsupported vector type %s" % type(vec)) | [
"\n Convert a vector from the new mllib-local representation.\n This does NOT copy the data; it copies references.\n\n :param vec: a :py:class:`pyspark.ml.linalg.Vector`\n :return: a :py:class:`pyspark.mllib.linalg.Vector`\n\n .. versionadded:: 2.0.0\n "
] |
Please provide a description of the function:def squared_distance(v1, v2):
v1, v2 = _convert_to_vector(v1), _convert_to_vector(v2)
return v1.squared_distance(v2) | [
"\n Squared distance between two vectors.\n a and b can be of type SparseVector, DenseVector, np.ndarray\n or array.array.\n\n >>> a = Vectors.sparse(4, [(0, 1), (3, 4)])\n >>> b = Vectors.dense([2, 5, 4, 1])\n >>> a.squared_distance(b)\n 51.0\n "
] |
Please provide a description of the function:def parse(s):
if s.find('(') == -1 and s.find('[') != -1:
return DenseVector.parse(s)
elif s.find('(') != -1:
return SparseVector.parse(s)
else:
raise ValueError(
"Cannot find tokens '[' or '(' from the input string.") | [
"Parse a string representation back into the Vector.\n\n >>> Vectors.parse('[2,1,2 ]')\n DenseVector([2.0, 1.0, 2.0])\n >>> Vectors.parse(' ( 100, [0], [2])')\n SparseVector(100, {0: 2.0})\n "
] |
Please provide a description of the function:def _equals(v1_indices, v1_values, v2_indices, v2_values):
v1_size = len(v1_values)
v2_size = len(v2_values)
k1 = 0
k2 = 0
all_equal = True
while all_equal:
while k1 < v1_size and v1_values[k1] == 0:
k1 += 1
while k2 < v2_size and v2_values[k2] == 0:
k2 += 1
if k1 >= v1_size or k2 >= v2_size:
return k1 >= v1_size and k2 >= v2_size
all_equal = v1_indices[k1] == v2_indices[k2] and v1_values[k1] == v2_values[k2]
k1 += 1
k2 += 1
return all_equal | [
"\n Check equality between sparse/dense vectors,\n v1_indices and v2_indices assume to be strictly increasing.\n "
] |
Please provide a description of the function:def _convert_to_array(array_like, dtype):
if isinstance(array_like, bytes):
return np.frombuffer(array_like, dtype=dtype)
return np.asarray(array_like, dtype=dtype) | [
"\n Convert Matrix attributes which are array-like or buffer to array.\n "
] |
Please provide a description of the function:def toArray(self):
if self.isTransposed:
return np.asfortranarray(
self.values.reshape((self.numRows, self.numCols)))
else:
return self.values.reshape((self.numRows, self.numCols), order='F') | [
"\n Return an numpy.ndarray\n\n >>> m = DenseMatrix(2, 2, range(4))\n >>> m.toArray()\n array([[ 0., 2.],\n [ 1., 3.]])\n "
] |
Please provide a description of the function:def toSparse(self):
if self.isTransposed:
values = np.ravel(self.toArray(), order='F')
else:
values = self.values
indices = np.nonzero(values)[0]
colCounts = np.bincount(indices // self.numRows)
colPtrs = np.cumsum(np.hstack(
(0, colCounts, np.zeros(self.numCols - colCounts.size))))
values = values[indices]
rowIndices = indices % self.numRows
return SparseMatrix(self.numRows, self.numCols, colPtrs, rowIndices, values) | [
"Convert to SparseMatrix"
] |
Please provide a description of the function:def asML(self):
return newlinalg.DenseMatrix(self.numRows, self.numCols, self.values, self.isTransposed) | [
"\n Convert this matrix to the new mllib-local representation.\n This does NOT copy the data; it copies references.\n\n :return: :py:class:`pyspark.ml.linalg.DenseMatrix`\n\n .. versionadded:: 2.0.0\n "
] |
Please provide a description of the function:def toArray(self):
A = np.zeros((self.numRows, self.numCols), dtype=np.float64, order='F')
for k in xrange(self.colPtrs.size - 1):
startptr = self.colPtrs[k]
endptr = self.colPtrs[k + 1]
if self.isTransposed:
A[k, self.rowIndices[startptr:endptr]] = self.values[startptr:endptr]
else:
A[self.rowIndices[startptr:endptr], k] = self.values[startptr:endptr]
return A | [
"\n Return an numpy.ndarray\n "
] |
Please provide a description of the function:def asML(self):
return newlinalg.SparseMatrix(self.numRows, self.numCols, self.colPtrs, self.rowIndices,
self.values, self.isTransposed) | [
"\n Convert this matrix to the new mllib-local representation.\n This does NOT copy the data; it copies references.\n\n :return: :py:class:`pyspark.ml.linalg.SparseMatrix`\n\n .. versionadded:: 2.0.0\n "
] |
Please provide a description of the function:def sparse(numRows, numCols, colPtrs, rowIndices, values):
return SparseMatrix(numRows, numCols, colPtrs, rowIndices, values) | [
"\n Create a SparseMatrix\n "
] |
Please provide a description of the function:def fromML(mat):
if isinstance(mat, newlinalg.DenseMatrix):
return DenseMatrix(mat.numRows, mat.numCols, mat.values, mat.isTransposed)
elif isinstance(mat, newlinalg.SparseMatrix):
return SparseMatrix(mat.numRows, mat.numCols, mat.colPtrs, mat.rowIndices,
mat.values, mat.isTransposed)
else:
raise TypeError("Unsupported matrix type %s" % type(mat)) | [
"\n Convert a matrix from the new mllib-local representation.\n This does NOT copy the data; it copies references.\n\n :param mat: a :py:class:`pyspark.ml.linalg.Matrix`\n :return: a :py:class:`pyspark.mllib.linalg.Matrix`\n\n .. versionadded:: 2.0.0\n "
] |
Please provide a description of the function:def approxNearestNeighbors(self, dataset, key, numNearestNeighbors, distCol="distCol"):
return self._call_java("approxNearestNeighbors", dataset, key, numNearestNeighbors,
distCol) | [
"\n Given a large dataset and an item, approximately find at most k items which have the\n closest distance to the item. If the :py:attr:`outputCol` is missing, the method will\n transform the data; if the :py:attr:`outputCol` exists, it will use that. This allows\n caching of the transformed data when necessary.\n\n .. note:: This method is experimental and will likely change behavior in the next release.\n\n :param dataset: The dataset to search for nearest neighbors of the key.\n :param key: Feature vector representing the item to search for.\n :param numNearestNeighbors: The maximum number of nearest neighbors.\n :param distCol: Output column for storing the distance between each result row and the key.\n Use \"distCol\" as default value if it's not specified.\n :return: A dataset containing at most k items closest to the key. A column \"distCol\" is\n added to show the distance between each row and the key.\n "
] |
Please provide a description of the function:def approxSimilarityJoin(self, datasetA, datasetB, threshold, distCol="distCol"):
threshold = TypeConverters.toFloat(threshold)
return self._call_java("approxSimilarityJoin", datasetA, datasetB, threshold, distCol) | [
"\n Join two datasets to approximately find all pairs of rows whose distance are smaller than\n the threshold. If the :py:attr:`outputCol` is missing, the method will transform the data;\n if the :py:attr:`outputCol` exists, it will use that. This allows caching of the\n transformed data when necessary.\n\n :param datasetA: One of the datasets to join.\n :param datasetB: Another dataset to join.\n :param threshold: The threshold for the distance of row pairs.\n :param distCol: Output column for storing the distance between each pair of rows. Use\n \"distCol\" as default value if it's not specified.\n :return: A joined dataset containing pairs of rows. The original rows are in columns\n \"datasetA\" and \"datasetB\", and a column \"distCol\" is added to show the distance\n between each pair.\n "
] |
Please provide a description of the function:def from_labels(cls, labels, inputCol, outputCol=None, handleInvalid=None):
sc = SparkContext._active_spark_context
java_class = sc._gateway.jvm.java.lang.String
jlabels = StringIndexerModel._new_java_array(labels, java_class)
model = StringIndexerModel._create_from_java_class(
"org.apache.spark.ml.feature.StringIndexerModel", jlabels)
model.setInputCol(inputCol)
if outputCol is not None:
model.setOutputCol(outputCol)
if handleInvalid is not None:
model.setHandleInvalid(handleInvalid)
return model | [
"\n Construct the model directly from an array of label strings,\n requires an active SparkContext.\n "
] |
Please provide a description of the function:def from_arrays_of_labels(cls, arrayOfLabels, inputCols, outputCols=None,
handleInvalid=None):
sc = SparkContext._active_spark_context
java_class = sc._gateway.jvm.java.lang.String
jlabels = StringIndexerModel._new_java_array(arrayOfLabels, java_class)
model = StringIndexerModel._create_from_java_class(
"org.apache.spark.ml.feature.StringIndexerModel", jlabels)
model.setInputCols(inputCols)
if outputCols is not None:
model.setOutputCols(outputCols)
if handleInvalid is not None:
model.setHandleInvalid(handleInvalid)
return model | [
"\n Construct the model directly from an array of array of label strings,\n requires an active SparkContext.\n "
] |
Please provide a description of the function:def setParams(self, inputCol=None, outputCol=None, stopWords=None, caseSensitive=False,
locale=None):
kwargs = self._input_kwargs
return self._set(**kwargs) | [
"\n setParams(self, inputCol=None, outputCol=None, stopWords=None, caseSensitive=false, \\\n locale=None)\n Sets params for this StopWordRemover.\n "
] |
Please provide a description of the function:def loadDefaultStopWords(language):
stopWordsObj = _jvm().org.apache.spark.ml.feature.StopWordsRemover
return list(stopWordsObj.loadDefaultStopWords(language)) | [
"\n Loads the default stop words for the given language.\n Supported languages: danish, dutch, english, finnish, french, german, hungarian,\n italian, norwegian, portuguese, russian, spanish, swedish, turkish\n "
] |
Please provide a description of the function:def findSynonyms(self, word, num):
if not isinstance(word, basestring):
word = _convert_to_vector(word)
return self._call_java("findSynonyms", word, num) | [
"\n Find \"num\" number of words closest in similarity to \"word\".\n word can be a string or vector representation.\n Returns a dataframe with two fields word and similarity (which\n gives the cosine similarity).\n "
] |
Please provide a description of the function:def findSynonymsArray(self, word, num):
if not isinstance(word, basestring):
word = _convert_to_vector(word)
tuples = self._java_obj.findSynonymsArray(word, num)
return list(map(lambda st: (st._1(), st._2()), list(tuples))) | [
"\n Find \"num\" number of words closest in similarity to \"word\".\n word can be a string or vector representation.\n Returns an array with two fields word and similarity (which\n gives the cosine similarity).\n "
] |
Please provide a description of the function:def install_exception_handler():
original = py4j.protocol.get_return_value
# The original `get_return_value` is not patched, it's idempotent.
patched = capture_sql_exception(original)
# only patch the one used in py4j.java_gateway (call Java API)
py4j.java_gateway.get_return_value = patched | [
"\n Hook an exception handler into Py4j, which could capture some SQL exceptions in Java.\n\n When calling Java API, it will call `get_return_value` to parse the returned object.\n If any exception happened in JVM, the result will be Java exception object, it raise\n py4j.protocol.Py4JJavaError. We replace the original `get_return_value` with one that\n could capture the Java exception and throw a Python one (with the same error message).\n\n It's idempotent, could be called multiple times.\n "
] |
Please provide a description of the function:def toJArray(gateway, jtype, arr):
jarr = gateway.new_array(jtype, len(arr))
for i in range(0, len(arr)):
jarr[i] = arr[i]
return jarr | [
"\n Convert python list to java type array\n :param gateway: Py4j Gateway\n :param jtype: java type of element in array\n :param arr: python type list\n "
] |
Please provide a description of the function:def require_minimum_pandas_version():
# TODO(HyukjinKwon): Relocate and deduplicate the version specification.
minimum_pandas_version = "0.19.2"
from distutils.version import LooseVersion
try:
import pandas
have_pandas = True
except ImportError:
have_pandas = False
if not have_pandas:
raise ImportError("Pandas >= %s must be installed; however, "
"it was not found." % minimum_pandas_version)
if LooseVersion(pandas.__version__) < LooseVersion(minimum_pandas_version):
raise ImportError("Pandas >= %s must be installed; however, "
"your version was %s." % (minimum_pandas_version, pandas.__version__)) | [
" Raise ImportError if minimum version of Pandas is not installed\n "
] |
Please provide a description of the function:def require_minimum_pyarrow_version():
# TODO(HyukjinKwon): Relocate and deduplicate the version specification.
minimum_pyarrow_version = "0.12.1"
from distutils.version import LooseVersion
try:
import pyarrow
have_arrow = True
except ImportError:
have_arrow = False
if not have_arrow:
raise ImportError("PyArrow >= %s must be installed; however, "
"it was not found." % minimum_pyarrow_version)
if LooseVersion(pyarrow.__version__) < LooseVersion(minimum_pyarrow_version):
raise ImportError("PyArrow >= %s must be installed; however, "
"your version was %s." % (minimum_pyarrow_version, pyarrow.__version__)) | [
" Raise ImportError if minimum version of pyarrow is not installed\n "
] |
Please provide a description of the function:def launch_gateway(conf=None, popen_kwargs=None):
if "PYSPARK_GATEWAY_PORT" in os.environ:
gateway_port = int(os.environ["PYSPARK_GATEWAY_PORT"])
gateway_secret = os.environ["PYSPARK_GATEWAY_SECRET"]
# Process already exists
proc = None
else:
SPARK_HOME = _find_spark_home()
# Launch the Py4j gateway using Spark's run command so that we pick up the
# proper classpath and settings from spark-env.sh
on_windows = platform.system() == "Windows"
script = "./bin/spark-submit.cmd" if on_windows else "./bin/spark-submit"
command = [os.path.join(SPARK_HOME, script)]
if conf:
for k, v in conf.getAll():
command += ['--conf', '%s=%s' % (k, v)]
submit_args = os.environ.get("PYSPARK_SUBMIT_ARGS", "pyspark-shell")
if os.environ.get("SPARK_TESTING"):
submit_args = ' '.join([
"--conf spark.ui.enabled=false",
submit_args
])
command = command + shlex.split(submit_args)
# Create a temporary directory where the gateway server should write the connection
# information.
conn_info_dir = tempfile.mkdtemp()
try:
fd, conn_info_file = tempfile.mkstemp(dir=conn_info_dir)
os.close(fd)
os.unlink(conn_info_file)
env = dict(os.environ)
env["_PYSPARK_DRIVER_CONN_INFO_PATH"] = conn_info_file
# Launch the Java gateway.
popen_kwargs = {} if popen_kwargs is None else popen_kwargs
# We open a pipe to stdin so that the Java gateway can die when the pipe is broken
popen_kwargs['stdin'] = PIPE
# We always set the necessary environment variables.
popen_kwargs['env'] = env
if not on_windows:
# Don't send ctrl-c / SIGINT to the Java gateway:
def preexec_func():
signal.signal(signal.SIGINT, signal.SIG_IGN)
popen_kwargs['preexec_fn'] = preexec_func
proc = Popen(command, **popen_kwargs)
else:
# preexec_fn not supported on Windows
proc = Popen(command, **popen_kwargs)
# Wait for the file to appear, or for the process to exit, whichever happens first.
while not proc.poll() and not os.path.isfile(conn_info_file):
time.sleep(0.1)
if not os.path.isfile(conn_info_file):
raise Exception("Java gateway process exited before sending its port number")
with open(conn_info_file, "rb") as info:
gateway_port = read_int(info)
gateway_secret = UTF8Deserializer().loads(info)
finally:
shutil.rmtree(conn_info_dir)
# In Windows, ensure the Java child processes do not linger after Python has exited.
# In UNIX-based systems, the child process can kill itself on broken pipe (i.e. when
# the parent process' stdin sends an EOF). In Windows, however, this is not possible
# because java.lang.Process reads directly from the parent process' stdin, contending
# with any opportunity to read an EOF from the parent. Note that this is only best
# effort and will not take effect if the python process is violently terminated.
if on_windows:
# In Windows, the child process here is "spark-submit.cmd", not the JVM itself
# (because the UNIX "exec" command is not available). This means we cannot simply
# call proc.kill(), which kills only the "spark-submit.cmd" process but not the
# JVMs. Instead, we use "taskkill" with the tree-kill option "/t" to terminate all
# child processes in the tree (http://technet.microsoft.com/en-us/library/bb491009.aspx)
def killChild():
Popen(["cmd", "/c", "taskkill", "/f", "/t", "/pid", str(proc.pid)])
atexit.register(killChild)
# Connect to the gateway
gateway = JavaGateway(
gateway_parameters=GatewayParameters(port=gateway_port, auth_token=gateway_secret,
auto_convert=True))
# Store a reference to the Popen object for use by the caller (e.g., in reading stdout/stderr)
gateway.proc = proc
# Import the classes used by PySpark
java_import(gateway.jvm, "org.apache.spark.SparkConf")
java_import(gateway.jvm, "org.apache.spark.api.java.*")
java_import(gateway.jvm, "org.apache.spark.api.python.*")
java_import(gateway.jvm, "org.apache.spark.ml.python.*")
java_import(gateway.jvm, "org.apache.spark.mllib.api.python.*")
# TODO(davies): move into sql
java_import(gateway.jvm, "org.apache.spark.sql.*")
java_import(gateway.jvm, "org.apache.spark.sql.api.python.*")
java_import(gateway.jvm, "org.apache.spark.sql.hive.*")
java_import(gateway.jvm, "scala.Tuple2")
return gateway | [
"\n launch jvm gateway\n :param conf: spark configuration passed to spark-submit\n :param popen_kwargs: Dictionary of kwargs to pass to Popen when spawning\n the py4j JVM. This is a developer feature intended for use in\n customizing how pyspark interacts with the py4j JVM (e.g., capturing\n stdout/stderr).\n :return:\n "
] |
Please provide a description of the function:def _do_server_auth(conn, auth_secret):
write_with_length(auth_secret.encode("utf-8"), conn)
conn.flush()
reply = UTF8Deserializer().loads(conn)
if reply != "ok":
conn.close()
raise Exception("Unexpected reply from iterator server.") | [
"\n Performs the authentication protocol defined by the SocketAuthHelper class on the given\n file-like object 'conn'.\n "
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.