INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Print the profile stats to stdout id is the RDD id | def show(self, id):
""" Print the profile stats to stdout, id is the RDD id """
stats = self.stats()
if stats:
print("=" * 60)
print("Profile of RDD<id=%d>" % id)
print("=" * 60)
stats.sort_stats("time", "cumulative").print_stats() |
Dump the profile into path id is the RDD id | def dump(self, id, path):
""" Dump the profile into path, id is the RDD id """
if not os.path.exists(path):
os.makedirs(path)
stats = self.stats()
if stats:
p = os.path.join(path, "rdd_%d.pstats" % id)
stats.dump_stats(p) |
Runs and profiles the method to_profile passed in. A profile object is returned. | def profile(self, func):
""" Runs and profiles the method to_profile passed in. A profile object is returned. """
pr = cProfile.Profile()
pr.runcall(func)
st = pstats.Stats(pr)
st.stream = None # make it picklable
st.strip_dirs()
# Adds a new profile to the exis... |
Get the existing SQLContext or create a new one with given SparkContext. | def getOrCreate(cls, sc):
"""
Get the existing SQLContext or create a new one with given SparkContext.
:param sc: SparkContext
"""
if cls._instantiatedContext is None:
jsqlContext = sc._jvm.SQLContext.getOrCreate(sc._jsc.sc())
sparkSession = SparkSession(... |
Sets the given Spark SQL configuration property. | def setConf(self, key, value):
"""Sets the given Spark SQL configuration property.
"""
self.sparkSession.conf.set(key, value) |
Returns the value of Spark SQL configuration property for the given key. | def getConf(self, key, defaultValue=_NoValue):
"""Returns the value of Spark SQL configuration property for the given key.
If the key is not set and defaultValue is set, return
defaultValue. If the key is not set and defaultValue is not set, return
the system default value.
>>>... |
Create a: class: DataFrame with single: class: pyspark. sql. types. LongType column named id containing elements in a range from start to end ( exclusive ) with step value step. | def range(self, start, end=None, step=1, numPartitions=None):
"""
Create a :class:`DataFrame` with single :class:`pyspark.sql.types.LongType` column named
``id``, containing elements in a range from ``start`` to ``end`` (exclusive) with
step value ``step``.
:param start: the sta... |
An alias for: func: spark. udf. register. See: meth: pyspark. sql. UDFRegistration. register. | def registerFunction(self, name, f, returnType=None):
"""An alias for :func:`spark.udf.register`.
See :meth:`pyspark.sql.UDFRegistration.register`.
.. note:: Deprecated in 2.3.0. Use :func:`spark.udf.register` instead.
"""
warnings.warn(
"Deprecated in 2.3.0. Use spa... |
An alias for: func: spark. udf. registerJavaFunction. See: meth: pyspark. sql. UDFRegistration. registerJavaFunction. | def registerJavaFunction(self, name, javaClassName, returnType=None):
"""An alias for :func:`spark.udf.registerJavaFunction`.
See :meth:`pyspark.sql.UDFRegistration.registerJavaFunction`.
.. note:: Deprecated in 2.3.0. Use :func:`spark.udf.registerJavaFunction` instead.
"""
warn... |
Creates a: class: DataFrame from an: class: RDD a list or a: class: pandas. DataFrame. | def createDataFrame(self, data, schema=None, samplingRatio=None, verifySchema=True):
"""
Creates a :class:`DataFrame` from an :class:`RDD`, a list or a :class:`pandas.DataFrame`.
When ``schema`` is a list of column names, the type of each column
will be inferred from ``data``.
... |
Creates an external table based on the dataset in a data source. | def createExternalTable(self, tableName, path=None, source=None, schema=None, **options):
"""Creates an external table based on the dataset in a data source.
It returns the DataFrame associated with the external table.
The data source is specified by the ``source`` and a set of ``options``.
... |
Returns a: class: DataFrame containing names of tables in the given database. | def tables(self, dbName=None):
"""Returns a :class:`DataFrame` containing names of tables in the given database.
If ``dbName`` is not specified, the current database will be used.
The returned DataFrame has two columns: ``tableName`` and ``isTemporary``
(a column with :class:`BooleanTy... |
Returns a list of names of tables in the database dbName. | def tableNames(self, dbName=None):
"""Returns a list of names of tables in the database ``dbName``.
:param dbName: string, name of the database to use. Default to the current database.
:return: list of table names, in string
>>> sqlContext.registerDataFrameAsTable(df, "table1")
... |
Returns a: class: StreamingQueryManager that allows managing all the: class: StreamingQuery StreamingQueries active on this context. | def streams(self):
"""Returns a :class:`StreamingQueryManager` that allows managing all the
:class:`StreamingQuery` StreamingQueries active on `this` context.
.. note:: Evolving.
"""
from pyspark.sql.streaming import StreamingQueryManager
return StreamingQueryManager(sel... |
Converts a binary column of avro format into its corresponding catalyst value. The specified schema must match the read data otherwise the behavior is undefined: it may fail or return arbitrary result. | def from_avro(data, jsonFormatSchema, options={}):
"""
Converts a binary column of avro format into its corresponding catalyst value. The specified
schema must match the read data, otherwise the behavior is undefined: it may fail or return
arbitrary result.
Note: Avro is built-in but external data ... |
Get the absolute path of a file added through C { SparkContext. addFile () }. | def get(cls, filename):
"""
Get the absolute path of a file added through C{SparkContext.addFile()}.
"""
path = os.path.join(SparkFiles.getRootDirectory(), filename)
return os.path.abspath(path) |
Get the root directory that contains files added through C { SparkContext. addFile () }. | def getRootDirectory(cls):
"""
Get the root directory that contains files added through
C{SparkContext.addFile()}.
"""
if cls._is_running_on_worker:
return cls._root_directory
else:
# This will have to change if we support multiple SparkContexts:
... |
Gets summary ( e. g. accuracy/ precision/ recall objective history total iterations ) of model trained on the training set. An exception is thrown if trainingSummary is None. | def summary(self):
"""
Gets summary (e.g. accuracy/precision/recall, objective history, total iterations) of model
trained on the training set. An exception is thrown if `trainingSummary is None`.
"""
if self.hasSummary:
if self.numClasses <= 2:
return... |
Evaluates the model on a test dataset. | def evaluate(self, dataset):
"""
Evaluates the model on a test dataset.
:param dataset:
Test dataset to evaluate model on, where dataset is an
instance of :py:class:`pyspark.sql.DataFrame`
"""
if not isinstance(dataset, DataFrame):
raise ValueErro... |
Creates a copy of this instance with a randomly generated uid and some extra params. This creates a deep copy of the embedded paramMap and copies the embedded and extra parameters over. | def copy(self, extra=None):
"""
Creates a copy of this instance with a randomly generated uid
and some extra params. This creates a deep copy of the embedded paramMap,
and copies the embedded and extra parameters over.
:param extra: Extra parameters to copy to the new instance
... |
Given a Java OneVsRestModel create and return a Python wrapper of it. Used for ML persistence. | def _from_java(cls, java_stage):
"""
Given a Java OneVsRestModel, create and return a Python wrapper of it.
Used for ML persistence.
"""
featuresCol = java_stage.getFeaturesCol()
labelCol = java_stage.getLabelCol()
predictionCol = java_stage.getPredictionCol()
... |
Transfer this instance to a Java OneVsRestModel. Used for ML persistence. | def _to_java(self):
"""
Transfer this instance to a Java OneVsRestModel. Used for ML persistence.
:return: Java object equivalent to this instance.
"""
sc = SparkContext._active_spark_context
java_models = [model._to_java() for model in self.models]
java_models_a... |
Return the message from an exception as either a str or unicode object. Supports both Python 2 and Python 3. | def _exception_message(excp):
"""Return the message from an exception as either a str or unicode object. Supports both
Python 2 and Python 3.
>>> msg = "Exception message"
>>> excp = Exception(msg)
>>> msg == _exception_message(excp)
True
>>> msg = u"unicöde"
>>> excp = Exception(msg)... |
Get argspec of a function. Supports both Python 2 and Python 3. | def _get_argspec(f):
"""
Get argspec of a function. Supports both Python 2 and Python 3.
"""
if sys.version_info[0] < 3:
argspec = inspect.getargspec(f)
else:
# `getargspec` is deprecated since python3.0 (incompatible with function annotations).
# See SPARK-23569.
arg... |
Wraps the input function to fail on StopIteration by raising a RuntimeError prevents silent loss of data when f is used in a for loop in Spark code | def fail_on_stopiteration(f):
"""
Wraps the input function to fail on 'StopIteration' by raising a 'RuntimeError'
prevents silent loss of data when 'f' is used in a for loop in Spark code
"""
def wrapper(*args, **kwargs):
try:
return f(*args, **kwargs)
except StopIteratio... |
Given a Spark version string return the ( major version number minor version number ). E. g. for 2. 0. 1 - SNAPSHOT return ( 2 0 ). | def majorMinorVersion(sparkVersion):
"""
Given a Spark version string, return the (major version number, minor version number).
E.g., for 2.0.1-SNAPSHOT, return (2, 0).
>>> sparkVersion = "2.4.0"
>>> VersionUtils.majorMinorVersion(sparkVersion)
(2, 4)
>>> sparkVe... |
Checks whether a SparkContext is initialized or not. Throws error if a SparkContext is already running. | def _ensure_initialized(cls, instance=None, gateway=None, conf=None):
"""
Checks whether a SparkContext is initialized or not.
Throws error if a SparkContext is already running.
"""
with SparkContext._lock:
if not SparkContext._gateway:
SparkContext._g... |
Get or instantiate a SparkContext and register it as a singleton object. | def getOrCreate(cls, conf=None):
"""
Get or instantiate a SparkContext and register it as a singleton object.
:param conf: SparkConf (optional)
"""
with SparkContext._lock:
if SparkContext._active_spark_context is None:
SparkContext(conf=conf or Spark... |
Set a Java system property such as spark. executor. memory. This must must be invoked before instantiating SparkContext. | def setSystemProperty(cls, key, value):
"""
Set a Java system property, such as spark.executor.memory. This must
must be invoked before instantiating SparkContext.
"""
SparkContext._ensure_initialized()
SparkContext._jvm.java.lang.System.setProperty(key, value) |
Shut down the SparkContext. | def stop(self):
"""
Shut down the SparkContext.
"""
if getattr(self, "_jsc", None):
try:
self._jsc.stop()
except Py4JError:
# Case: SPARK-18523
warnings.warn(
'Unable to cleanly shutdown Spark JVM... |
Create a new RDD of int containing elements from start to end ( exclusive ) increased by step every element. Can be called the same way as python s built - in range () function. If called with a single argument the argument is interpreted as end and start is set to 0. | def range(self, start, end=None, step=1, numSlices=None):
"""
Create a new RDD of int containing elements from `start` to `end`
(exclusive), increased by `step` every element. Can be called the same
way as python's built-in range() function. If called with a single argument,
the ... |
Distribute a local Python collection to form an RDD. Using xrange is recommended if the input represents a range for performance. | def parallelize(self, c, numSlices=None):
"""
Distribute a local Python collection to form an RDD. Using xrange
is recommended if the input represents a range for performance.
>>> sc.parallelize([0, 2, 3, 4, 6], 5).glom().collect()
[[0], [2], [3], [4], [6]]
>>> sc.parall... |
Using py4j to send a large dataset to the jvm is really slow so we use either a file or a socket if we have encryption enabled.: param data:: param serializer:: param reader_func: A function which takes a filename and reads in the data in the jvm and returns a JavaRDD. Only used when encryption is disabled.: param crea... | def _serialize_to_jvm(self, data, serializer, reader_func, createRDDServer):
"""
Using py4j to send a large dataset to the jvm is really slow, so we use either a file
or a socket if we have encryption enabled.
:param data:
:param serializer:
:param reader_func: A functio... |
Load an RDD previously saved using L { RDD. saveAsPickleFile } method. | def pickleFile(self, name, minPartitions=None):
"""
Load an RDD previously saved using L{RDD.saveAsPickleFile} method.
>>> tmpFile = NamedTemporaryFile(delete=True)
>>> tmpFile.close()
>>> sc.parallelize(range(10)).saveAsPickleFile(tmpFile.name, 5)
>>> sorted(sc.pickleFi... |
Read a text file from HDFS a local file system ( available on all nodes ) or any Hadoop - supported file system URI and return it as an RDD of Strings. The text files must be encoded as UTF - 8. | def textFile(self, name, minPartitions=None, use_unicode=True):
"""
Read a text file from HDFS, a local file system (available on all
nodes), or any Hadoop-supported file system URI, and return it as an
RDD of Strings.
The text files must be encoded as UTF-8.
If use_unic... |
Read a directory of text files from HDFS a local file system ( available on all nodes ) or any Hadoop - supported file system URI. Each file is read as a single record and returned in a key - value pair where the key is the path of each file the value is the content of each file. The text files must be encoded as UTF -... | def wholeTextFiles(self, path, minPartitions=None, use_unicode=True):
"""
Read a directory of text files from HDFS, a local file system
(available on all nodes), or any Hadoop-supported file system
URI. Each file is read as a single record and returned in a
key-value pair, where... |
.. note:: Experimental | def binaryFiles(self, path, minPartitions=None):
"""
.. note:: Experimental
Read a directory of binary files from HDFS, a local file system
(available on all nodes), or any Hadoop-supported file system URI
as a byte array. Each file is read as a single record and returned
... |
.. note:: Experimental | def binaryRecords(self, path, recordLength):
"""
.. note:: Experimental
Load data from a flat binary file, assuming each record is a set of numbers
with the specified numerical format (see ByteBuffer), and the number of
bytes per record is constant.
:param path: Directo... |
Read a Hadoop SequenceFile with arbitrary key and value Writable class from HDFS a local file system ( available on all nodes ) or any Hadoop - supported file system URI. The mechanism is as follows: | def sequenceFile(self, path, keyClass=None, valueClass=None, keyConverter=None,
valueConverter=None, minSplits=None, batchSize=0):
"""
Read a Hadoop SequenceFile with arbitrary key and value Writable class from HDFS,
a local file system (available on all nodes), or any Hadoo... |
Read a new API Hadoop InputFormat with arbitrary key and value class from HDFS a local file system ( available on all nodes ) or any Hadoop - supported file system URI. The mechanism is the same as for sc. sequenceFile. | def newAPIHadoopFile(self, path, inputFormatClass, keyClass, valueClass, keyConverter=None,
valueConverter=None, conf=None, batchSize=0):
"""
Read a 'new API' Hadoop InputFormat with arbitrary key and value class from HDFS,
a local file system (available on all nodes), o... |
Build the union of a list of RDDs. | def union(self, rdds):
"""
Build the union of a list of RDDs.
This supports unions() of RDDs with different serialized formats,
although this forces them to be reserialized using the default
serializer:
>>> path = os.path.join(tempdir, "union-text.txt")
>>> with... |
Create an L { Accumulator } with the given initial value using a given L { AccumulatorParam } helper object to define how to add values of the data type if provided. Default AccumulatorParams are used for integers and floating - point numbers if you do not provide one. For other types a custom AccumulatorParam can be u... | def accumulator(self, value, accum_param=None):
"""
Create an L{Accumulator} with the given initial value, using a given
L{AccumulatorParam} helper object to define how to add values of the
data type if provided. Default AccumulatorParams are used for integers
and floating-point ... |
Add a file to be downloaded with this Spark job on every node. The C { path } passed can be either a local file a file in HDFS ( or other Hadoop - supported filesystems ) or an HTTP HTTPS or FTP URI. | def addFile(self, path, recursive=False):
"""
Add a file to be downloaded with this Spark job on every node.
The C{path} passed can be either a local file, a file in HDFS
(or other Hadoop-supported filesystems), or an HTTP, HTTPS or
FTP URI.
To access the file in Spark j... |
Add a. py or. zip dependency for all tasks to be executed on this SparkContext in the future. The C { path } passed can be either a local file a file in HDFS ( or other Hadoop - supported filesystems ) or an HTTP HTTPS or FTP URI. | def addPyFile(self, path):
"""
Add a .py or .zip dependency for all tasks to be executed on this
SparkContext in the future. The C{path} passed can be either a local
file, a file in HDFS (or other Hadoop-supported filesystems), or an
HTTP, HTTPS or FTP URI.
.. note:: A ... |
Returns a Java StorageLevel based on a pyspark. StorageLevel. | def _getJavaStorageLevel(self, storageLevel):
"""
Returns a Java StorageLevel based on a pyspark.StorageLevel.
"""
if not isinstance(storageLevel, StorageLevel):
raise Exception("storageLevel must be of type pyspark.StorageLevel")
newStorageLevel = self._jvm.org.apac... |
Assigns a group ID to all the jobs started by this thread until the group ID is set to a different value or cleared. | def setJobGroup(self, groupId, description, interruptOnCancel=False):
"""
Assigns a group ID to all the jobs started by this thread until the group ID is set to a
different value or cleared.
Often, a unit of execution in an application consists of multiple Spark actions or jobs.
... |
Executes the given partitionFunc on the specified set of partitions returning the result as an array of elements. | def runJob(self, rdd, partitionFunc, partitions=None, allowLocal=False):
"""
Executes the given partitionFunc on the specified set of partitions,
returning the result as an array of elements.
If 'partitions' is not specified, this will run over all partitions.
>>> myRDD = sc.pa... |
Dump the profile stats into directory path | def dump_profiles(self, path):
""" Dump the profile stats into directory `path`
"""
if self.profiler_collector is not None:
self.profiler_collector.dump_profiles(path)
else:
raise RuntimeError("'spark.python.profile' configuration must be set "
... |
Train a matrix factorization model given an RDD of ratings by users for a subset of products. The ratings matrix is approximated as the product of two lower - rank matrices of a given rank ( number of features ). To solve for these features ALS is run iteratively with a configurable level of parallelism. | def train(cls, ratings, rank, iterations=5, lambda_=0.01, blocks=-1, nonnegative=False,
seed=None):
"""
Train a matrix factorization model given an RDD of ratings by users
for a subset of products. The ratings matrix is approximated as the
product of two lower-rank matrices... |
Computes an FP - Growth model that contains frequent itemsets. | def train(cls, data, minSupport=0.3, numPartitions=-1):
"""
Computes an FP-Growth model that contains frequent itemsets.
:param data:
The input data set, each element contains a transaction.
:param minSupport:
The minimal support level.
(default: 0.3)
... |
Finds the complete set of frequent sequential patterns in the input sequences of itemsets. | def train(cls, data, minSupport=0.1, maxPatternLength=10, maxLocalProjDBSize=32000000):
"""
Finds the complete set of frequent sequential patterns in the
input sequences of itemsets.
:param data:
The input data set, each element contains a sequence of
itemsets.
... |
Set sample points from the population. Should be a RDD | def setSample(self, sample):
"""Set sample points from the population. Should be a RDD"""
if not isinstance(sample, RDD):
raise TypeError("samples should be a RDD, received %s" % type(sample))
self._sample = sample |
Estimate the probability density at points | def estimate(self, points):
"""Estimate the probability density at points"""
points = list(points)
densities = callMLlibFunc(
"estimateKernelDensity", self._sample, self._bandwidth, points)
return np.asarray(densities) |
Start a TCP server to receive accumulator updates in a daemon thread and returns it | def _start_update_server(auth_token):
"""Start a TCP server to receive accumulator updates in a daemon thread, and returns it"""
server = AccumulatorServer(("localhost", 0), _UpdateRequestHandler, auth_token)
thread = threading.Thread(target=server.serve_forever)
thread.daemon = True
thread.start()
... |
Adds a term to this accumulator s value | def add(self, term):
"""Adds a term to this accumulator's value"""
self._value = self.accum_param.addInPlace(self._value, term) |
Compute aggregates and returns the result as a: class: DataFrame. | def agg(self, *exprs):
"""Compute aggregates and returns the result as a :class:`DataFrame`.
The available aggregate functions can be:
1. built-in aggregation functions, such as `avg`, `max`, `min`, `sum`, `count`
2. group aggregate pandas UDFs, created with :func:`pyspark.sql.functio... |
Pivots a column of the current: class: DataFrame and perform the specified aggregation. There are two versions of pivot function: one that requires the caller to specify the list of distinct values to pivot on and one that does not. The latter is more concise but less efficient because Spark needs to first compute the ... | def pivot(self, pivot_col, values=None):
"""
Pivots a column of the current :class:`DataFrame` and perform the specified aggregation.
There are two versions of pivot function: one that requires the caller to specify the list
of distinct values to pivot on, and one that does not. The latt... |
Maps each group of the current: class: DataFrame using a pandas udf and returns the result as a DataFrame. | def apply(self, udf):
"""
Maps each group of the current :class:`DataFrame` using a pandas udf and returns the result
as a `DataFrame`.
The user-defined function should take a `pandas.DataFrame` and return another
`pandas.DataFrame`. For each group, all columns are passed togeth... |
Creates a: class: WindowSpec with the partitioning defined. | def partitionBy(*cols):
"""
Creates a :class:`WindowSpec` with the partitioning defined.
"""
sc = SparkContext._active_spark_context
jspec = sc._jvm.org.apache.spark.sql.expressions.Window.partitionBy(_to_java_cols(cols))
return WindowSpec(jspec) |
Creates a: class: WindowSpec with the frame boundaries defined from start ( inclusive ) to end ( inclusive ). | def rowsBetween(start, end):
"""
Creates a :class:`WindowSpec` with the frame boundaries defined,
from `start` (inclusive) to `end` (inclusive).
Both `start` and `end` are relative positions from the current row.
For example, "0" means "current row", while "-1" means the row bef... |
Defines the frame boundaries from start ( inclusive ) to end ( inclusive ). | def rowsBetween(self, start, end):
"""
Defines the frame boundaries, from `start` (inclusive) to `end` (inclusive).
Both `start` and `end` are relative positions from the current row.
For example, "0" means "current row", while "-1" means the row before
the current row, and "5" ... |
Generates an RDD comprised of i. i. d. samples from the uniform distribution U ( 0. 0 1. 0 ). | def uniformRDD(sc, size, numPartitions=None, seed=None):
"""
Generates an RDD comprised of i.i.d. samples from the
uniform distribution U(0.0, 1.0).
To transform the distribution in the generated RDD from U(0.0, 1.0)
to U(a, b), use
C{RandomRDDs.uniformRDD(sc, n, p, seed... |
Generates an RDD comprised of i. i. d. samples from the standard normal distribution. | def normalRDD(sc, size, numPartitions=None, seed=None):
"""
Generates an RDD comprised of i.i.d. samples from the standard normal
distribution.
To transform the distribution in the generated RDD from standard normal
to some other normal N(mean, sigma^2), use
C{RandomRDDs... |
Generates an RDD comprised of i. i. d. samples from the log normal distribution with the input mean and standard distribution. | def logNormalRDD(sc, mean, std, size, numPartitions=None, seed=None):
"""
Generates an RDD comprised of i.i.d. samples from the log normal
distribution with the input mean and standard distribution.
:param sc: SparkContext used to create the RDD.
:param mean: mean for the log No... |
Generates an RDD comprised of i. i. d. samples from the Exponential distribution with the input mean. | def exponentialRDD(sc, mean, size, numPartitions=None, seed=None):
"""
Generates an RDD comprised of i.i.d. samples from the Exponential
distribution with the input mean.
:param sc: SparkContext used to create the RDD.
:param mean: Mean, or 1 / lambda, for the Exponential distri... |
Generates an RDD comprised of i. i. d. samples from the Gamma distribution with the input shape and scale. | def gammaRDD(sc, shape, scale, size, numPartitions=None, seed=None):
"""
Generates an RDD comprised of i.i.d. samples from the Gamma
distribution with the input shape and scale.
:param sc: SparkContext used to create the RDD.
:param shape: shape (> 0) parameter for the Gamma dis... |
Generates an RDD comprised of vectors containing i. i. d. samples drawn from the uniform distribution U ( 0. 0 1. 0 ). | def uniformVectorRDD(sc, numRows, numCols, numPartitions=None, seed=None):
"""
Generates an RDD comprised of vectors containing i.i.d. samples drawn
from the uniform distribution U(0.0, 1.0).
:param sc: SparkContext used to create the RDD.
:param numRows: Number of Vectors in th... |
Generates an RDD comprised of vectors containing i. i. d. samples drawn from the standard normal distribution. | def normalVectorRDD(sc, numRows, numCols, numPartitions=None, seed=None):
"""
Generates an RDD comprised of vectors containing i.i.d. samples drawn
from the standard normal distribution.
:param sc: SparkContext used to create the RDD.
:param numRows: Number of Vectors in the RDD... |
Generates an RDD comprised of vectors containing i. i. d. samples drawn from the log normal distribution. | def logNormalVectorRDD(sc, mean, std, numRows, numCols, numPartitions=None, seed=None):
"""
Generates an RDD comprised of vectors containing i.i.d. samples drawn
from the log normal distribution.
:param sc: SparkContext used to create the RDD.
:param mean: Mean of the log normal... |
Generates an RDD comprised of vectors containing i. i. d. samples drawn from the Poisson distribution with the input mean. | def poissonVectorRDD(sc, mean, numRows, numCols, numPartitions=None, seed=None):
"""
Generates an RDD comprised of vectors containing i.i.d. samples drawn
from the Poisson distribution with the input mean.
:param sc: SparkContext used to create the RDD.
:param mean: Mean, or lam... |
Generates an RDD comprised of vectors containing i. i. d. samples drawn from the Gamma distribution. | def gammaVectorRDD(sc, shape, scale, numRows, numCols, numPartitions=None, seed=None):
"""
Generates an RDD comprised of vectors containing i.i.d. samples drawn
from the Gamma distribution.
:param sc: SparkContext used to create the RDD.
:param shape: Shape (> 0) of the Gamma di... |
Returns the active SparkSession for the current thread returned by the builder. >>> s = SparkSession. getActiveSession () >>> l = [ ( Alice 1 ) ] >>> rdd = s. sparkContext. parallelize ( l ) >>> df = s. createDataFrame ( rdd [ name age ] ) >>> df. select ( age ). collect () [ Row ( age = 1 ) ] | def getActiveSession(cls):
"""
Returns the active SparkSession for the current thread, returned by the builder.
>>> s = SparkSession.getActiveSession()
>>> l = [('Alice', 1)]
>>> rdd = s.sparkContext.parallelize(l)
>>> df = s.createDataFrame(rdd, ['name', 'age'])
... |
Runtime configuration interface for Spark. | def conf(self):
"""Runtime configuration interface for Spark.
This is the interface through which the user can get and set all Spark and Hadoop
configurations that are relevant to Spark SQL. When getting the value of a config,
this defaults to the value set in the underlying :class:`Spa... |
Interface through which the user may create drop alter or query underlying databases tables functions etc. | def catalog(self):
"""Interface through which the user may create, drop, alter or query underlying
databases, tables, functions etc.
:return: :class:`Catalog`
"""
from pyspark.sql.catalog import Catalog
if not hasattr(self, "_catalog"):
self._catalog = Catalo... |
Create a: class: DataFrame with single: class: pyspark. sql. types. LongType column named id containing elements in a range from start to end ( exclusive ) with step value step. | def range(self, start, end=None, step=1, numPartitions=None):
"""
Create a :class:`DataFrame` with single :class:`pyspark.sql.types.LongType` column named
``id``, containing elements in a range from ``start`` to ``end`` (exclusive) with
step value ``step``.
:param start: the sta... |
Infer schema from list of Row or tuple. | def _inferSchemaFromList(self, data, names=None):
"""
Infer schema from list of Row or tuple.
:param data: list of Row or tuple
:param names: list of column names
:return: :class:`pyspark.sql.types.StructType`
"""
if not data:
raise ValueError("can no... |
Infer schema from an RDD of Row or tuple. | def _inferSchema(self, rdd, samplingRatio=None, names=None):
"""
Infer schema from an RDD of Row or tuple.
:param rdd: an RDD of Row or tuple
:param samplingRatio: sampling ratio, or no sampling (default)
:return: :class:`pyspark.sql.types.StructType`
"""
first =... |
Create an RDD for DataFrame from an existing RDD returns the RDD and schema. | def _createFromRDD(self, rdd, schema, samplingRatio):
"""
Create an RDD for DataFrame from an existing RDD, returns the RDD and schema.
"""
if schema is None or isinstance(schema, (list, tuple)):
struct = self._inferSchema(rdd, samplingRatio, names=schema)
convert... |
Create an RDD for DataFrame from a list or pandas. DataFrame returns the RDD and schema. | def _createFromLocal(self, data, schema):
"""
Create an RDD for DataFrame from a list or pandas.DataFrame, returns
the RDD and schema.
"""
# make sure data could consumed multiple times
if not isinstance(data, list):
data = list(data)
if schema is Non... |
Used when converting a pandas. DataFrame to Spark using to_records () this will correct the dtypes of fields in a record so they can be properly loaded into Spark.: param rec: a numpy record to check field dtypes: return corrected dtype for a numpy. record or None if no correction needed | def _get_numpy_record_dtype(self, rec):
"""
Used when converting a pandas.DataFrame to Spark using to_records(), this will correct
the dtypes of fields in a record so they can be properly loaded into Spark.
:param rec: a numpy record to check field dtypes
:return corrected dtype ... |
Convert a pandas. DataFrame to list of records that can be used to make a DataFrame: return list of records | def _convert_from_pandas(self, pdf, schema, timezone):
"""
Convert a pandas.DataFrame to list of records that can be used to make a DataFrame
:return list of records
"""
if timezone is not None:
from pyspark.sql.types import _check_series_convert_timestamps_tz_local... |
Create a DataFrame from a given pandas. DataFrame by slicing it into partitions converting to Arrow data then sending to the JVM to parallelize. If a schema is passed in the data types will be used to coerce the data in Pandas to Arrow conversion. | def _create_from_pandas_with_arrow(self, pdf, schema, timezone):
"""
Create a DataFrame from a given pandas.DataFrame by slicing it into partitions, converting
to Arrow data, then sending to the JVM to parallelize. If a schema is passed in, the
data types will be used to coerce the data ... |
Initialize a SparkSession for a pyspark shell session. This is called from shell. py to make error handling simpler without needing to declare local variables in that script which would expose those to users. | def _create_shell_session():
"""
Initialize a SparkSession for a pyspark shell session. This is called from shell.py
to make error handling simpler without needing to declare local variables in that
script, which would expose those to users.
"""
import py4j
from p... |
Creates a: class: DataFrame from an: class: RDD a list or a: class: pandas. DataFrame. | def createDataFrame(self, data, schema=None, samplingRatio=None, verifySchema=True):
"""
Creates a :class:`DataFrame` from an :class:`RDD`, a list or a :class:`pandas.DataFrame`.
When ``schema`` is a list of column names, the type of each column
will be inferred from ``data``.
... |
Returns a: class: DataFrame representing the result of the given query. | def sql(self, sqlQuery):
"""Returns a :class:`DataFrame` representing the result of the given query.
:return: :class:`DataFrame`
>>> df.createOrReplaceTempView("table1")
>>> df2 = spark.sql("SELECT field1 AS f1, field2 as f2 from table1")
>>> df2.collect()
[Row(f1=1, f2... |
Returns the specified table as a: class: DataFrame. | def table(self, tableName):
"""Returns the specified table as a :class:`DataFrame`.
:return: :class:`DataFrame`
>>> df.createOrReplaceTempView("table1")
>>> df2 = spark.table("table1")
>>> sorted(df.collect()) == sorted(df2.collect())
True
"""
return Dat... |
Returns a: class: StreamingQueryManager that allows managing all the: class: StreamingQuery StreamingQueries active on this context. | def streams(self):
"""Returns a :class:`StreamingQueryManager` that allows managing all the
:class:`StreamingQuery` StreamingQueries active on `this` context.
.. note:: Evolving.
:return: :class:`StreamingQueryManager`
"""
from pyspark.sql.streaming import StreamingQuer... |
Stop the underlying: class: SparkContext. | def stop(self):
"""Stop the underlying :class:`SparkContext`.
"""
self._sc.stop()
# We should clean the default session up. See SPARK-23228.
self._jvm.SparkSession.clearDefaultSession()
self._jvm.SparkSession.clearActiveSession()
SparkSession._instantiatedSession ... |
Returns a: class: SparkJobInfo object or None if the job info could not be found or was garbage collected. | def getJobInfo(self, jobId):
"""
Returns a :class:`SparkJobInfo` object, or None if the job info
could not be found or was garbage collected.
"""
job = self._jtracker.getJobInfo(jobId)
if job is not None:
return SparkJobInfo(jobId, job.stageIds(), str(job.stat... |
Returns a: class: SparkStageInfo object or None if the stage info could not be found or was garbage collected. | def getStageInfo(self, stageId):
"""
Returns a :class:`SparkStageInfo` object, or None if the stage
info could not be found or was garbage collected.
"""
stage = self._jtracker.getStageInfo(stageId)
if stage is not None:
# TODO: fetch them in batch for better ... |
Restore an object of namedtuple | def _restore(name, fields, value):
""" Restore an object of namedtuple"""
k = (name, fields)
cls = __cls.get(k)
if cls is None:
cls = collections.namedtuple(name, fields)
__cls[k] = cls
return cls(*value) |
Make class generated by namedtuple picklable | def _hack_namedtuple(cls):
""" Make class generated by namedtuple picklable """
name = cls.__name__
fields = cls._fields
def __reduce__(self):
return (_restore, (name, fields, tuple(self)))
cls.__reduce__ = __reduce__
cls._is_namedtuple_ = True
return cls |
Hack namedtuple () to make it picklable | def _hijack_namedtuple():
""" Hack namedtuple() to make it picklable """
# hijack only one time
if hasattr(collections.namedtuple, "__hijack"):
return
global _old_namedtuple # or it will put in closure
global _old_namedtuple_kwdefaults # or it will put in closure too
def _copy_func(f... |
Load a stream of un - ordered Arrow RecordBatches where the last iteration yields a list of indices that can be used to put the RecordBatches in the correct order. | def load_stream(self, stream):
"""
Load a stream of un-ordered Arrow RecordBatches, where the last iteration yields
a list of indices that can be used to put the RecordBatches in the correct order.
"""
# load the batches
for batch in self.serializer.load_stream(stream):
... |
Create an Arrow record batch from the given pandas. Series or list of Series with optional type. | def _create_batch(self, series):
"""
Create an Arrow record batch from the given pandas.Series or list of Series,
with optional type.
:param series: A single pandas.Series, list of Series, or list of (series, arrow_type)
:return: Arrow RecordBatch
"""
import pand... |
Make ArrowRecordBatches from Pandas Series and serialize. Input is a single series or a list of series accompanied by an optional pyarrow type to coerce the data to. | def dump_stream(self, iterator, stream):
"""
Make ArrowRecordBatches from Pandas Series and serialize. Input is a single series or
a list of series accompanied by an optional pyarrow type to coerce the data to.
"""
batches = (self._create_batch(series) for series in iterator)
... |
Deserialize ArrowRecordBatches to an Arrow table and return as a list of pandas. Series. | def load_stream(self, stream):
"""
Deserialize ArrowRecordBatches to an Arrow table and return as a list of pandas.Series.
"""
batches = super(ArrowStreamPandasSerializer, self).load_stream(stream)
import pyarrow as pa
for batch in batches:
yield [self.arrow_t... |
Override because Pandas UDFs require a START_ARROW_STREAM before the Arrow stream is sent. This should be sent after creating the first record batch so in case of an error it can be sent back to the JVM before the Arrow stream starts. | def dump_stream(self, iterator, stream):
"""
Override because Pandas UDFs require a START_ARROW_STREAM before the Arrow stream is sent.
This should be sent after creating the first record batch so in case of an error, it can
be sent back to the JVM before the Arrow stream starts.
... |
Waits for the termination of this query either by: func: query. stop () or by an exception. If the query has terminated with an exception then the exception will be thrown. If timeout is set it returns whether the query has terminated or not within the timeout seconds. | def awaitTermination(self, timeout=None):
"""Waits for the termination of `this` query, either by :func:`query.stop()` or by an
exception. If the query has terminated with an exception, then the exception will be thrown.
If `timeout` is set, it returns whether the query has terminated or not wit... |
Returns an array of the most recent [[ StreamingQueryProgress ]] updates for this query. The number of progress updates retained for each stream is configured by Spark session configuration spark. sql. streaming. numRecentProgressUpdates. | def recentProgress(self):
"""Returns an array of the most recent [[StreamingQueryProgress]] updates for this query.
The number of progress updates retained for each stream is configured by Spark session
configuration `spark.sql.streaming.numRecentProgressUpdates`.
"""
return [jso... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.