repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
129
original_string
stringlengths
234
21.9k
language
stringclasses
1 value
code
stringlengths
234
21.9k
code_tokens
listlengths
20
10.3k
docstring
stringlengths
1
11.2k
docstring_tokens
listlengths
1
725
sha
stringlengths
40
40
url
stringlengths
88
315
partition
stringclasses
3 values
summary
stringlengths
5
350
ageitgey/face_recognition
examples/face_recognition_knn.py
train
def train(train_dir, model_save_path=None, n_neighbors=None, knn_algo='ball_tree', verbose=False): """ Trains a k-nearest neighbors classifier for face recognition. :param train_dir: directory that contains a sub-directory for each known person, with its name. (View in source code to see train_dir ex...
python
def train(train_dir, model_save_path=None, n_neighbors=None, knn_algo='ball_tree', verbose=False): """ Trains a k-nearest neighbors classifier for face recognition. :param train_dir: directory that contains a sub-directory for each known person, with its name. (View in source code to see train_dir ex...
[ "def", "train", "(", "train_dir", ",", "model_save_path", "=", "None", ",", "n_neighbors", "=", "None", ",", "knn_algo", "=", "'ball_tree'", ",", "verbose", "=", "False", ")", ":", "X", "=", "[", "]", "y", "=", "[", "]", "# Loop through each person in the ...
Trains a k-nearest neighbors classifier for face recognition. :param train_dir: directory that contains a sub-directory for each known person, with its name. (View in source code to see train_dir example tree structure) Structure: <train_dir>/ β”œβ”€β”€ <person1>/ β”‚ β”œβ”€β”€ <somename1>....
[ "Trains", "a", "k", "-", "nearest", "neighbors", "classifier", "for", "face", "recognition", "." ]
c96b010c02f15e8eeb0f71308c641179ac1f19bb
https://github.com/ageitgey/face_recognition/blob/c96b010c02f15e8eeb0f71308c641179ac1f19bb/examples/face_recognition_knn.py#L46-L108
train
Train a k - nearest neighbors classifier for face recognition.
ageitgey/face_recognition
examples/face_recognition_knn.py
predict
def predict(X_img_path, knn_clf=None, model_path=None, distance_threshold=0.6): """ Recognizes faces in given image using a trained KNN classifier :param X_img_path: path to image to be recognized :param knn_clf: (optional) a knn classifier object. if not specified, model_save_path must be specified. ...
python
def predict(X_img_path, knn_clf=None, model_path=None, distance_threshold=0.6): """ Recognizes faces in given image using a trained KNN classifier :param X_img_path: path to image to be recognized :param knn_clf: (optional) a knn classifier object. if not specified, model_save_path must be specified. ...
[ "def", "predict", "(", "X_img_path", ",", "knn_clf", "=", "None", ",", "model_path", "=", "None", ",", "distance_threshold", "=", "0.6", ")", ":", "if", "not", "os", ".", "path", ".", "isfile", "(", "X_img_path", ")", "or", "os", ".", "path", ".", "s...
Recognizes faces in given image using a trained KNN classifier :param X_img_path: path to image to be recognized :param knn_clf: (optional) a knn classifier object. if not specified, model_save_path must be specified. :param model_path: (optional) path to a pickled knn classifier. if not specified, model_s...
[ "Recognizes", "faces", "in", "given", "image", "using", "a", "trained", "KNN", "classifier" ]
c96b010c02f15e8eeb0f71308c641179ac1f19bb
https://github.com/ageitgey/face_recognition/blob/c96b010c02f15e8eeb0f71308c641179ac1f19bb/examples/face_recognition_knn.py#L111-L150
train
Predicts faces in a given image using a KNN classifier.
ageitgey/face_recognition
examples/face_recognition_knn.py
show_prediction_labels_on_image
def show_prediction_labels_on_image(img_path, predictions): """ Shows the face recognition results visually. :param img_path: path to image to be recognized :param predictions: results of the predict function :return: """ pil_image = Image.open(img_path).convert("RGB") draw = ImageDraw....
python
def show_prediction_labels_on_image(img_path, predictions): """ Shows the face recognition results visually. :param img_path: path to image to be recognized :param predictions: results of the predict function :return: """ pil_image = Image.open(img_path).convert("RGB") draw = ImageDraw....
[ "def", "show_prediction_labels_on_image", "(", "img_path", ",", "predictions", ")", ":", "pil_image", "=", "Image", ".", "open", "(", "img_path", ")", ".", "convert", "(", "\"RGB\"", ")", "draw", "=", "ImageDraw", ".", "Draw", "(", "pil_image", ")", "for", ...
Shows the face recognition results visually. :param img_path: path to image to be recognized :param predictions: results of the predict function :return:
[ "Shows", "the", "face", "recognition", "results", "visually", "." ]
c96b010c02f15e8eeb0f71308c641179ac1f19bb
https://github.com/ageitgey/face_recognition/blob/c96b010c02f15e8eeb0f71308c641179ac1f19bb/examples/face_recognition_knn.py#L153-L181
train
Show the face recognition results visually.
ageitgey/face_recognition
face_recognition/api.py
_trim_css_to_bounds
def _trim_css_to_bounds(css, image_shape): """ Make sure a tuple in (top, right, bottom, left) order is within the bounds of the image. :param css: plain tuple representation of the rect in (top, right, bottom, left) order :param image_shape: numpy shape of the image array :return: a trimmed plain...
python
def _trim_css_to_bounds(css, image_shape): """ Make sure a tuple in (top, right, bottom, left) order is within the bounds of the image. :param css: plain tuple representation of the rect in (top, right, bottom, left) order :param image_shape: numpy shape of the image array :return: a trimmed plain...
[ "def", "_trim_css_to_bounds", "(", "css", ",", "image_shape", ")", ":", "return", "max", "(", "css", "[", "0", "]", ",", "0", ")", ",", "min", "(", "css", "[", "1", "]", ",", "image_shape", "[", "1", "]", ")", ",", "min", "(", "css", "[", "2", ...
Make sure a tuple in (top, right, bottom, left) order is within the bounds of the image. :param css: plain tuple representation of the rect in (top, right, bottom, left) order :param image_shape: numpy shape of the image array :return: a trimmed plain tuple representation of the rect in (top, right, botto...
[ "Make", "sure", "a", "tuple", "in", "(", "top", "right", "bottom", "left", ")", "order", "is", "within", "the", "bounds", "of", "the", "image", "." ]
c96b010c02f15e8eeb0f71308c641179ac1f19bb
https://github.com/ageitgey/face_recognition/blob/c96b010c02f15e8eeb0f71308c641179ac1f19bb/face_recognition/api.py#L52-L60
train
Trim the given CSS tuple to the bounds of the image.
ageitgey/face_recognition
face_recognition/api.py
face_distance
def face_distance(face_encodings, face_to_compare): """ Given a list of face encodings, compare them to a known face encoding and get a euclidean distance for each comparison face. The distance tells you how similar the faces are. :param faces: List of face encodings to compare :param face_to_compa...
python
def face_distance(face_encodings, face_to_compare): """ Given a list of face encodings, compare them to a known face encoding and get a euclidean distance for each comparison face. The distance tells you how similar the faces are. :param faces: List of face encodings to compare :param face_to_compa...
[ "def", "face_distance", "(", "face_encodings", ",", "face_to_compare", ")", ":", "if", "len", "(", "face_encodings", ")", "==", "0", ":", "return", "np", ".", "empty", "(", "(", "0", ")", ")", "return", "np", ".", "linalg", ".", "norm", "(", "face_enco...
Given a list of face encodings, compare them to a known face encoding and get a euclidean distance for each comparison face. The distance tells you how similar the faces are. :param faces: List of face encodings to compare :param face_to_compare: A face encoding to compare against :return: A numpy ndar...
[ "Given", "a", "list", "of", "face", "encodings", "compare", "them", "to", "a", "known", "face", "encoding", "and", "get", "a", "euclidean", "distance", "for", "each", "comparison", "face", ".", "The", "distance", "tells", "you", "how", "similar", "the", "f...
c96b010c02f15e8eeb0f71308c641179ac1f19bb
https://github.com/ageitgey/face_recognition/blob/c96b010c02f15e8eeb0f71308c641179ac1f19bb/face_recognition/api.py#L63-L75
train
Given a list of face encodings compare them to a known face encoding and get a euclidean distance for each comparison face.
ageitgey/face_recognition
face_recognition/api.py
load_image_file
def load_image_file(file, mode='RGB'): """ Loads an image file (.jpg, .png, etc) into a numpy array :param file: image file name or file object to load :param mode: format to convert the image to. Only 'RGB' (8-bit RGB, 3 channels) and 'L' (black and white) are supported. :return: image contents as...
python
def load_image_file(file, mode='RGB'): """ Loads an image file (.jpg, .png, etc) into a numpy array :param file: image file name or file object to load :param mode: format to convert the image to. Only 'RGB' (8-bit RGB, 3 channels) and 'L' (black and white) are supported. :return: image contents as...
[ "def", "load_image_file", "(", "file", ",", "mode", "=", "'RGB'", ")", ":", "im", "=", "PIL", ".", "Image", ".", "open", "(", "file", ")", "if", "mode", ":", "im", "=", "im", ".", "convert", "(", "mode", ")", "return", "np", ".", "array", "(", ...
Loads an image file (.jpg, .png, etc) into a numpy array :param file: image file name or file object to load :param mode: format to convert the image to. Only 'RGB' (8-bit RGB, 3 channels) and 'L' (black and white) are supported. :return: image contents as numpy array
[ "Loads", "an", "image", "file", "(", ".", "jpg", ".", "png", "etc", ")", "into", "a", "numpy", "array" ]
c96b010c02f15e8eeb0f71308c641179ac1f19bb
https://github.com/ageitgey/face_recognition/blob/c96b010c02f15e8eeb0f71308c641179ac1f19bb/face_recognition/api.py#L78-L89
train
Loads an image file into a numpy array.
ageitgey/face_recognition
face_recognition/api.py
_raw_face_locations
def _raw_face_locations(img, number_of_times_to_upsample=1, model="hog"): """ Returns an array of bounding boxes of human faces in a image :param img: An image (as a numpy array) :param number_of_times_to_upsample: How many times to upsample the image looking for faces. Higher numbers find smaller face...
python
def _raw_face_locations(img, number_of_times_to_upsample=1, model="hog"): """ Returns an array of bounding boxes of human faces in a image :param img: An image (as a numpy array) :param number_of_times_to_upsample: How many times to upsample the image looking for faces. Higher numbers find smaller face...
[ "def", "_raw_face_locations", "(", "img", ",", "number_of_times_to_upsample", "=", "1", ",", "model", "=", "\"hog\"", ")", ":", "if", "model", "==", "\"cnn\"", ":", "return", "cnn_face_detector", "(", "img", ",", "number_of_times_to_upsample", ")", "else", ":", ...
Returns an array of bounding boxes of human faces in a image :param img: An image (as a numpy array) :param number_of_times_to_upsample: How many times to upsample the image looking for faces. Higher numbers find smaller faces. :param model: Which face detection model to use. "hog" is less accurate but fas...
[ "Returns", "an", "array", "of", "bounding", "boxes", "of", "human", "faces", "in", "a", "image" ]
c96b010c02f15e8eeb0f71308c641179ac1f19bb
https://github.com/ageitgey/face_recognition/blob/c96b010c02f15e8eeb0f71308c641179ac1f19bb/face_recognition/api.py#L92-L105
train
Returns an array of bounding boxes of human faces in a image.
ageitgey/face_recognition
face_recognition/api.py
face_locations
def face_locations(img, number_of_times_to_upsample=1, model="hog"): """ Returns an array of bounding boxes of human faces in a image :param img: An image (as a numpy array) :param number_of_times_to_upsample: How many times to upsample the image looking for faces. Higher numbers find smaller faces. ...
python
def face_locations(img, number_of_times_to_upsample=1, model="hog"): """ Returns an array of bounding boxes of human faces in a image :param img: An image (as a numpy array) :param number_of_times_to_upsample: How many times to upsample the image looking for faces. Higher numbers find smaller faces. ...
[ "def", "face_locations", "(", "img", ",", "number_of_times_to_upsample", "=", "1", ",", "model", "=", "\"hog\"", ")", ":", "if", "model", "==", "\"cnn\"", ":", "return", "[", "_trim_css_to_bounds", "(", "_rect_to_css", "(", "face", ".", "rect", ")", ",", "...
Returns an array of bounding boxes of human faces in a image :param img: An image (as a numpy array) :param number_of_times_to_upsample: How many times to upsample the image looking for faces. Higher numbers find smaller faces. :param model: Which face detection model to use. "hog" is less accurate but fas...
[ "Returns", "an", "array", "of", "bounding", "boxes", "of", "human", "faces", "in", "a", "image" ]
c96b010c02f15e8eeb0f71308c641179ac1f19bb
https://github.com/ageitgey/face_recognition/blob/c96b010c02f15e8eeb0f71308c641179ac1f19bb/face_recognition/api.py#L108-L121
train
Returns an array of bounding boxes of human faces in a image.
ageitgey/face_recognition
face_recognition/api.py
batch_face_locations
def batch_face_locations(images, number_of_times_to_upsample=1, batch_size=128): """ Returns an 2d array of bounding boxes of human faces in a image using the cnn face detector If you are using a GPU, this can give you much faster results since the GPU can process batches of images at once. If you aren'...
python
def batch_face_locations(images, number_of_times_to_upsample=1, batch_size=128): """ Returns an 2d array of bounding boxes of human faces in a image using the cnn face detector If you are using a GPU, this can give you much faster results since the GPU can process batches of images at once. If you aren'...
[ "def", "batch_face_locations", "(", "images", ",", "number_of_times_to_upsample", "=", "1", ",", "batch_size", "=", "128", ")", ":", "def", "convert_cnn_detections_to_css", "(", "detections", ")", ":", "return", "[", "_trim_css_to_bounds", "(", "_rect_to_css", "(", ...
Returns an 2d array of bounding boxes of human faces in a image using the cnn face detector If you are using a GPU, this can give you much faster results since the GPU can process batches of images at once. If you aren't using a GPU, you don't need this function. :param img: A list of images (each as a num...
[ "Returns", "an", "2d", "array", "of", "bounding", "boxes", "of", "human", "faces", "in", "a", "image", "using", "the", "cnn", "face", "detector", "If", "you", "are", "using", "a", "GPU", "this", "can", "give", "you", "much", "faster", "results", "since",...
c96b010c02f15e8eeb0f71308c641179ac1f19bb
https://github.com/ageitgey/face_recognition/blob/c96b010c02f15e8eeb0f71308c641179ac1f19bb/face_recognition/api.py#L135-L151
train
Returns a 2d array of bounding boxes of human faces in a given image using the cnn face detectors.
ageitgey/face_recognition
face_recognition/api.py
face_landmarks
def face_landmarks(face_image, face_locations=None, model="large"): """ Given an image, returns a dict of face feature locations (eyes, nose, etc) for each face in the image :param face_image: image to search :param face_locations: Optionally provide a list of face locations to check. :param model:...
python
def face_landmarks(face_image, face_locations=None, model="large"): """ Given an image, returns a dict of face feature locations (eyes, nose, etc) for each face in the image :param face_image: image to search :param face_locations: Optionally provide a list of face locations to check. :param model:...
[ "def", "face_landmarks", "(", "face_image", ",", "face_locations", "=", "None", ",", "model", "=", "\"large\"", ")", ":", "landmarks", "=", "_raw_face_landmarks", "(", "face_image", ",", "face_locations", ",", "model", ")", "landmarks_as_tuples", "=", "[", "[", ...
Given an image, returns a dict of face feature locations (eyes, nose, etc) for each face in the image :param face_image: image to search :param face_locations: Optionally provide a list of face locations to check. :param model: Optional - which model to use. "large" (default) or "small" which only returns ...
[ "Given", "an", "image", "returns", "a", "dict", "of", "face", "feature", "locations", "(", "eyes", "nose", "etc", ")", "for", "each", "face", "in", "the", "image" ]
c96b010c02f15e8eeb0f71308c641179ac1f19bb
https://github.com/ageitgey/face_recognition/blob/c96b010c02f15e8eeb0f71308c641179ac1f19bb/face_recognition/api.py#L168-L200
train
Given an image returns a dict of face feature locations
ageitgey/face_recognition
face_recognition/api.py
face_encodings
def face_encodings(face_image, known_face_locations=None, num_jitters=1): """ Given an image, return the 128-dimension face encoding for each face in the image. :param face_image: The image that contains one or more faces :param known_face_locations: Optional - the bounding boxes of each face if you al...
python
def face_encodings(face_image, known_face_locations=None, num_jitters=1): """ Given an image, return the 128-dimension face encoding for each face in the image. :param face_image: The image that contains one or more faces :param known_face_locations: Optional - the bounding boxes of each face if you al...
[ "def", "face_encodings", "(", "face_image", ",", "known_face_locations", "=", "None", ",", "num_jitters", "=", "1", ")", ":", "raw_landmarks", "=", "_raw_face_landmarks", "(", "face_image", ",", "known_face_locations", ",", "model", "=", "\"small\"", ")", "return"...
Given an image, return the 128-dimension face encoding for each face in the image. :param face_image: The image that contains one or more faces :param known_face_locations: Optional - the bounding boxes of each face if you already know them. :param num_jitters: How many times to re-sample the face when cal...
[ "Given", "an", "image", "return", "the", "128", "-", "dimension", "face", "encoding", "for", "each", "face", "in", "the", "image", "." ]
c96b010c02f15e8eeb0f71308c641179ac1f19bb
https://github.com/ageitgey/face_recognition/blob/c96b010c02f15e8eeb0f71308c641179ac1f19bb/face_recognition/api.py#L203-L213
train
Given an image returns the 128 - dimensional face encoding for each face in the image.
apache/spark
python/pyspark/sql/types.py
_parse_datatype_string
def _parse_datatype_string(s): """ Parses the given data type string to a :class:`DataType`. The data type string format equals to :class:`DataType.simpleString`, except that top level struct type can omit the ``struct<>`` and atomic types use ``typeName()`` as their format, e.g. use ``byte`` instead ...
python
def _parse_datatype_string(s): """ Parses the given data type string to a :class:`DataType`. The data type string format equals to :class:`DataType.simpleString`, except that top level struct type can omit the ``struct<>`` and atomic types use ``typeName()`` as their format, e.g. use ``byte`` instead ...
[ "def", "_parse_datatype_string", "(", "s", ")", ":", "sc", "=", "SparkContext", ".", "_active_spark_context", "def", "from_ddl_schema", "(", "type_str", ")", ":", "return", "_parse_datatype_json_string", "(", "sc", ".", "_jvm", ".", "org", ".", "apache", ".", ...
Parses the given data type string to a :class:`DataType`. The data type string format equals to :class:`DataType.simpleString`, except that top level struct type can omit the ``struct<>`` and atomic types use ``typeName()`` as their format, e.g. use ``byte`` instead of ``tinyint`` for :class:`ByteType`. We ...
[ "Parses", "the", "given", "data", "type", "string", "to", "a", ":", "class", ":", "DataType", ".", "The", "data", "type", "string", "format", "equals", "to", ":", "class", ":", "DataType", ".", "simpleString", "except", "that", "top", "level", "struct", ...
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/sql/types.py#L758-L820
train
Parses a string into a base - level structure type.
apache/spark
python/pyspark/sql/types.py
_infer_type
def _infer_type(obj): """Infer the DataType from obj """ if obj is None: return NullType() if hasattr(obj, '__UDT__'): return obj.__UDT__ dataType = _type_mappings.get(type(obj)) if dataType is DecimalType: # the precision and scale of `obj` may be different from row to...
python
def _infer_type(obj): """Infer the DataType from obj """ if obj is None: return NullType() if hasattr(obj, '__UDT__'): return obj.__UDT__ dataType = _type_mappings.get(type(obj)) if dataType is DecimalType: # the precision and scale of `obj` may be different from row to...
[ "def", "_infer_type", "(", "obj", ")", ":", "if", "obj", "is", "None", ":", "return", "NullType", "(", ")", "if", "hasattr", "(", "obj", ",", "'__UDT__'", ")", ":", "return", "obj", ".", "__UDT__", "dataType", "=", "_type_mappings", ".", "get", "(", ...
Infer the DataType from obj
[ "Infer", "the", "DataType", "from", "obj" ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/sql/types.py#L1003-L1038
train
Infer the DataType from obj
apache/spark
python/pyspark/sql/types.py
_infer_schema
def _infer_schema(row, names=None): """Infer the schema from dict/namedtuple/object""" if isinstance(row, dict): items = sorted(row.items()) elif isinstance(row, (tuple, list)): if hasattr(row, "__fields__"): # Row items = zip(row.__fields__, tuple(row)) elif hasattr(ro...
python
def _infer_schema(row, names=None): """Infer the schema from dict/namedtuple/object""" if isinstance(row, dict): items = sorted(row.items()) elif isinstance(row, (tuple, list)): if hasattr(row, "__fields__"): # Row items = zip(row.__fields__, tuple(row)) elif hasattr(ro...
[ "def", "_infer_schema", "(", "row", ",", "names", "=", "None", ")", ":", "if", "isinstance", "(", "row", ",", "dict", ")", ":", "items", "=", "sorted", "(", "row", ".", "items", "(", ")", ")", "elif", "isinstance", "(", "row", ",", "(", "tuple", ...
Infer the schema from dict/namedtuple/object
[ "Infer", "the", "schema", "from", "dict", "/", "namedtuple", "/", "object" ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/sql/types.py#L1041-L1065
train
Infer the schema from dict namedtuple or object
apache/spark
python/pyspark/sql/types.py
_create_converter
def _create_converter(dataType): """Create a converter to drop the names of fields in obj """ if not _need_converter(dataType): return lambda x: x if isinstance(dataType, ArrayType): conv = _create_converter(dataType.elementType) return lambda row: [conv(v) for v in row] elif i...
python
def _create_converter(dataType): """Create a converter to drop the names of fields in obj """ if not _need_converter(dataType): return lambda x: x if isinstance(dataType, ArrayType): conv = _create_converter(dataType.elementType) return lambda row: [conv(v) for v in row] elif i...
[ "def", "_create_converter", "(", "dataType", ")", ":", "if", "not", "_need_converter", "(", "dataType", ")", ":", "return", "lambda", "x", ":", "x", "if", "isinstance", "(", "dataType", ",", "ArrayType", ")", ":", "conv", "=", "_create_converter", "(", "da...
Create a converter to drop the names of fields in obj
[ "Create", "a", "converter", "to", "drop", "the", "names", "of", "fields", "in", "obj" ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/sql/types.py#L1133-L1180
train
Create a converter to drop the names of fields in obj
apache/spark
python/pyspark/sql/types.py
to_arrow_type
def to_arrow_type(dt): """ Convert Spark data type to pyarrow type """ import pyarrow as pa if type(dt) == BooleanType: arrow_type = pa.bool_() elif type(dt) == ByteType: arrow_type = pa.int8() elif type(dt) == ShortType: arrow_type = pa.int16() elif type(dt) == Integ...
python
def to_arrow_type(dt): """ Convert Spark data type to pyarrow type """ import pyarrow as pa if type(dt) == BooleanType: arrow_type = pa.bool_() elif type(dt) == ByteType: arrow_type = pa.int8() elif type(dt) == ShortType: arrow_type = pa.int16() elif type(dt) == Integ...
[ "def", "to_arrow_type", "(", "dt", ")", ":", "import", "pyarrow", "as", "pa", "if", "type", "(", "dt", ")", "==", "BooleanType", ":", "arrow_type", "=", "pa", ".", "bool_", "(", ")", "elif", "type", "(", "dt", ")", "==", "ByteType", ":", "arrow_type"...
Convert Spark data type to pyarrow type
[ "Convert", "Spark", "data", "type", "to", "pyarrow", "type" ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/sql/types.py#L1581-L1622
train
Convert Spark data type to Arrow type
apache/spark
python/pyspark/sql/types.py
from_arrow_type
def from_arrow_type(at): """ Convert pyarrow type to Spark data type. """ import pyarrow.types as types if types.is_boolean(at): spark_type = BooleanType() elif types.is_int8(at): spark_type = ByteType() elif types.is_int16(at): spark_type = ShortType() elif types.is_...
python
def from_arrow_type(at): """ Convert pyarrow type to Spark data type. """ import pyarrow.types as types if types.is_boolean(at): spark_type = BooleanType() elif types.is_int8(at): spark_type = ByteType() elif types.is_int16(at): spark_type = ShortType() elif types.is_...
[ "def", "from_arrow_type", "(", "at", ")", ":", "import", "pyarrow", ".", "types", "as", "types", "if", "types", ".", "is_boolean", "(", "at", ")", ":", "spark_type", "=", "BooleanType", "(", ")", "elif", "types", ".", "is_int8", "(", "at", ")", ":", ...
Convert pyarrow type to Spark data type.
[ "Convert", "pyarrow", "type", "to", "Spark", "data", "type", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/sql/types.py#L1634-L1674
train
Convert a pyarrow type to Spark data type.
apache/spark
python/pyspark/sql/types.py
_check_series_localize_timestamps
def _check_series_localize_timestamps(s, timezone): """ Convert timezone aware timestamps to timezone-naive in the specified timezone or local timezone. If the input series is not a timestamp series, then the same series is returned. If the input series is a timestamp series, then a converted series is...
python
def _check_series_localize_timestamps(s, timezone): """ Convert timezone aware timestamps to timezone-naive in the specified timezone or local timezone. If the input series is not a timestamp series, then the same series is returned. If the input series is a timestamp series, then a converted series is...
[ "def", "_check_series_localize_timestamps", "(", "s", ",", "timezone", ")", ":", "from", "pyspark", ".", "sql", ".", "utils", "import", "require_minimum_pandas_version", "require_minimum_pandas_version", "(", ")", "from", "pandas", ".", "api", ".", "types", "import"...
Convert timezone aware timestamps to timezone-naive in the specified timezone or local timezone. If the input series is not a timestamp series, then the same series is returned. If the input series is a timestamp series, then a converted series is returned. :param s: pandas.Series :param timezone: the...
[ "Convert", "timezone", "aware", "timestamps", "to", "timezone", "-", "naive", "in", "the", "specified", "timezone", "or", "local", "timezone", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/sql/types.py#L1700-L1720
train
Convert timezone aware timestamps to timezone - naive in the specified timezone or local timezone.
apache/spark
python/pyspark/sql/types.py
_check_dataframe_localize_timestamps
def _check_dataframe_localize_timestamps(pdf, timezone): """ Convert timezone aware timestamps to timezone-naive in the specified timezone or local timezone :param pdf: pandas.DataFrame :param timezone: the timezone to convert. if None then use local timezone :return pandas.DataFrame where any time...
python
def _check_dataframe_localize_timestamps(pdf, timezone): """ Convert timezone aware timestamps to timezone-naive in the specified timezone or local timezone :param pdf: pandas.DataFrame :param timezone: the timezone to convert. if None then use local timezone :return pandas.DataFrame where any time...
[ "def", "_check_dataframe_localize_timestamps", "(", "pdf", ",", "timezone", ")", ":", "from", "pyspark", ".", "sql", ".", "utils", "import", "require_minimum_pandas_version", "require_minimum_pandas_version", "(", ")", "for", "column", ",", "series", "in", "pdf", "....
Convert timezone aware timestamps to timezone-naive in the specified timezone or local timezone :param pdf: pandas.DataFrame :param timezone: the timezone to convert. if None then use local timezone :return pandas.DataFrame where any timezone aware columns have been converted to tz-naive
[ "Convert", "timezone", "aware", "timestamps", "to", "timezone", "-", "naive", "in", "the", "specified", "timezone", "or", "local", "timezone" ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/sql/types.py#L1723-L1736
train
Convert timezone aware timestamps to timezone - naive in the specified timezone or local timezone - naive in the specified timezone or local timezone - naive in the specified timezone.
apache/spark
python/pyspark/sql/types.py
_check_series_convert_timestamps_internal
def _check_series_convert_timestamps_internal(s, timezone): """ Convert a tz-naive timestamp in the specified timezone or local timezone to UTC normalized for Spark internal storage :param s: a pandas.Series :param timezone: the timezone to convert. if None then use local timezone :return panda...
python
def _check_series_convert_timestamps_internal(s, timezone): """ Convert a tz-naive timestamp in the specified timezone or local timezone to UTC normalized for Spark internal storage :param s: a pandas.Series :param timezone: the timezone to convert. if None then use local timezone :return panda...
[ "def", "_check_series_convert_timestamps_internal", "(", "s", ",", "timezone", ")", ":", "from", "pyspark", ".", "sql", ".", "utils", "import", "require_minimum_pandas_version", "require_minimum_pandas_version", "(", ")", "from", "pandas", ".", "api", ".", "types", ...
Convert a tz-naive timestamp in the specified timezone or local timezone to UTC normalized for Spark internal storage :param s: a pandas.Series :param timezone: the timezone to convert. if None then use local timezone :return pandas.Series where if it is a timestamp, has been UTC normalized without a t...
[ "Convert", "a", "tz", "-", "naive", "timestamp", "in", "the", "specified", "timezone", "or", "local", "timezone", "to", "UTC", "normalized", "for", "Spark", "internal", "storage" ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/sql/types.py#L1739-L1789
train
Convert a tz - naive timestamp in the specified timezone or local timezone to UTC normalized for Spark internal storage.
apache/spark
python/pyspark/sql/types.py
_check_series_convert_timestamps_localize
def _check_series_convert_timestamps_localize(s, from_timezone, to_timezone): """ Convert timestamp to timezone-naive in the specified timezone or local timezone :param s: a pandas.Series :param from_timezone: the timezone to convert from. if None then use local timezone :param to_timezone: the tim...
python
def _check_series_convert_timestamps_localize(s, from_timezone, to_timezone): """ Convert timestamp to timezone-naive in the specified timezone or local timezone :param s: a pandas.Series :param from_timezone: the timezone to convert from. if None then use local timezone :param to_timezone: the tim...
[ "def", "_check_series_convert_timestamps_localize", "(", "s", ",", "from_timezone", ",", "to_timezone", ")", ":", "from", "pyspark", ".", "sql", ".", "utils", "import", "require_minimum_pandas_version", "require_minimum_pandas_version", "(", ")", "import", "pandas", "as...
Convert timestamp to timezone-naive in the specified timezone or local timezone :param s: a pandas.Series :param from_timezone: the timezone to convert from. if None then use local timezone :param to_timezone: the timezone to convert to. if None then use local timezone :return pandas.Series where if it...
[ "Convert", "timestamp", "to", "timezone", "-", "naive", "in", "the", "specified", "timezone", "or", "local", "timezone" ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/sql/types.py#L1792-L1817
train
Convert timestamp to timezone - naive in the specified timezone or local timezone.
apache/spark
python/pyspark/sql/types.py
StructType.add
def add(self, field, data_type=None, nullable=True, metadata=None): """ Construct a StructType by adding new elements to it to define the schema. The method accepts either: a) A single parameter which is a StructField object. b) Between 2 and 4 parameters as (name, data_...
python
def add(self, field, data_type=None, nullable=True, metadata=None): """ Construct a StructType by adding new elements to it to define the schema. The method accepts either: a) A single parameter which is a StructField object. b) Between 2 and 4 parameters as (name, data_...
[ "def", "add", "(", "self", ",", "field", ",", "data_type", "=", "None", ",", "nullable", "=", "True", ",", "metadata", "=", "None", ")", ":", "if", "isinstance", "(", "field", ",", "StructField", ")", ":", "self", ".", "fields", ".", "append", "(", ...
Construct a StructType by adding new elements to it to define the schema. The method accepts either: a) A single parameter which is a StructField object. b) Between 2 and 4 parameters as (name, data_type, nullable (optional), metadata(optional). The data_type parameter ma...
[ "Construct", "a", "StructType", "by", "adding", "new", "elements", "to", "it", "to", "define", "the", "schema", ".", "The", "method", "accepts", "either", ":" ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/sql/types.py#L491-L537
train
Constructs a new StructType object by adding new elements to the list of fields.
apache/spark
python/pyspark/sql/types.py
Row.asDict
def asDict(self, recursive=False): """ Return as an dict :param recursive: turns the nested Row as dict (default: False). >>> Row(name="Alice", age=11).asDict() == {'name': 'Alice', 'age': 11} True >>> row = Row(key=1, value=Row(name='a', age=2)) >>> row.asDict(...
python
def asDict(self, recursive=False): """ Return as an dict :param recursive: turns the nested Row as dict (default: False). >>> Row(name="Alice", age=11).asDict() == {'name': 'Alice', 'age': 11} True >>> row = Row(key=1, value=Row(name='a', age=2)) >>> row.asDict(...
[ "def", "asDict", "(", "self", ",", "recursive", "=", "False", ")", ":", "if", "not", "hasattr", "(", "self", ",", "\"__fields__\"", ")", ":", "raise", "TypeError", "(", "\"Cannot convert a Row class into dict\"", ")", "if", "recursive", ":", "def", "conv", "...
Return as an dict :param recursive: turns the nested Row as dict (default: False). >>> Row(name="Alice", age=11).asDict() == {'name': 'Alice', 'age': 11} True >>> row = Row(key=1, value=Row(name='a', age=2)) >>> row.asDict() == {'key': 1, 'value': Row(age=2, name='a')} ...
[ "Return", "as", "an", "dict" ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/sql/types.py#L1463-L1492
train
Converts the table into a dict.
apache/spark
python/pyspark/shuffle.py
ExternalMerger.mergeValues
def mergeValues(self, iterator): """ Combine the items by creator and combiner """ # speedup attribute lookup creator, comb = self.agg.createCombiner, self.agg.mergeValue c, data, pdata, hfun, batch = 0, self.data, self.pdata, self._partition, self.batch limit = self.memory_limit...
python
def mergeValues(self, iterator): """ Combine the items by creator and combiner """ # speedup attribute lookup creator, comb = self.agg.createCombiner, self.agg.mergeValue c, data, pdata, hfun, batch = 0, self.data, self.pdata, self._partition, self.batch limit = self.memory_limit...
[ "def", "mergeValues", "(", "self", ",", "iterator", ")", ":", "# speedup attribute lookup", "creator", ",", "comb", "=", "self", ".", "agg", ".", "createCombiner", ",", "self", ".", "agg", ".", "mergeValue", "c", ",", "data", ",", "pdata", ",", "hfun", "...
Combine the items by creator and combiner
[ "Combine", "the", "items", "by", "creator", "and", "combiner" ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/shuffle.py#L231-L253
train
Combine the items by creator and combiner
apache/spark
python/pyspark/shuffle.py
ExternalMerger.mergeCombiners
def mergeCombiners(self, iterator, limit=None): """ Merge (K,V) pair by mergeCombiner """ if limit is None: limit = self.memory_limit # speedup attribute lookup comb, hfun, objsize = self.agg.mergeCombiners, self._partition, self._object_size c, data, pdata, batch = 0...
python
def mergeCombiners(self, iterator, limit=None): """ Merge (K,V) pair by mergeCombiner """ if limit is None: limit = self.memory_limit # speedup attribute lookup comb, hfun, objsize = self.agg.mergeCombiners, self._partition, self._object_size c, data, pdata, batch = 0...
[ "def", "mergeCombiners", "(", "self", ",", "iterator", ",", "limit", "=", "None", ")", ":", "if", "limit", "is", "None", ":", "limit", "=", "self", ".", "memory_limit", "# speedup attribute lookup", "comb", ",", "hfun", ",", "objsize", "=", "self", ".", ...
Merge (K,V) pair by mergeCombiner
[ "Merge", "(", "K", "V", ")", "pair", "by", "mergeCombiner" ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/shuffle.py#L265-L289
train
Merge a set of keys and values by merging them into a single object.
apache/spark
python/pyspark/shuffle.py
ExternalMerger._spill
def _spill(self): """ dump already partitioned data into disks. It will dump the data in batch for better performance. """ global MemoryBytesSpilled, DiskBytesSpilled path = self._get_spill_dir(self.spills) if not os.path.exists(path): os.makedirs(pat...
python
def _spill(self): """ dump already partitioned data into disks. It will dump the data in batch for better performance. """ global MemoryBytesSpilled, DiskBytesSpilled path = self._get_spill_dir(self.spills) if not os.path.exists(path): os.makedirs(pat...
[ "def", "_spill", "(", "self", ")", ":", "global", "MemoryBytesSpilled", ",", "DiskBytesSpilled", "path", "=", "self", ".", "_get_spill_dir", "(", "self", ".", "spills", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "os", "....
dump already partitioned data into disks. It will dump the data in batch for better performance.
[ "dump", "already", "partitioned", "data", "into", "disks", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/shuffle.py#L291-L337
train
This function will dump already partitioned data into disks. It will dump the data into the disks and the memory used by the memory.
apache/spark
python/pyspark/shuffle.py
ExternalMerger._external_items
def _external_items(self): """ Return all partitioned items as iterator """ assert not self.data if any(self.pdata): self._spill() # disable partitioning and spilling when merge combiners from disk self.pdata = [] try: for i in range(self.partitio...
python
def _external_items(self): """ Return all partitioned items as iterator """ assert not self.data if any(self.pdata): self._spill() # disable partitioning and spilling when merge combiners from disk self.pdata = [] try: for i in range(self.partitio...
[ "def", "_external_items", "(", "self", ")", ":", "assert", "not", "self", ".", "data", "if", "any", "(", "self", ".", "pdata", ")", ":", "self", ".", "_spill", "(", ")", "# disable partitioning and spilling when merge combiners from disk", "self", ".", "pdata", ...
Return all partitioned items as iterator
[ "Return", "all", "partitioned", "items", "as", "iterator" ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/shuffle.py#L345-L364
train
Return all partitioned items as iterator
apache/spark
python/pyspark/shuffle.py
ExternalMerger._recursive_merged_items
def _recursive_merged_items(self, index): """ merge the partitioned items and return the as iterator If one partition can not be fit in memory, then them will be partitioned and merged recursively. """ subdirs = [os.path.join(d, "parts", str(index)) for d in self.localdi...
python
def _recursive_merged_items(self, index): """ merge the partitioned items and return the as iterator If one partition can not be fit in memory, then them will be partitioned and merged recursively. """ subdirs = [os.path.join(d, "parts", str(index)) for d in self.localdi...
[ "def", "_recursive_merged_items", "(", "self", ",", "index", ")", ":", "subdirs", "=", "[", "os", ".", "path", ".", "join", "(", "d", ",", "\"parts\"", ",", "str", "(", "index", ")", ")", "for", "d", "in", "self", ".", "localdirs", "]", "m", "=", ...
merge the partitioned items and return the as iterator If one partition can not be fit in memory, then them will be partitioned and merged recursively.
[ "merge", "the", "partitioned", "items", "and", "return", "the", "as", "iterator" ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/shuffle.py#L386-L409
train
Merge the partitioned items and return the as iterator
apache/spark
python/pyspark/shuffle.py
ExternalSorter.sorted
def sorted(self, iterator, key=None, reverse=False): """ Sort the elements in iterator, do external sort when the memory goes above the limit. """ global MemoryBytesSpilled, DiskBytesSpilled batch, limit = 100, self._next_limit() chunks, current_chunk = [], [] ...
python
def sorted(self, iterator, key=None, reverse=False): """ Sort the elements in iterator, do external sort when the memory goes above the limit. """ global MemoryBytesSpilled, DiskBytesSpilled batch, limit = 100, self._next_limit() chunks, current_chunk = [], [] ...
[ "def", "sorted", "(", "self", ",", "iterator", ",", "key", "=", "None", ",", "reverse", "=", "False", ")", ":", "global", "MemoryBytesSpilled", ",", "DiskBytesSpilled", "batch", ",", "limit", "=", "100", ",", "self", ".", "_next_limit", "(", ")", "chunks...
Sort the elements in iterator, do external sort when the memory goes above the limit.
[ "Sort", "the", "elements", "in", "iterator", "do", "external", "sort", "when", "the", "memory", "goes", "above", "the", "limit", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/shuffle.py#L455-L501
train
Sort the elements in iterator do external sort when the memory is below the limit.
apache/spark
python/pyspark/shuffle.py
ExternalGroupBy._spill
def _spill(self): """ dump already partitioned data into disks. """ global MemoryBytesSpilled, DiskBytesSpilled path = self._get_spill_dir(self.spills) if not os.path.exists(path): os.makedirs(path) used_memory = get_used_memory() if not self....
python
def _spill(self): """ dump already partitioned data into disks. """ global MemoryBytesSpilled, DiskBytesSpilled path = self._get_spill_dir(self.spills) if not os.path.exists(path): os.makedirs(path) used_memory = get_used_memory() if not self....
[ "def", "_spill", "(", "self", ")", ":", "global", "MemoryBytesSpilled", ",", "DiskBytesSpilled", "path", "=", "self", ".", "_get_spill_dir", "(", "self", ".", "spills", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "os", "....
dump already partitioned data into disks.
[ "dump", "already", "partitioned", "data", "into", "disks", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/shuffle.py#L709-L766
train
Dump already partitioned data into disks.
apache/spark
python/pyspark/shuffle.py
ExternalGroupBy._merge_sorted_items
def _merge_sorted_items(self, index): """ load a partition from disk, then sort and group by key """ def load_partition(j): path = self._get_spill_dir(j) p = os.path.join(path, str(index)) with open(p, 'rb', 65536) as f: for v in self.serializer.load_s...
python
def _merge_sorted_items(self, index): """ load a partition from disk, then sort and group by key """ def load_partition(j): path = self._get_spill_dir(j) p = os.path.join(path, str(index)) with open(p, 'rb', 65536) as f: for v in self.serializer.load_s...
[ "def", "_merge_sorted_items", "(", "self", ",", "index", ")", ":", "def", "load_partition", "(", "j", ")", ":", "path", "=", "self", ".", "_get_spill_dir", "(", "j", ")", "p", "=", "os", ".", "path", ".", "join", "(", "path", ",", "str", "(", "inde...
load a partition from disk, then sort and group by key
[ "load", "a", "partition", "from", "disk", "then", "sort", "and", "group", "by", "key" ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/shuffle.py#L786-L808
train
Load a partition from disk then sort and group by key
apache/spark
python/pyspark/daemon.py
worker
def worker(sock, authenticated): """ Called by a worker process after the fork(). """ signal.signal(SIGHUP, SIG_DFL) signal.signal(SIGCHLD, SIG_DFL) signal.signal(SIGTERM, SIG_DFL) # restore the handler for SIGINT, # it's useful for debugging (show the stacktrace before exit) signal....
python
def worker(sock, authenticated): """ Called by a worker process after the fork(). """ signal.signal(SIGHUP, SIG_DFL) signal.signal(SIGCHLD, SIG_DFL) signal.signal(SIGTERM, SIG_DFL) # restore the handler for SIGINT, # it's useful for debugging (show the stacktrace before exit) signal....
[ "def", "worker", "(", "sock", ",", "authenticated", ")", ":", "signal", ".", "signal", "(", "SIGHUP", ",", "SIG_DFL", ")", "signal", ".", "signal", "(", "SIGCHLD", ",", "SIG_DFL", ")", "signal", ".", "signal", "(", "SIGTERM", ",", "SIG_DFL", ")", "# re...
Called by a worker process after the fork().
[ "Called", "by", "a", "worker", "process", "after", "the", "fork", "()", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/daemon.py#L43-L81
train
This function is called by the worker process.
apache/spark
python/pyspark/rdd.py
portable_hash
def portable_hash(x): """ This function returns consistent hash code for builtin types, especially for None and tuple with None. The algorithm is similar to that one used by CPython 2.7 >>> portable_hash(None) 0 >>> portable_hash((None, 1)) & 0xffffffff 219750521 """ if sys.ve...
python
def portable_hash(x): """ This function returns consistent hash code for builtin types, especially for None and tuple with None. The algorithm is similar to that one used by CPython 2.7 >>> portable_hash(None) 0 >>> portable_hash((None, 1)) & 0xffffffff 219750521 """ if sys.ve...
[ "def", "portable_hash", "(", "x", ")", ":", "if", "sys", ".", "version_info", ">=", "(", "3", ",", "2", ",", "3", ")", "and", "'PYTHONHASHSEED'", "not", "in", "os", ".", "environ", ":", "raise", "Exception", "(", "\"Randomness of hash of string should be dis...
This function returns consistent hash code for builtin types, especially for None and tuple with None. The algorithm is similar to that one used by CPython 2.7 >>> portable_hash(None) 0 >>> portable_hash((None, 1)) & 0xffffffff 219750521
[ "This", "function", "returns", "consistent", "hash", "code", "for", "builtin", "types", "especially", "for", "None", "and", "tuple", "with", "None", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L78-L106
train
This function returns consistent hash code for builtin types and tuple with None.
apache/spark
python/pyspark/rdd.py
_parse_memory
def _parse_memory(s): """ Parse a memory string in the format supported by Java (e.g. 1g, 200m) and return the value in MiB >>> _parse_memory("256m") 256 >>> _parse_memory("2g") 2048 """ units = {'g': 1024, 'm': 1, 't': 1 << 20, 'k': 1.0 / 1024} if s[-1].lower() not in units: ...
python
def _parse_memory(s): """ Parse a memory string in the format supported by Java (e.g. 1g, 200m) and return the value in MiB >>> _parse_memory("256m") 256 >>> _parse_memory("2g") 2048 """ units = {'g': 1024, 'm': 1, 't': 1 << 20, 'k': 1.0 / 1024} if s[-1].lower() not in units: ...
[ "def", "_parse_memory", "(", "s", ")", ":", "units", "=", "{", "'g'", ":", "1024", ",", "'m'", ":", "1", ",", "'t'", ":", "1", "<<", "20", ",", "'k'", ":", "1.0", "/", "1024", "}", "if", "s", "[", "-", "1", "]", ".", "lower", "(", ")", "n...
Parse a memory string in the format supported by Java (e.g. 1g, 200m) and return the value in MiB >>> _parse_memory("256m") 256 >>> _parse_memory("2g") 2048
[ "Parse", "a", "memory", "string", "in", "the", "format", "supported", "by", "Java", "(", "e", ".", "g", ".", "1g", "200m", ")", "and", "return", "the", "value", "in", "MiB" ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L125-L138
train
Parse a memory string in the format supported by Java and return the value in MiB.
apache/spark
python/pyspark/rdd.py
ignore_unicode_prefix
def ignore_unicode_prefix(f): """ Ignore the 'u' prefix of string in doc tests, to make it works in both python 2 and 3 """ if sys.version >= '3': # the representation of unicode string in Python 3 does not have prefix 'u', # so remove the prefix 'u' for doc tests literal_re ...
python
def ignore_unicode_prefix(f): """ Ignore the 'u' prefix of string in doc tests, to make it works in both python 2 and 3 """ if sys.version >= '3': # the representation of unicode string in Python 3 does not have prefix 'u', # so remove the prefix 'u' for doc tests literal_re ...
[ "def", "ignore_unicode_prefix", "(", "f", ")", ":", "if", "sys", ".", "version", ">=", "'3'", ":", "# the representation of unicode string in Python 3 does not have prefix 'u',", "# so remove the prefix 'u' for doc tests", "literal_re", "=", "re", ".", "compile", "(", "r\"(...
Ignore the 'u' prefix of string in doc tests, to make it works in both python 2 and 3
[ "Ignore", "the", "u", "prefix", "of", "string", "in", "doc", "tests", "to", "make", "it", "works", "in", "both", "python", "2", "and", "3" ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L150-L160
train
Ignore the u prefix of string in doc tests
apache/spark
python/pyspark/rdd.py
RDD.persist
def persist(self, storageLevel=StorageLevel.MEMORY_ONLY): """ Set this RDD's storage level to persist its values across operations after the first time it is computed. This can only be used to assign a new storage level if the RDD does not have a storage level set yet. If no stor...
python
def persist(self, storageLevel=StorageLevel.MEMORY_ONLY): """ Set this RDD's storage level to persist its values across operations after the first time it is computed. This can only be used to assign a new storage level if the RDD does not have a storage level set yet. If no stor...
[ "def", "persist", "(", "self", ",", "storageLevel", "=", "StorageLevel", ".", "MEMORY_ONLY", ")", ":", "self", ".", "is_cached", "=", "True", "javaStorageLevel", "=", "self", ".", "ctx", ".", "_getJavaStorageLevel", "(", "storageLevel", ")", "self", ".", "_j...
Set this RDD's storage level to persist its values across operations after the first time it is computed. This can only be used to assign a new storage level if the RDD does not have a storage level set yet. If no storage level is specified defaults to (C{MEMORY_ONLY}). >>> rdd = sc.par...
[ "Set", "this", "RDD", "s", "storage", "level", "to", "persist", "its", "values", "across", "operations", "after", "the", "first", "time", "it", "is", "computed", ".", "This", "can", "only", "be", "used", "to", "assign", "a", "new", "storage", "level", "i...
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L231-L245
train
Set this RDD s storage level to persist its values across operations .
apache/spark
python/pyspark/rdd.py
RDD.flatMap
def flatMap(self, f, preservesPartitioning=False): """ Return a new RDD by first applying a function to all elements of this RDD, and then flattening the results. >>> rdd = sc.parallelize([2, 3, 4]) >>> sorted(rdd.flatMap(lambda x: range(1, x)).collect()) [1, 1, 1, 2, 2,...
python
def flatMap(self, f, preservesPartitioning=False): """ Return a new RDD by first applying a function to all elements of this RDD, and then flattening the results. >>> rdd = sc.parallelize([2, 3, 4]) >>> sorted(rdd.flatMap(lambda x: range(1, x)).collect()) [1, 1, 1, 2, 2,...
[ "def", "flatMap", "(", "self", ",", "f", ",", "preservesPartitioning", "=", "False", ")", ":", "def", "func", "(", "s", ",", "iterator", ")", ":", "return", "chain", ".", "from_iterable", "(", "map", "(", "fail_on_stopiteration", "(", "f", ")", ",", "i...
Return a new RDD by first applying a function to all elements of this RDD, and then flattening the results. >>> rdd = sc.parallelize([2, 3, 4]) >>> sorted(rdd.flatMap(lambda x: range(1, x)).collect()) [1, 1, 1, 2, 2, 3] >>> sorted(rdd.flatMap(lambda x: [(x, x), (x, x)]).collect(...
[ "Return", "a", "new", "RDD", "by", "first", "applying", "a", "function", "to", "all", "elements", "of", "this", "RDD", "and", "then", "flattening", "the", "results", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L329-L342
train
Return a new RDD by first applying a function to all elements of this RDD and then flattening the results.
apache/spark
python/pyspark/rdd.py
RDD.mapPartitionsWithSplit
def mapPartitionsWithSplit(self, f, preservesPartitioning=False): """ Deprecated: use mapPartitionsWithIndex instead. Return a new RDD by applying a function to each partition of this RDD, while tracking the index of the original partition. >>> rdd = sc.parallelize([1, 2, 3, 4]...
python
def mapPartitionsWithSplit(self, f, preservesPartitioning=False): """ Deprecated: use mapPartitionsWithIndex instead. Return a new RDD by applying a function to each partition of this RDD, while tracking the index of the original partition. >>> rdd = sc.parallelize([1, 2, 3, 4]...
[ "def", "mapPartitionsWithSplit", "(", "self", ",", "f", ",", "preservesPartitioning", "=", "False", ")", ":", "warnings", ".", "warn", "(", "\"mapPartitionsWithSplit is deprecated; \"", "\"use mapPartitionsWithIndex instead\"", ",", "DeprecationWarning", ",", "stacklevel", ...
Deprecated: use mapPartitionsWithIndex instead. Return a new RDD by applying a function to each partition of this RDD, while tracking the index of the original partition. >>> rdd = sc.parallelize([1, 2, 3, 4], 4) >>> def f(splitIndex, iterator): yield splitIndex >>> rdd.mapPart...
[ "Deprecated", ":", "use", "mapPartitionsWithIndex", "instead", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L369-L383
train
Return a new RDD by applying a function to each partition of this RDD while tracking the index of the original partition.
apache/spark
python/pyspark/rdd.py
RDD.sample
def sample(self, withReplacement, fraction, seed=None): """ Return a sampled subset of this RDD. :param withReplacement: can elements be sampled multiple times (replaced when sampled out) :param fraction: expected size of the sample as a fraction of this RDD's size without r...
python
def sample(self, withReplacement, fraction, seed=None): """ Return a sampled subset of this RDD. :param withReplacement: can elements be sampled multiple times (replaced when sampled out) :param fraction: expected size of the sample as a fraction of this RDD's size without r...
[ "def", "sample", "(", "self", ",", "withReplacement", ",", "fraction", ",", "seed", "=", "None", ")", ":", "assert", "fraction", ">=", "0.0", ",", "\"Negative fraction value: %s\"", "%", "fraction", "return", "self", ".", "mapPartitionsWithIndex", "(", "RDDSampl...
Return a sampled subset of this RDD. :param withReplacement: can elements be sampled multiple times (replaced when sampled out) :param fraction: expected size of the sample as a fraction of this RDD's size without replacement: probability that each element is chosen; fraction must be [0, 1]...
[ "Return", "a", "sampled", "subset", "of", "this", "RDD", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L418-L436
train
Return a new RDD with the specified fraction of the total number of elements in this RDD.
apache/spark
python/pyspark/rdd.py
RDD.randomSplit
def randomSplit(self, weights, seed=None): """ Randomly splits this RDD with the provided weights. :param weights: weights for splits, will be normalized if they don't sum to 1 :param seed: random seed :return: split RDDs in a list >>> rdd = sc.parallelize(range(500), 1...
python
def randomSplit(self, weights, seed=None): """ Randomly splits this RDD with the provided weights. :param weights: weights for splits, will be normalized if they don't sum to 1 :param seed: random seed :return: split RDDs in a list >>> rdd = sc.parallelize(range(500), 1...
[ "def", "randomSplit", "(", "self", ",", "weights", ",", "seed", "=", "None", ")", ":", "s", "=", "float", "(", "sum", "(", "weights", ")", ")", "cweights", "=", "[", "0.0", "]", "for", "w", "in", "weights", ":", "cweights", ".", "append", "(", "c...
Randomly splits this RDD with the provided weights. :param weights: weights for splits, will be normalized if they don't sum to 1 :param seed: random seed :return: split RDDs in a list >>> rdd = sc.parallelize(range(500), 1) >>> rdd1, rdd2 = rdd.randomSplit([2, 3], 17) ...
[ "Randomly", "splits", "this", "RDD", "with", "the", "provided", "weights", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L438-L462
train
Randomly splits this RDD with the provided weights.
apache/spark
python/pyspark/rdd.py
RDD.takeSample
def takeSample(self, withReplacement, num, seed=None): """ Return a fixed-size sampled subset of this RDD. .. note:: This method should only be used if the resulting array is expected to be small, as all the data is loaded into the driver's memory. >>> rdd = sc.parallelize(...
python
def takeSample(self, withReplacement, num, seed=None): """ Return a fixed-size sampled subset of this RDD. .. note:: This method should only be used if the resulting array is expected to be small, as all the data is loaded into the driver's memory. >>> rdd = sc.parallelize(...
[ "def", "takeSample", "(", "self", ",", "withReplacement", ",", "num", ",", "seed", "=", "None", ")", ":", "numStDev", "=", "10.0", "if", "num", "<", "0", ":", "raise", "ValueError", "(", "\"Sample size cannot be negative.\"", ")", "elif", "num", "==", "0",...
Return a fixed-size sampled subset of this RDD. .. note:: This method should only be used if the resulting array is expected to be small, as all the data is loaded into the driver's memory. >>> rdd = sc.parallelize(range(0, 10)) >>> len(rdd.takeSample(True, 20, 1)) 20 ...
[ "Return", "a", "fixed", "-", "size", "sampled", "subset", "of", "this", "RDD", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L465-L518
train
Return a fixed - size sampled subset of this RDD.
apache/spark
python/pyspark/rdd.py
RDD._computeFractionForSampleSize
def _computeFractionForSampleSize(sampleSizeLowerBound, total, withReplacement): """ Returns a sampling rate that guarantees a sample of size >= sampleSizeLowerBound 99.99% of the time. How the sampling rate is determined: Let p = num / total, where num is the sample size and to...
python
def _computeFractionForSampleSize(sampleSizeLowerBound, total, withReplacement): """ Returns a sampling rate that guarantees a sample of size >= sampleSizeLowerBound 99.99% of the time. How the sampling rate is determined: Let p = num / total, where num is the sample size and to...
[ "def", "_computeFractionForSampleSize", "(", "sampleSizeLowerBound", ",", "total", ",", "withReplacement", ")", ":", "fraction", "=", "float", "(", "sampleSizeLowerBound", ")", "/", "total", "if", "withReplacement", ":", "numStDev", "=", "5", "if", "(", "sampleSiz...
Returns a sampling rate that guarantees a sample of size >= sampleSizeLowerBound 99.99% of the time. How the sampling rate is determined: Let p = num / total, where num is the sample size and total is the total number of data points in the RDD. We're trying to compute q > p such...
[ "Returns", "a", "sampling", "rate", "that", "guarantees", "a", "sample", "of", "size", ">", "=", "sampleSizeLowerBound", "99", ".", "99%", "of", "the", "time", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L521-L551
train
Compute the sampling rate for a specific sample size.
apache/spark
python/pyspark/rdd.py
RDD.union
def union(self, other): """ Return the union of this RDD and another one. >>> rdd = sc.parallelize([1, 1, 2, 3]) >>> rdd.union(rdd).collect() [1, 1, 2, 3, 1, 1, 2, 3] """ if self._jrdd_deserializer == other._jrdd_deserializer: rdd = RDD(self._jrdd.uni...
python
def union(self, other): """ Return the union of this RDD and another one. >>> rdd = sc.parallelize([1, 1, 2, 3]) >>> rdd.union(rdd).collect() [1, 1, 2, 3, 1, 1, 2, 3] """ if self._jrdd_deserializer == other._jrdd_deserializer: rdd = RDD(self._jrdd.uni...
[ "def", "union", "(", "self", ",", "other", ")", ":", "if", "self", ".", "_jrdd_deserializer", "==", "other", ".", "_jrdd_deserializer", ":", "rdd", "=", "RDD", "(", "self", ".", "_jrdd", ".", "union", "(", "other", ".", "_jrdd", ")", ",", "self", "."...
Return the union of this RDD and another one. >>> rdd = sc.parallelize([1, 1, 2, 3]) >>> rdd.union(rdd).collect() [1, 1, 2, 3, 1, 1, 2, 3]
[ "Return", "the", "union", "of", "this", "RDD", "and", "another", "one", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L553-L574
train
Return the union of this RDD and another RDD.
apache/spark
python/pyspark/rdd.py
RDD.intersection
def intersection(self, other): """ Return the intersection of this RDD and another one. The output will not contain any duplicate elements, even if the input RDDs did. .. note:: This method performs a shuffle internally. >>> rdd1 = sc.parallelize([1, 10, 2, 3, 4, 5]) >>...
python
def intersection(self, other): """ Return the intersection of this RDD and another one. The output will not contain any duplicate elements, even if the input RDDs did. .. note:: This method performs a shuffle internally. >>> rdd1 = sc.parallelize([1, 10, 2, 3, 4, 5]) >>...
[ "def", "intersection", "(", "self", ",", "other", ")", ":", "return", "self", ".", "map", "(", "lambda", "v", ":", "(", "v", ",", "None", ")", ")", ".", "cogroup", "(", "other", ".", "map", "(", "lambda", "v", ":", "(", "v", ",", "None", ")", ...
Return the intersection of this RDD and another one. The output will not contain any duplicate elements, even if the input RDDs did. .. note:: This method performs a shuffle internally. >>> rdd1 = sc.parallelize([1, 10, 2, 3, 4, 5]) >>> rdd2 = sc.parallelize([1, 6, 2, 3, 7, 8]) ...
[ "Return", "the", "intersection", "of", "this", "RDD", "and", "another", "one", ".", "The", "output", "will", "not", "contain", "any", "duplicate", "elements", "even", "if", "the", "input", "RDDs", "did", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L576-L591
train
Return the intersection of this RDD and another RDD.
apache/spark
python/pyspark/rdd.py
RDD.repartitionAndSortWithinPartitions
def repartitionAndSortWithinPartitions(self, numPartitions=None, partitionFunc=portable_hash, ascending=True, keyfunc=lambda x: x): """ Repartition the RDD according to the given partitioner and, within each resulting partition, sort records by their ke...
python
def repartitionAndSortWithinPartitions(self, numPartitions=None, partitionFunc=portable_hash, ascending=True, keyfunc=lambda x: x): """ Repartition the RDD according to the given partitioner and, within each resulting partition, sort records by their ke...
[ "def", "repartitionAndSortWithinPartitions", "(", "self", ",", "numPartitions", "=", "None", ",", "partitionFunc", "=", "portable_hash", ",", "ascending", "=", "True", ",", "keyfunc", "=", "lambda", "x", ":", "x", ")", ":", "if", "numPartitions", "is", "None",...
Repartition the RDD according to the given partitioner and, within each resulting partition, sort records by their keys. >>> rdd = sc.parallelize([(0, 5), (3, 8), (2, 6), (0, 8), (3, 8), (1, 3)]) >>> rdd2 = rdd.repartitionAndSortWithinPartitions(2, lambda x: x % 2, True) >>> rdd2.glom()...
[ "Repartition", "the", "RDD", "according", "to", "the", "given", "partitioner", "and", "within", "each", "resulting", "partition", "sort", "records", "by", "their", "keys", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L612-L633
train
Repartition the RDD according to the given partitioner and within each resulting partition sort records by their keys.
apache/spark
python/pyspark/rdd.py
RDD.sortByKey
def sortByKey(self, ascending=True, numPartitions=None, keyfunc=lambda x: x): """ Sorts this RDD, which is assumed to consist of (key, value) pairs. >>> tmp = [('a', 1), ('b', 2), ('1', 3), ('d', 4), ('2', 5)] >>> sc.parallelize(tmp).sortByKey().first() ('1', 3) >>> sc.p...
python
def sortByKey(self, ascending=True, numPartitions=None, keyfunc=lambda x: x): """ Sorts this RDD, which is assumed to consist of (key, value) pairs. >>> tmp = [('a', 1), ('b', 2), ('1', 3), ('d', 4), ('2', 5)] >>> sc.parallelize(tmp).sortByKey().first() ('1', 3) >>> sc.p...
[ "def", "sortByKey", "(", "self", ",", "ascending", "=", "True", ",", "numPartitions", "=", "None", ",", "keyfunc", "=", "lambda", "x", ":", "x", ")", ":", "if", "numPartitions", "is", "None", ":", "numPartitions", "=", "self", ".", "_defaultReducePartition...
Sorts this RDD, which is assumed to consist of (key, value) pairs. >>> tmp = [('a', 1), ('b', 2), ('1', 3), ('d', 4), ('2', 5)] >>> sc.parallelize(tmp).sortByKey().first() ('1', 3) >>> sc.parallelize(tmp).sortByKey(True, 1).collect() [('1', 3), ('2', 5), ('a', 1), ('b', 2), ('d'...
[ "Sorts", "this", "RDD", "which", "is", "assumed", "to", "consist", "of", "(", "key", "value", ")", "pairs", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L635-L689
train
Sorts this RDD by key.
apache/spark
python/pyspark/rdd.py
RDD.sortBy
def sortBy(self, keyfunc, ascending=True, numPartitions=None): """ Sorts this RDD by the given keyfunc >>> tmp = [('a', 1), ('b', 2), ('1', 3), ('d', 4), ('2', 5)] >>> sc.parallelize(tmp).sortBy(lambda x: x[0]).collect() [('1', 3), ('2', 5), ('a', 1), ('b', 2), ('d', 4)] ...
python
def sortBy(self, keyfunc, ascending=True, numPartitions=None): """ Sorts this RDD by the given keyfunc >>> tmp = [('a', 1), ('b', 2), ('1', 3), ('d', 4), ('2', 5)] >>> sc.parallelize(tmp).sortBy(lambda x: x[0]).collect() [('1', 3), ('2', 5), ('a', 1), ('b', 2), ('d', 4)] ...
[ "def", "sortBy", "(", "self", ",", "keyfunc", ",", "ascending", "=", "True", ",", "numPartitions", "=", "None", ")", ":", "return", "self", ".", "keyBy", "(", "keyfunc", ")", ".", "sortByKey", "(", "ascending", ",", "numPartitions", ")", ".", "values", ...
Sorts this RDD by the given keyfunc >>> tmp = [('a', 1), ('b', 2), ('1', 3), ('d', 4), ('2', 5)] >>> sc.parallelize(tmp).sortBy(lambda x: x[0]).collect() [('1', 3), ('2', 5), ('a', 1), ('b', 2), ('d', 4)] >>> sc.parallelize(tmp).sortBy(lambda x: x[1]).collect() [('a', 1), ('b', ...
[ "Sorts", "this", "RDD", "by", "the", "given", "keyfunc" ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L691-L701
train
Sorts this RDD by the given keyfunc.
apache/spark
python/pyspark/rdd.py
RDD.cartesian
def cartesian(self, other): """ Return the Cartesian product of this RDD and another one, that is, the RDD of all pairs of elements C{(a, b)} where C{a} is in C{self} and C{b} is in C{other}. >>> rdd = sc.parallelize([1, 2]) >>> sorted(rdd.cartesian(rdd).collect()) ...
python
def cartesian(self, other): """ Return the Cartesian product of this RDD and another one, that is, the RDD of all pairs of elements C{(a, b)} where C{a} is in C{self} and C{b} is in C{other}. >>> rdd = sc.parallelize([1, 2]) >>> sorted(rdd.cartesian(rdd).collect()) ...
[ "def", "cartesian", "(", "self", ",", "other", ")", ":", "# Due to batching, we can't use the Java cartesian method.", "deserializer", "=", "CartesianDeserializer", "(", "self", ".", "_jrdd_deserializer", ",", "other", ".", "_jrdd_deserializer", ")", "return", "RDD", "(...
Return the Cartesian product of this RDD and another one, that is, the RDD of all pairs of elements C{(a, b)} where C{a} is in C{self} and C{b} is in C{other}. >>> rdd = sc.parallelize([1, 2]) >>> sorted(rdd.cartesian(rdd).collect()) [(1, 1), (1, 2), (2, 1), (2, 2)]
[ "Return", "the", "Cartesian", "product", "of", "this", "RDD", "and", "another", "one", "that", "is", "the", "RDD", "of", "all", "pairs", "of", "elements", "C", "{", "(", "a", "b", ")", "}", "where", "C", "{", "a", "}", "is", "in", "C", "{", "self...
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L716-L729
train
Return the Cartesian product of this RDD and another RDD.
apache/spark
python/pyspark/rdd.py
RDD.groupBy
def groupBy(self, f, numPartitions=None, partitionFunc=portable_hash): """ Return an RDD of grouped items. >>> rdd = sc.parallelize([1, 1, 2, 3, 5, 8]) >>> result = rdd.groupBy(lambda x: x % 2).collect() >>> sorted([(x, sorted(y)) for (x, y) in result]) [(0, [2, 8]), (1,...
python
def groupBy(self, f, numPartitions=None, partitionFunc=portable_hash): """ Return an RDD of grouped items. >>> rdd = sc.parallelize([1, 1, 2, 3, 5, 8]) >>> result = rdd.groupBy(lambda x: x % 2).collect() >>> sorted([(x, sorted(y)) for (x, y) in result]) [(0, [2, 8]), (1,...
[ "def", "groupBy", "(", "self", ",", "f", ",", "numPartitions", "=", "None", ",", "partitionFunc", "=", "portable_hash", ")", ":", "return", "self", ".", "map", "(", "lambda", "x", ":", "(", "f", "(", "x", ")", ",", "x", ")", ")", ".", "groupByKey",...
Return an RDD of grouped items. >>> rdd = sc.parallelize([1, 1, 2, 3, 5, 8]) >>> result = rdd.groupBy(lambda x: x % 2).collect() >>> sorted([(x, sorted(y)) for (x, y) in result]) [(0, [2, 8]), (1, [1, 1, 3, 5])]
[ "Return", "an", "RDD", "of", "grouped", "items", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L731-L740
train
Return an RDD of grouped items by a function.
apache/spark
python/pyspark/rdd.py
RDD.pipe
def pipe(self, command, env=None, checkCode=False): """ Return an RDD created by piping elements to a forked external process. >>> sc.parallelize(['1', '2', '', '3']).pipe('cat').collect() [u'1', u'2', u'', u'3'] :param checkCode: whether or not to check the return value of the...
python
def pipe(self, command, env=None, checkCode=False): """ Return an RDD created by piping elements to a forked external process. >>> sc.parallelize(['1', '2', '', '3']).pipe('cat').collect() [u'1', u'2', u'', u'3'] :param checkCode: whether or not to check the return value of the...
[ "def", "pipe", "(", "self", ",", "command", ",", "env", "=", "None", ",", "checkCode", "=", "False", ")", ":", "if", "env", "is", "None", ":", "env", "=", "dict", "(", ")", "def", "func", "(", "iterator", ")", ":", "pipe", "=", "Popen", "(", "s...
Return an RDD created by piping elements to a forked external process. >>> sc.parallelize(['1', '2', '', '3']).pipe('cat').collect() [u'1', u'2', u'', u'3'] :param checkCode: whether or not to check the return value of the shell command.
[ "Return", "an", "RDD", "created", "by", "piping", "elements", "to", "a", "forked", "external", "process", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L743-L776
train
Return an RDD of strings from a shell command.
apache/spark
python/pyspark/rdd.py
RDD.collect
def collect(self): """ Return a list that contains all of the elements in this RDD. .. note:: This method should only be used if the resulting array is expected to be small, as all the data is loaded into the driver's memory. """ with SCCallSiteSync(self.context) as ...
python
def collect(self): """ Return a list that contains all of the elements in this RDD. .. note:: This method should only be used if the resulting array is expected to be small, as all the data is loaded into the driver's memory. """ with SCCallSiteSync(self.context) as ...
[ "def", "collect", "(", "self", ")", ":", "with", "SCCallSiteSync", "(", "self", ".", "context", ")", "as", "css", ":", "sock_info", "=", "self", ".", "ctx", ".", "_jvm", ".", "PythonRDD", ".", "collectAndServe", "(", "self", ".", "_jrdd", ".", "rdd", ...
Return a list that contains all of the elements in this RDD. .. note:: This method should only be used if the resulting array is expected to be small, as all the data is loaded into the driver's memory.
[ "Return", "a", "list", "that", "contains", "all", "of", "the", "elements", "in", "this", "RDD", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L810-L819
train
Returns a list containing all of the elements in this RDD.
apache/spark
python/pyspark/rdd.py
RDD.reduce
def reduce(self, f): """ Reduces the elements of this RDD using the specified commutative and associative binary operator. Currently reduces partitions locally. >>> from operator import add >>> sc.parallelize([1, 2, 3, 4, 5]).reduce(add) 15 >>> sc.parallelize((2 ...
python
def reduce(self, f): """ Reduces the elements of this RDD using the specified commutative and associative binary operator. Currently reduces partitions locally. >>> from operator import add >>> sc.parallelize([1, 2, 3, 4, 5]).reduce(add) 15 >>> sc.parallelize((2 ...
[ "def", "reduce", "(", "self", ",", "f", ")", ":", "f", "=", "fail_on_stopiteration", "(", "f", ")", "def", "func", "(", "iterator", ")", ":", "iterator", "=", "iter", "(", "iterator", ")", "try", ":", "initial", "=", "next", "(", "iterator", ")", "...
Reduces the elements of this RDD using the specified commutative and associative binary operator. Currently reduces partitions locally. >>> from operator import add >>> sc.parallelize([1, 2, 3, 4, 5]).reduce(add) 15 >>> sc.parallelize((2 for _ in range(10))).map(lambda x: 1).cac...
[ "Reduces", "the", "elements", "of", "this", "RDD", "using", "the", "specified", "commutative", "and", "associative", "binary", "operator", ".", "Currently", "reduces", "partitions", "locally", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L821-L849
train
Reduces the elements of this RDD using the specified commutative and an associative binary operator. Currently reduces partitions locally.
apache/spark
python/pyspark/rdd.py
RDD.treeReduce
def treeReduce(self, f, depth=2): """ Reduces the elements of this RDD in a multi-level tree pattern. :param depth: suggested depth of the tree (default: 2) >>> add = lambda x, y: x + y >>> rdd = sc.parallelize([-5, -4, -3, -2, -1, 1, 2, 3, 4], 10) >>> rdd.treeReduce(ad...
python
def treeReduce(self, f, depth=2): """ Reduces the elements of this RDD in a multi-level tree pattern. :param depth: suggested depth of the tree (default: 2) >>> add = lambda x, y: x + y >>> rdd = sc.parallelize([-5, -4, -3, -2, -1, 1, 2, 3, 4], 10) >>> rdd.treeReduce(ad...
[ "def", "treeReduce", "(", "self", ",", "f", ",", "depth", "=", "2", ")", ":", "if", "depth", "<", "1", ":", "raise", "ValueError", "(", "\"Depth cannot be smaller than 1 but got %d.\"", "%", "depth", ")", "zeroValue", "=", "None", ",", "True", "# Use the sec...
Reduces the elements of this RDD in a multi-level tree pattern. :param depth: suggested depth of the tree (default: 2) >>> add = lambda x, y: x + y >>> rdd = sc.parallelize([-5, -4, -3, -2, -1, 1, 2, 3, 4], 10) >>> rdd.treeReduce(add) -5 >>> rdd.treeReduce(add, 1) ...
[ "Reduces", "the", "elements", "of", "this", "RDD", "in", "a", "multi", "-", "level", "tree", "pattern", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L851-L886
train
Reduces the elements of this RDD in a multi - level tree pattern.
apache/spark
python/pyspark/rdd.py
RDD.fold
def fold(self, zeroValue, op): """ Aggregate the elements of each partition, and then the results for all the partitions, using a given associative function and a neutral "zero value." The function C{op(t1, t2)} is allowed to modify C{t1} and return it as its result value to avo...
python
def fold(self, zeroValue, op): """ Aggregate the elements of each partition, and then the results for all the partitions, using a given associative function and a neutral "zero value." The function C{op(t1, t2)} is allowed to modify C{t1} and return it as its result value to avo...
[ "def", "fold", "(", "self", ",", "zeroValue", ",", "op", ")", ":", "op", "=", "fail_on_stopiteration", "(", "op", ")", "def", "func", "(", "iterator", ")", ":", "acc", "=", "zeroValue", "for", "obj", "in", "iterator", ":", "acc", "=", "op", "(", "a...
Aggregate the elements of each partition, and then the results for all the partitions, using a given associative function and a neutral "zero value." The function C{op(t1, t2)} is allowed to modify C{t1} and return it as its result value to avoid object allocation; however, it should not ...
[ "Aggregate", "the", "elements", "of", "each", "partition", "and", "then", "the", "results", "for", "all", "the", "partitions", "using", "a", "given", "associative", "function", "and", "a", "neutral", "zero", "value", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L888-L920
train
Folds the elements of each partition into a single value.
apache/spark
python/pyspark/rdd.py
RDD.aggregate
def aggregate(self, zeroValue, seqOp, combOp): """ Aggregate the elements of each partition, and then the results for all the partitions, using a given combine functions and a neutral "zero value." The functions C{op(t1, t2)} is allowed to modify C{t1} and return it as i...
python
def aggregate(self, zeroValue, seqOp, combOp): """ Aggregate the elements of each partition, and then the results for all the partitions, using a given combine functions and a neutral "zero value." The functions C{op(t1, t2)} is allowed to modify C{t1} and return it as i...
[ "def", "aggregate", "(", "self", ",", "zeroValue", ",", "seqOp", ",", "combOp", ")", ":", "seqOp", "=", "fail_on_stopiteration", "(", "seqOp", ")", "combOp", "=", "fail_on_stopiteration", "(", "combOp", ")", "def", "func", "(", "iterator", ")", ":", "acc",...
Aggregate the elements of each partition, and then the results for all the partitions, using a given combine functions and a neutral "zero value." The functions C{op(t1, t2)} is allowed to modify C{t1} and return it as its result value to avoid object allocation; however, it should not ...
[ "Aggregate", "the", "elements", "of", "each", "partition", "and", "then", "the", "results", "for", "all", "the", "partitions", "using", "a", "given", "combine", "functions", "and", "a", "neutral", "zero", "value", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L922-L955
train
Aggregate the elements of each partition and then the results for all the partitions using a given combine functions and a neutral zeroValue value.
apache/spark
python/pyspark/rdd.py
RDD.treeAggregate
def treeAggregate(self, zeroValue, seqOp, combOp, depth=2): """ Aggregates the elements of this RDD in a multi-level tree pattern. :param depth: suggested depth of the tree (default: 2) >>> add = lambda x, y: x + y >>> rdd = sc.parallelize([-5, -4, -3, -2, -1, 1, 2, 3, ...
python
def treeAggregate(self, zeroValue, seqOp, combOp, depth=2): """ Aggregates the elements of this RDD in a multi-level tree pattern. :param depth: suggested depth of the tree (default: 2) >>> add = lambda x, y: x + y >>> rdd = sc.parallelize([-5, -4, -3, -2, -1, 1, 2, 3, ...
[ "def", "treeAggregate", "(", "self", ",", "zeroValue", ",", "seqOp", ",", "combOp", ",", "depth", "=", "2", ")", ":", "if", "depth", "<", "1", ":", "raise", "ValueError", "(", "\"Depth cannot be smaller than 1 but got %d.\"", "%", "depth", ")", "if", "self",...
Aggregates the elements of this RDD in a multi-level tree pattern. :param depth: suggested depth of the tree (default: 2) >>> add = lambda x, y: x + y >>> rdd = sc.parallelize([-5, -4, -3, -2, -1, 1, 2, 3, 4], 10) >>> rdd.treeAggregate(0, add, add) -5 >>> rdd.tr...
[ "Aggregates", "the", "elements", "of", "this", "RDD", "in", "a", "multi", "-", "level", "tree", "pattern", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L957-L1007
train
This function aggregates the elements of this RDD in a multi - level tree.
apache/spark
python/pyspark/rdd.py
RDD.countByValue
def countByValue(self): """ Return the count of each unique value in this RDD as a dictionary of (value, count) pairs. >>> sorted(sc.parallelize([1, 2, 1, 2, 2], 2).countByValue().items()) [(1, 2), (2, 3)] """ def countPartition(iterator): counts = de...
python
def countByValue(self): """ Return the count of each unique value in this RDD as a dictionary of (value, count) pairs. >>> sorted(sc.parallelize([1, 2, 1, 2, 2], 2).countByValue().items()) [(1, 2), (2, 3)] """ def countPartition(iterator): counts = de...
[ "def", "countByValue", "(", "self", ")", ":", "def", "countPartition", "(", "iterator", ")", ":", "counts", "=", "defaultdict", "(", "int", ")", "for", "obj", "in", "iterator", ":", "counts", "[", "obj", "]", "+=", "1", "yield", "counts", "def", "merge...
Return the count of each unique value in this RDD as a dictionary of (value, count) pairs. >>> sorted(sc.parallelize([1, 2, 1, 2, 2], 2).countByValue().items()) [(1, 2), (2, 3)]
[ "Return", "the", "count", "of", "each", "unique", "value", "in", "this", "RDD", "as", "a", "dictionary", "of", "(", "value", "count", ")", "pairs", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L1245-L1263
train
Return the count of each unique value in this RDD as a dictionary of = > count
apache/spark
python/pyspark/rdd.py
RDD.top
def top(self, num, key=None): """ Get the top N elements from an RDD. .. note:: This method should only be used if the resulting array is expected to be small, as all the data is loaded into the driver's memory. .. note:: It returns the list sorted in descending order. ...
python
def top(self, num, key=None): """ Get the top N elements from an RDD. .. note:: This method should only be used if the resulting array is expected to be small, as all the data is loaded into the driver's memory. .. note:: It returns the list sorted in descending order. ...
[ "def", "top", "(", "self", ",", "num", ",", "key", "=", "None", ")", ":", "def", "topIterator", "(", "iterator", ")", ":", "yield", "heapq", ".", "nlargest", "(", "num", ",", "iterator", ",", "key", "=", "key", ")", "def", "merge", "(", "a", ",",...
Get the top N elements from an RDD. .. note:: This method should only be used if the resulting array is expected to be small, as all the data is loaded into the driver's memory. .. note:: It returns the list sorted in descending order. >>> sc.parallelize([10, 4, 2, 12, 3]).top(1) ...
[ "Get", "the", "top", "N", "elements", "from", "an", "RDD", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L1265-L1287
train
Return the top N elements from an RDD.
apache/spark
python/pyspark/rdd.py
RDD.takeOrdered
def takeOrdered(self, num, key=None): """ Get the N elements from an RDD ordered in ascending order or as specified by the optional key function. .. note:: this method should only be used if the resulting array is expected to be small, as all the data is loaded into the driv...
python
def takeOrdered(self, num, key=None): """ Get the N elements from an RDD ordered in ascending order or as specified by the optional key function. .. note:: this method should only be used if the resulting array is expected to be small, as all the data is loaded into the driv...
[ "def", "takeOrdered", "(", "self", ",", "num", ",", "key", "=", "None", ")", ":", "def", "merge", "(", "a", ",", "b", ")", ":", "return", "heapq", ".", "nsmallest", "(", "num", ",", "a", "+", "b", ",", "key", ")", "return", "self", ".", "mapPar...
Get the N elements from an RDD ordered in ascending order or as specified by the optional key function. .. note:: this method should only be used if the resulting array is expected to be small, as all the data is loaded into the driver's memory. >>> sc.parallelize([10, 1, 2, 9, 3, ...
[ "Get", "the", "N", "elements", "from", "an", "RDD", "ordered", "in", "ascending", "order", "or", "as", "specified", "by", "the", "optional", "key", "function", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L1289-L1306
train
Take the N elements from an RDD ordered in ascending order or as is specified by the optional key function.
apache/spark
python/pyspark/rdd.py
RDD.take
def take(self, num): """ Take the first num elements of the RDD. It works by first scanning one partition, and use the results from that partition to estimate the number of additional partitions needed to satisfy the limit. Translated from the Scala implementation in RD...
python
def take(self, num): """ Take the first num elements of the RDD. It works by first scanning one partition, and use the results from that partition to estimate the number of additional partitions needed to satisfy the limit. Translated from the Scala implementation in RD...
[ "def", "take", "(", "self", ",", "num", ")", ":", "items", "=", "[", "]", "totalParts", "=", "self", ".", "getNumPartitions", "(", ")", "partsScanned", "=", "0", "while", "len", "(", "items", ")", "<", "num", "and", "partsScanned", "<", "totalParts", ...
Take the first num elements of the RDD. It works by first scanning one partition, and use the results from that partition to estimate the number of additional partitions needed to satisfy the limit. Translated from the Scala implementation in RDD#take(). .. note:: this method ...
[ "Take", "the", "first", "num", "elements", "of", "the", "RDD", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L1308-L1367
train
Take the first num elements of the RDD.
apache/spark
python/pyspark/rdd.py
RDD.saveAsNewAPIHadoopDataset
def saveAsNewAPIHadoopDataset(self, conf, keyConverter=None, valueConverter=None): """ Output a Python RDD of key-value pairs (of form C{RDD[(K, V)]}) to any Hadoop file system, using the new Hadoop OutputFormat API (mapreduce package). Keys/values are converted for output using either u...
python
def saveAsNewAPIHadoopDataset(self, conf, keyConverter=None, valueConverter=None): """ Output a Python RDD of key-value pairs (of form C{RDD[(K, V)]}) to any Hadoop file system, using the new Hadoop OutputFormat API (mapreduce package). Keys/values are converted for output using either u...
[ "def", "saveAsNewAPIHadoopDataset", "(", "self", ",", "conf", ",", "keyConverter", "=", "None", ",", "valueConverter", "=", "None", ")", ":", "jconf", "=", "self", ".", "ctx", ".", "_dictToJavaMap", "(", "conf", ")", "pickledRDD", "=", "self", ".", "_pickl...
Output a Python RDD of key-value pairs (of form C{RDD[(K, V)]}) to any Hadoop file system, using the new Hadoop OutputFormat API (mapreduce package). Keys/values are converted for output using either user specified converters or, by default, L{org.apache.spark.api.python.JavaToWritableConverter}...
[ "Output", "a", "Python", "RDD", "of", "key", "-", "value", "pairs", "(", "of", "form", "C", "{", "RDD", "[", "(", "K", "V", ")", "]", "}", ")", "to", "any", "Hadoop", "file", "system", "using", "the", "new", "Hadoop", "OutputFormat", "API", "(", ...
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L1398-L1412
train
Save a Python RDD of key - value pairs to any Hadoop file system using the new Hadoop OutputFormat API.
apache/spark
python/pyspark/rdd.py
RDD.saveAsNewAPIHadoopFile
def saveAsNewAPIHadoopFile(self, path, outputFormatClass, keyClass=None, valueClass=None, keyConverter=None, valueConverter=None, conf=None): """ Output a Python RDD of key-value pairs (of form C{RDD[(K, V)]}) to any Hadoop file system, using the new Hadoop OutputF...
python
def saveAsNewAPIHadoopFile(self, path, outputFormatClass, keyClass=None, valueClass=None, keyConverter=None, valueConverter=None, conf=None): """ Output a Python RDD of key-value pairs (of form C{RDD[(K, V)]}) to any Hadoop file system, using the new Hadoop OutputF...
[ "def", "saveAsNewAPIHadoopFile", "(", "self", ",", "path", ",", "outputFormatClass", ",", "keyClass", "=", "None", ",", "valueClass", "=", "None", ",", "keyConverter", "=", "None", ",", "valueConverter", "=", "None", ",", "conf", "=", "None", ")", ":", "jc...
Output a Python RDD of key-value pairs (of form C{RDD[(K, V)]}) to any Hadoop file system, using the new Hadoop OutputFormat API (mapreduce package). Key and value types will be inferred if not specified. Keys and values are converted for output using either user specified converters or L{org.ap...
[ "Output", "a", "Python", "RDD", "of", "key", "-", "value", "pairs", "(", "of", "form", "C", "{", "RDD", "[", "(", "K", "V", ")", "]", "}", ")", "to", "any", "Hadoop", "file", "system", "using", "the", "new", "Hadoop", "OutputFormat", "API", "(", ...
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L1414-L1440
train
Save the current RDD to a new Hadoop file using the new API.
apache/spark
python/pyspark/rdd.py
RDD.saveAsSequenceFile
def saveAsSequenceFile(self, path, compressionCodecClass=None): """ Output a Python RDD of key-value pairs (of form C{RDD[(K, V)]}) to any Hadoop file system, using the L{org.apache.hadoop.io.Writable} types that we convert from the RDD's key and value types. The mechanism is as follows:...
python
def saveAsSequenceFile(self, path, compressionCodecClass=None): """ Output a Python RDD of key-value pairs (of form C{RDD[(K, V)]}) to any Hadoop file system, using the L{org.apache.hadoop.io.Writable} types that we convert from the RDD's key and value types. The mechanism is as follows:...
[ "def", "saveAsSequenceFile", "(", "self", ",", "path", ",", "compressionCodecClass", "=", "None", ")", ":", "pickledRDD", "=", "self", ".", "_pickled", "(", ")", "self", ".", "ctx", ".", "_jvm", ".", "PythonRDD", ".", "saveAsSequenceFile", "(", "pickledRDD",...
Output a Python RDD of key-value pairs (of form C{RDD[(K, V)]}) to any Hadoop file system, using the L{org.apache.hadoop.io.Writable} types that we convert from the RDD's key and value types. The mechanism is as follows: 1. Pyrolite is used to convert pickled Python RDD into RDD of Java obj...
[ "Output", "a", "Python", "RDD", "of", "key", "-", "value", "pairs", "(", "of", "form", "C", "{", "RDD", "[", "(", "K", "V", ")", "]", "}", ")", "to", "any", "Hadoop", "file", "system", "using", "the", "L", "{", "org", ".", "apache", ".", "hadoo...
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L1489-L1503
train
Save the current RDD to a sequence file.
apache/spark
python/pyspark/rdd.py
RDD.saveAsPickleFile
def saveAsPickleFile(self, path, batchSize=10): """ Save this RDD as a SequenceFile of serialized objects. The serializer used is L{pyspark.serializers.PickleSerializer}, default batch size is 10. >>> tmpFile = NamedTemporaryFile(delete=True) >>> tmpFile.close() ...
python
def saveAsPickleFile(self, path, batchSize=10): """ Save this RDD as a SequenceFile of serialized objects. The serializer used is L{pyspark.serializers.PickleSerializer}, default batch size is 10. >>> tmpFile = NamedTemporaryFile(delete=True) >>> tmpFile.close() ...
[ "def", "saveAsPickleFile", "(", "self", ",", "path", ",", "batchSize", "=", "10", ")", ":", "if", "batchSize", "==", "0", ":", "ser", "=", "AutoBatchedSerializer", "(", "PickleSerializer", "(", ")", ")", "else", ":", "ser", "=", "BatchedSerializer", "(", ...
Save this RDD as a SequenceFile of serialized objects. The serializer used is L{pyspark.serializers.PickleSerializer}, default batch size is 10. >>> tmpFile = NamedTemporaryFile(delete=True) >>> tmpFile.close() >>> sc.parallelize([1, 2, 'spark', 'rdd']).saveAsPickleFile(tmpFile....
[ "Save", "this", "RDD", "as", "a", "SequenceFile", "of", "serialized", "objects", ".", "The", "serializer", "used", "is", "L", "{", "pyspark", ".", "serializers", ".", "PickleSerializer", "}", "default", "batch", "size", "is", "10", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L1505-L1521
train
Save this RDD as a PickleFile.
apache/spark
python/pyspark/rdd.py
RDD.saveAsTextFile
def saveAsTextFile(self, path, compressionCodecClass=None): """ Save this RDD as a text file, using string representations of elements. @param path: path to text file @param compressionCodecClass: (None by default) string i.e. "org.apache.hadoop.io.compress.GzipCodec" ...
python
def saveAsTextFile(self, path, compressionCodecClass=None): """ Save this RDD as a text file, using string representations of elements. @param path: path to text file @param compressionCodecClass: (None by default) string i.e. "org.apache.hadoop.io.compress.GzipCodec" ...
[ "def", "saveAsTextFile", "(", "self", ",", "path", ",", "compressionCodecClass", "=", "None", ")", ":", "def", "func", "(", "split", ",", "iterator", ")", ":", "for", "x", "in", "iterator", ":", "if", "not", "isinstance", "(", "x", ",", "(", "unicode",...
Save this RDD as a text file, using string representations of elements. @param path: path to text file @param compressionCodecClass: (None by default) string i.e. "org.apache.hadoop.io.compress.GzipCodec" >>> tempFile = NamedTemporaryFile(delete=True) >>> tempFile.close() ...
[ "Save", "this", "RDD", "as", "a", "text", "file", "using", "string", "representations", "of", "elements", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L1524-L1572
train
Save this RDD as a text file using string representations of elements.
apache/spark
python/pyspark/rdd.py
RDD.reduceByKey
def reduceByKey(self, func, numPartitions=None, partitionFunc=portable_hash): """ Merge the values for each key using an associative and commutative reduce function. This will also perform the merging locally on each mapper before sending results to a reducer, similarly to a "combiner" ...
python
def reduceByKey(self, func, numPartitions=None, partitionFunc=portable_hash): """ Merge the values for each key using an associative and commutative reduce function. This will also perform the merging locally on each mapper before sending results to a reducer, similarly to a "combiner" ...
[ "def", "reduceByKey", "(", "self", ",", "func", ",", "numPartitions", "=", "None", ",", "partitionFunc", "=", "portable_hash", ")", ":", "return", "self", ".", "combineByKey", "(", "lambda", "x", ":", "x", ",", "func", ",", "func", ",", "numPartitions", ...
Merge the values for each key using an associative and commutative reduce function. This will also perform the merging locally on each mapper before sending results to a reducer, similarly to a "combiner" in MapReduce. Output will be partitioned with C{numPartitions} partitions, or the...
[ "Merge", "the", "values", "for", "each", "key", "using", "an", "associative", "and", "commutative", "reduce", "function", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L1611-L1627
train
Return a new RDD with the values for each key using an associative and commutative reduce function.
apache/spark
python/pyspark/rdd.py
RDD.reduceByKeyLocally
def reduceByKeyLocally(self, func): """ Merge the values for each key using an associative and commutative reduce function, but return the results immediately to the master as a dictionary. This will also perform the merging locally on each mapper before sending results to a red...
python
def reduceByKeyLocally(self, func): """ Merge the values for each key using an associative and commutative reduce function, but return the results immediately to the master as a dictionary. This will also perform the merging locally on each mapper before sending results to a red...
[ "def", "reduceByKeyLocally", "(", "self", ",", "func", ")", ":", "func", "=", "fail_on_stopiteration", "(", "func", ")", "def", "reducePartition", "(", "iterator", ")", ":", "m", "=", "{", "}", "for", "k", ",", "v", "in", "iterator", ":", "m", "[", "...
Merge the values for each key using an associative and commutative reduce function, but return the results immediately to the master as a dictionary. This will also perform the merging locally on each mapper before sending results to a reducer, similarly to a "combiner" in MapReduce. >...
[ "Merge", "the", "values", "for", "each", "key", "using", "an", "associative", "and", "commutative", "reduce", "function", "but", "return", "the", "results", "immediately", "to", "the", "master", "as", "a", "dictionary", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L1629-L1654
train
Return a new DStream with the values for each key using an associative and commutative reduce function.
apache/spark
python/pyspark/rdd.py
RDD.partitionBy
def partitionBy(self, numPartitions, partitionFunc=portable_hash): """ Return a copy of the RDD partitioned using the specified partitioner. >>> pairs = sc.parallelize([1, 2, 3, 4, 2, 4, 1]).map(lambda x: (x, x)) >>> sets = pairs.partitionBy(2).glom().collect() >>> len(set(sets[...
python
def partitionBy(self, numPartitions, partitionFunc=portable_hash): """ Return a copy of the RDD partitioned using the specified partitioner. >>> pairs = sc.parallelize([1, 2, 3, 4, 2, 4, 1]).map(lambda x: (x, x)) >>> sets = pairs.partitionBy(2).glom().collect() >>> len(set(sets[...
[ "def", "partitionBy", "(", "self", ",", "numPartitions", ",", "partitionFunc", "=", "portable_hash", ")", ":", "if", "numPartitions", "is", "None", ":", "numPartitions", "=", "self", ".", "_defaultReducePartitions", "(", ")", "partitioner", "=", "Partitioner", "...
Return a copy of the RDD partitioned using the specified partitioner. >>> pairs = sc.parallelize([1, 2, 3, 4, 2, 4, 1]).map(lambda x: (x, x)) >>> sets = pairs.partitionBy(2).glom().collect() >>> len(set(sets[0]).intersection(set(sets[1]))) 0
[ "Return", "a", "copy", "of", "the", "RDD", "partitioned", "using", "the", "specified", "partitioner", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L1742-L1810
train
Return a copy of the RDD partitioned by the specified partitioner.
apache/spark
python/pyspark/rdd.py
RDD.combineByKey
def combineByKey(self, createCombiner, mergeValue, mergeCombiners, numPartitions=None, partitionFunc=portable_hash): """ Generic function to combine the elements for each key using a custom set of aggregation functions. Turns an RDD[(K, V)] into a result of type RDD...
python
def combineByKey(self, createCombiner, mergeValue, mergeCombiners, numPartitions=None, partitionFunc=portable_hash): """ Generic function to combine the elements for each key using a custom set of aggregation functions. Turns an RDD[(K, V)] into a result of type RDD...
[ "def", "combineByKey", "(", "self", ",", "createCombiner", ",", "mergeValue", ",", "mergeCombiners", ",", "numPartitions", "=", "None", ",", "partitionFunc", "=", "portable_hash", ")", ":", "if", "numPartitions", "is", "None", ":", "numPartitions", "=", "self", ...
Generic function to combine the elements for each key using a custom set of aggregation functions. Turns an RDD[(K, V)] into a result of type RDD[(K, C)], for a "combined type" C. Users provide three functions: - C{createCombiner}, which turns a V into a C (e.g., creates ...
[ "Generic", "function", "to", "combine", "the", "elements", "for", "each", "key", "using", "a", "custom", "set", "of", "aggregation", "functions", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L1813-L1874
train
This function returns an RDD of elements from the first entry in the RDD that are combined with the second entry in the RDD.
apache/spark
python/pyspark/rdd.py
RDD.aggregateByKey
def aggregateByKey(self, zeroValue, seqFunc, combFunc, numPartitions=None, partitionFunc=portable_hash): """ Aggregate the values of each key, using given combine functions and a neutral "zero value". This function can return a different result type, U, than the type ...
python
def aggregateByKey(self, zeroValue, seqFunc, combFunc, numPartitions=None, partitionFunc=portable_hash): """ Aggregate the values of each key, using given combine functions and a neutral "zero value". This function can return a different result type, U, than the type ...
[ "def", "aggregateByKey", "(", "self", ",", "zeroValue", ",", "seqFunc", ",", "combFunc", ",", "numPartitions", "=", "None", ",", "partitionFunc", "=", "portable_hash", ")", ":", "def", "createZero", "(", ")", ":", "return", "copy", ".", "deepcopy", "(", "z...
Aggregate the values of each key, using given combine functions and a neutral "zero value". This function can return a different result type, U, than the type of the values in this RDD, V. Thus, we need one operation for merging a V into a U and one operation for merging two U's, The former oper...
[ "Aggregate", "the", "values", "of", "each", "key", "using", "given", "combine", "functions", "and", "a", "neutral", "zero", "value", ".", "This", "function", "can", "return", "a", "different", "result", "type", "U", "than", "the", "type", "of", "the", "val...
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L1876-L1891
train
Aggregate the values of each key using given combine functions and a neutral zero value.
apache/spark
python/pyspark/rdd.py
RDD.foldByKey
def foldByKey(self, zeroValue, func, numPartitions=None, partitionFunc=portable_hash): """ Merge the values for each key using an associative function "func" and a neutral "zeroValue" which may be added to the result an arbitrary number of times, and must not change the result (e...
python
def foldByKey(self, zeroValue, func, numPartitions=None, partitionFunc=portable_hash): """ Merge the values for each key using an associative function "func" and a neutral "zeroValue" which may be added to the result an arbitrary number of times, and must not change the result (e...
[ "def", "foldByKey", "(", "self", ",", "zeroValue", ",", "func", ",", "numPartitions", "=", "None", ",", "partitionFunc", "=", "portable_hash", ")", ":", "def", "createZero", "(", ")", ":", "return", "copy", ".", "deepcopy", "(", "zeroValue", ")", "return",...
Merge the values for each key using an associative function "func" and a neutral "zeroValue" which may be added to the result an arbitrary number of times, and must not change the result (e.g., 0 for addition, or 1 for multiplication.). >>> rdd = sc.parallelize([("a", 1), ("b", 1), ("a"...
[ "Merge", "the", "values", "for", "each", "key", "using", "an", "associative", "function", "func", "and", "a", "neutral", "zeroValue", "which", "may", "be", "added", "to", "the", "result", "an", "arbitrary", "number", "of", "times", "and", "must", "not", "c...
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L1893-L1909
train
Return a new table with the values for each key in the table grouped by func.
apache/spark
python/pyspark/rdd.py
RDD.groupByKey
def groupByKey(self, numPartitions=None, partitionFunc=portable_hash): """ Group the values for each key in the RDD into a single sequence. Hash-partitions the resulting RDD with numPartitions partitions. .. note:: If you are grouping in order to perform an aggregation (such as a ...
python
def groupByKey(self, numPartitions=None, partitionFunc=portable_hash): """ Group the values for each key in the RDD into a single sequence. Hash-partitions the resulting RDD with numPartitions partitions. .. note:: If you are grouping in order to perform an aggregation (such as a ...
[ "def", "groupByKey", "(", "self", ",", "numPartitions", "=", "None", ",", "partitionFunc", "=", "portable_hash", ")", ":", "def", "createCombiner", "(", "x", ")", ":", "return", "[", "x", "]", "def", "mergeValue", "(", "xs", ",", "x", ")", ":", "xs", ...
Group the values for each key in the RDD into a single sequence. Hash-partitions the resulting RDD with numPartitions partitions. .. note:: If you are grouping in order to perform an aggregation (such as a sum or average) over each key, using reduceByKey or aggregateByKey will p...
[ "Group", "the", "values", "for", "each", "key", "in", "the", "RDD", "into", "a", "single", "sequence", ".", "Hash", "-", "partitions", "the", "resulting", "RDD", "with", "numPartitions", "partitions", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L1915-L1958
train
Return an RDD of all the values for each key in the RDD.
apache/spark
python/pyspark/rdd.py
RDD.flatMapValues
def flatMapValues(self, f): """ Pass each value in the key-value pair RDD through a flatMap function without changing the keys; this also retains the original RDD's partitioning. >>> x = sc.parallelize([("a", ["x", "y", "z"]), ("b", ["p", "r"])]) >>> def f(x): return x ...
python
def flatMapValues(self, f): """ Pass each value in the key-value pair RDD through a flatMap function without changing the keys; this also retains the original RDD's partitioning. >>> x = sc.parallelize([("a", ["x", "y", "z"]), ("b", ["p", "r"])]) >>> def f(x): return x ...
[ "def", "flatMapValues", "(", "self", ",", "f", ")", ":", "flat_map_fn", "=", "lambda", "kv", ":", "(", "(", "kv", "[", "0", "]", ",", "x", ")", "for", "x", "in", "f", "(", "kv", "[", "1", "]", ")", ")", "return", "self", ".", "flatMap", "(", ...
Pass each value in the key-value pair RDD through a flatMap function without changing the keys; this also retains the original RDD's partitioning. >>> x = sc.parallelize([("a", ["x", "y", "z"]), ("b", ["p", "r"])]) >>> def f(x): return x >>> x.flatMapValues(f).collect() ...
[ "Pass", "each", "value", "in", "the", "key", "-", "value", "pair", "RDD", "through", "a", "flatMap", "function", "without", "changing", "the", "keys", ";", "this", "also", "retains", "the", "original", "RDD", "s", "partitioning", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L1960-L1972
train
Return a new RDD with the elements of each key - value pair obtained by applying a function to each value in the key - value pair.
apache/spark
python/pyspark/rdd.py
RDD.mapValues
def mapValues(self, f): """ Pass each value in the key-value pair RDD through a map function without changing the keys; this also retains the original RDD's partitioning. >>> x = sc.parallelize([("a", ["apple", "banana", "lemon"]), ("b", ["grapes"])]) >>> def f(x): retur...
python
def mapValues(self, f): """ Pass each value in the key-value pair RDD through a map function without changing the keys; this also retains the original RDD's partitioning. >>> x = sc.parallelize([("a", ["apple", "banana", "lemon"]), ("b", ["grapes"])]) >>> def f(x): retur...
[ "def", "mapValues", "(", "self", ",", "f", ")", ":", "map_values_fn", "=", "lambda", "kv", ":", "(", "kv", "[", "0", "]", ",", "f", "(", "kv", "[", "1", "]", ")", ")", "return", "self", ".", "map", "(", "map_values_fn", ",", "preservesPartitioning"...
Pass each value in the key-value pair RDD through a map function without changing the keys; this also retains the original RDD's partitioning. >>> x = sc.parallelize([("a", ["apple", "banana", "lemon"]), ("b", ["grapes"])]) >>> def f(x): return len(x) >>> x.mapValues(f).collect(...
[ "Pass", "each", "value", "in", "the", "key", "-", "value", "pair", "RDD", "through", "a", "map", "function", "without", "changing", "the", "keys", ";", "this", "also", "retains", "the", "original", "RDD", "s", "partitioning", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L1974-L1986
train
Return an RDD with the values of each key - value pair mapped through a map function.
apache/spark
python/pyspark/rdd.py
RDD.sampleByKey
def sampleByKey(self, withReplacement, fractions, seed=None): """ Return a subset of this RDD sampled by key (via stratified sampling). Create a sample of this RDD using variable sampling rates for different keys as specified by fractions, a key to sampling rate map. >>> fractio...
python
def sampleByKey(self, withReplacement, fractions, seed=None): """ Return a subset of this RDD sampled by key (via stratified sampling). Create a sample of this RDD using variable sampling rates for different keys as specified by fractions, a key to sampling rate map. >>> fractio...
[ "def", "sampleByKey", "(", "self", ",", "withReplacement", ",", "fractions", ",", "seed", "=", "None", ")", ":", "for", "fraction", "in", "fractions", ".", "values", "(", ")", ":", "assert", "fraction", ">=", "0.0", ",", "\"Negative fraction value: %s\"", "%...
Return a subset of this RDD sampled by key (via stratified sampling). Create a sample of this RDD using variable sampling rates for different keys as specified by fractions, a key to sampling rate map. >>> fractions = {"a": 0.2, "b": 0.1} >>> rdd = sc.parallelize(fractions.keys()).carte...
[ "Return", "a", "subset", "of", "this", "RDD", "sampled", "by", "key", "(", "via", "stratified", "sampling", ")", ".", "Create", "a", "sample", "of", "this", "RDD", "using", "variable", "sampling", "rates", "for", "different", "keys", "as", "specified", "by...
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L2016-L2035
train
Return a subset of this RDD with the values of the keys specified by fractions.
apache/spark
python/pyspark/rdd.py
RDD.subtractByKey
def subtractByKey(self, other, numPartitions=None): """ Return each (key, value) pair in C{self} that has no pair with matching key in C{other}. >>> x = sc.parallelize([("a", 1), ("b", 4), ("b", 5), ("a", 2)]) >>> y = sc.parallelize([("a", 3), ("c", None)]) >>> sorted(x....
python
def subtractByKey(self, other, numPartitions=None): """ Return each (key, value) pair in C{self} that has no pair with matching key in C{other}. >>> x = sc.parallelize([("a", 1), ("b", 4), ("b", 5), ("a", 2)]) >>> y = sc.parallelize([("a", 3), ("c", None)]) >>> sorted(x....
[ "def", "subtractByKey", "(", "self", ",", "other", ",", "numPartitions", "=", "None", ")", ":", "def", "filter_func", "(", "pair", ")", ":", "key", ",", "(", "val1", ",", "val2", ")", "=", "pair", "return", "val1", "and", "not", "val2", "return", "se...
Return each (key, value) pair in C{self} that has no pair with matching key in C{other}. >>> x = sc.parallelize([("a", 1), ("b", 4), ("b", 5), ("a", 2)]) >>> y = sc.parallelize([("a", 3), ("c", None)]) >>> sorted(x.subtractByKey(y).collect()) [('b', 4), ('b', 5)]
[ "Return", "each", "(", "key", "value", ")", "pair", "in", "C", "{", "self", "}", "that", "has", "no", "pair", "with", "matching", "key", "in", "C", "{", "other", "}", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L2037-L2050
train
Return each key value pair in self that has no pair with matching key in other.
apache/spark
python/pyspark/rdd.py
RDD.subtract
def subtract(self, other, numPartitions=None): """ Return each value in C{self} that is not contained in C{other}. >>> x = sc.parallelize([("a", 1), ("b", 4), ("b", 5), ("a", 3)]) >>> y = sc.parallelize([("a", 3), ("c", None)]) >>> sorted(x.subtract(y).collect()) [('a', ...
python
def subtract(self, other, numPartitions=None): """ Return each value in C{self} that is not contained in C{other}. >>> x = sc.parallelize([("a", 1), ("b", 4), ("b", 5), ("a", 3)]) >>> y = sc.parallelize([("a", 3), ("c", None)]) >>> sorted(x.subtract(y).collect()) [('a', ...
[ "def", "subtract", "(", "self", ",", "other", ",", "numPartitions", "=", "None", ")", ":", "# note: here 'True' is just a placeholder", "rdd", "=", "other", ".", "map", "(", "lambda", "x", ":", "(", "x", ",", "True", ")", ")", "return", "self", ".", "map...
Return each value in C{self} that is not contained in C{other}. >>> x = sc.parallelize([("a", 1), ("b", 4), ("b", 5), ("a", 3)]) >>> y = sc.parallelize([("a", 3), ("c", None)]) >>> sorted(x.subtract(y).collect()) [('a', 1), ('b', 4), ('b', 5)]
[ "Return", "each", "value", "in", "C", "{", "self", "}", "that", "is", "not", "contained", "in", "C", "{", "other", "}", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L2052-L2063
train
Return each value in self that is not contained in other.
apache/spark
python/pyspark/rdd.py
RDD.coalesce
def coalesce(self, numPartitions, shuffle=False): """ Return a new RDD that is reduced into `numPartitions` partitions. >>> sc.parallelize([1, 2, 3, 4, 5], 3).glom().collect() [[1], [2, 3], [4, 5]] >>> sc.parallelize([1, 2, 3, 4, 5], 3).coalesce(1).glom().collect() [[1, ...
python
def coalesce(self, numPartitions, shuffle=False): """ Return a new RDD that is reduced into `numPartitions` partitions. >>> sc.parallelize([1, 2, 3, 4, 5], 3).glom().collect() [[1], [2, 3], [4, 5]] >>> sc.parallelize([1, 2, 3, 4, 5], 3).coalesce(1).glom().collect() [[1, ...
[ "def", "coalesce", "(", "self", ",", "numPartitions", ",", "shuffle", "=", "False", ")", ":", "if", "shuffle", ":", "# Decrease the batch size in order to distribute evenly the elements across output", "# partitions. Otherwise, repartition will possibly produce highly skewed partitio...
Return a new RDD that is reduced into `numPartitions` partitions. >>> sc.parallelize([1, 2, 3, 4, 5], 3).glom().collect() [[1], [2, 3], [4, 5]] >>> sc.parallelize([1, 2, 3, 4, 5], 3).coalesce(1).glom().collect() [[1, 2, 3, 4, 5]]
[ "Return", "a", "new", "RDD", "that", "is", "reduced", "into", "numPartitions", "partitions", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L2095-L2115
train
Return a new RDD that is reduced into numPartitions partitions.
apache/spark
python/pyspark/rdd.py
RDD.zip
def zip(self, other): """ Zips this RDD with another one, returning key-value pairs with the first element in each RDD second element in each RDD, etc. Assumes that the two RDDs have the same number of partitions and the same number of elements in each partition (e.g. one was mad...
python
def zip(self, other): """ Zips this RDD with another one, returning key-value pairs with the first element in each RDD second element in each RDD, etc. Assumes that the two RDDs have the same number of partitions and the same number of elements in each partition (e.g. one was mad...
[ "def", "zip", "(", "self", ",", "other", ")", ":", "def", "get_batch_size", "(", "ser", ")", ":", "if", "isinstance", "(", "ser", ",", "BatchedSerializer", ")", ":", "return", "ser", ".", "batchSize", "return", "1", "# not batched", "def", "batch_as", "(...
Zips this RDD with another one, returning key-value pairs with the first element in each RDD second element in each RDD, etc. Assumes that the two RDDs have the same number of partitions and the same number of elements in each partition (e.g. one was made through a map on the other). ...
[ "Zips", "this", "RDD", "with", "another", "one", "returning", "key", "-", "value", "pairs", "with", "the", "first", "element", "in", "each", "RDD", "second", "element", "in", "each", "RDD", "etc", ".", "Assumes", "that", "the", "two", "RDDs", "have", "th...
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L2117-L2157
train
Returns an RDD of key - value pairs with the same entry - level as this one.
apache/spark
python/pyspark/rdd.py
RDD.zipWithIndex
def zipWithIndex(self): """ Zips this RDD with its element indices. The ordering is first based on the partition index and then the ordering of items within each partition. So the first item in the first partition gets index 0, and the last item in the last partition rec...
python
def zipWithIndex(self): """ Zips this RDD with its element indices. The ordering is first based on the partition index and then the ordering of items within each partition. So the first item in the first partition gets index 0, and the last item in the last partition rec...
[ "def", "zipWithIndex", "(", "self", ")", ":", "starts", "=", "[", "0", "]", "if", "self", ".", "getNumPartitions", "(", ")", ">", "1", ":", "nums", "=", "self", ".", "mapPartitions", "(", "lambda", "it", ":", "[", "sum", "(", "1", "for", "i", "in...
Zips this RDD with its element indices. The ordering is first based on the partition index and then the ordering of items within each partition. So the first item in the first partition gets index 0, and the last item in the last partition receives the largest index. This metho...
[ "Zips", "this", "RDD", "with", "its", "element", "indices", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L2159-L2184
train
Returns an RDD with its element indices.
apache/spark
python/pyspark/rdd.py
RDD.zipWithUniqueId
def zipWithUniqueId(self): """ Zips this RDD with generated unique Long ids. Items in the kth partition will get ids k, n+k, 2*n+k, ..., where n is the number of partitions. So there may exist gaps, but this method won't trigger a spark job, which is different from L{zip...
python
def zipWithUniqueId(self): """ Zips this RDD with generated unique Long ids. Items in the kth partition will get ids k, n+k, 2*n+k, ..., where n is the number of partitions. So there may exist gaps, but this method won't trigger a spark job, which is different from L{zip...
[ "def", "zipWithUniqueId", "(", "self", ")", ":", "n", "=", "self", ".", "getNumPartitions", "(", ")", "def", "func", "(", "k", ",", "it", ")", ":", "for", "i", ",", "v", "in", "enumerate", "(", "it", ")", ":", "yield", "v", ",", "i", "*", "n", ...
Zips this RDD with generated unique Long ids. Items in the kth partition will get ids k, n+k, 2*n+k, ..., where n is the number of partitions. So there may exist gaps, but this method won't trigger a spark job, which is different from L{zipWithIndex} >>> sc.parallelize(["a", "b...
[ "Zips", "this", "RDD", "with", "generated", "unique", "Long", "ids", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L2186-L2204
train
Returns an RDD with generated unique Long ids.
apache/spark
python/pyspark/rdd.py
RDD._defaultReducePartitions
def _defaultReducePartitions(self): """ Returns the default number of partitions to use during reduce tasks (e.g., groupBy). If spark.default.parallelism is set, then we'll use the value from SparkContext defaultParallelism, otherwise we'll use the number of partitions in this RDD. ...
python
def _defaultReducePartitions(self): """ Returns the default number of partitions to use during reduce tasks (e.g., groupBy). If spark.default.parallelism is set, then we'll use the value from SparkContext defaultParallelism, otherwise we'll use the number of partitions in this RDD. ...
[ "def", "_defaultReducePartitions", "(", "self", ")", ":", "if", "self", ".", "ctx", ".", "_conf", ".", "contains", "(", "\"spark.default.parallelism\"", ")", ":", "return", "self", ".", "ctx", ".", "defaultParallelism", "else", ":", "return", "self", ".", "g...
Returns the default number of partitions to use during reduce tasks (e.g., groupBy). If spark.default.parallelism is set, then we'll use the value from SparkContext defaultParallelism, otherwise we'll use the number of partitions in this RDD. This mirrors the behavior of the Scala Partitioner#d...
[ "Returns", "the", "default", "number", "of", "partitions", "to", "use", "during", "reduce", "tasks", "(", "e", ".", "g", ".", "groupBy", ")", ".", "If", "spark", ".", "default", ".", "parallelism", "is", "set", "then", "we", "ll", "use", "the", "value"...
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L2252-L2265
train
Returns the default number of partitions to use during reduce tasks.
apache/spark
python/pyspark/rdd.py
RDD.lookup
def lookup(self, key): """ Return the list of values in the RDD for key `key`. This operation is done efficiently if the RDD has a known partitioner by only searching the partition that the key maps to. >>> l = range(1000) >>> rdd = sc.parallelize(zip(l, l), 10) ...
python
def lookup(self, key): """ Return the list of values in the RDD for key `key`. This operation is done efficiently if the RDD has a known partitioner by only searching the partition that the key maps to. >>> l = range(1000) >>> rdd = sc.parallelize(zip(l, l), 10) ...
[ "def", "lookup", "(", "self", ",", "key", ")", ":", "values", "=", "self", ".", "filter", "(", "lambda", "kv", ":", "kv", "[", "0", "]", "==", "key", ")", ".", "values", "(", ")", "if", "self", ".", "partitioner", "is", "not", "None", ":", "ret...
Return the list of values in the RDD for key `key`. This operation is done efficiently if the RDD has a known partitioner by only searching the partition that the key maps to. >>> l = range(1000) >>> rdd = sc.parallelize(zip(l, l), 10) >>> rdd.lookup(42) # slow [42] ...
[ "Return", "the", "list", "of", "values", "in", "the", "RDD", "for", "key", "key", ".", "This", "operation", "is", "done", "efficiently", "if", "the", "RDD", "has", "a", "known", "partitioner", "by", "only", "searching", "the", "partition", "that", "the", ...
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L2267-L2291
train
Return the list of values in the RDD for key key. This operation is efficiently by searching the partitioner by only .
apache/spark
python/pyspark/rdd.py
RDD.sumApprox
def sumApprox(self, timeout, confidence=0.95): """ .. note:: Experimental Approximate operation to return the sum within a timeout or meet the confidence. >>> rdd = sc.parallelize(range(1000), 10) >>> r = sum(range(1000)) >>> abs(rdd.sumApprox(1000) - r) / r < 0...
python
def sumApprox(self, timeout, confidence=0.95): """ .. note:: Experimental Approximate operation to return the sum within a timeout or meet the confidence. >>> rdd = sc.parallelize(range(1000), 10) >>> r = sum(range(1000)) >>> abs(rdd.sumApprox(1000) - r) / r < 0...
[ "def", "sumApprox", "(", "self", ",", "timeout", ",", "confidence", "=", "0.95", ")", ":", "jrdd", "=", "self", ".", "mapPartitions", "(", "lambda", "it", ":", "[", "float", "(", "sum", "(", "it", ")", ")", "]", ")", ".", "_to_java_object_rdd", "(", ...
.. note:: Experimental Approximate operation to return the sum within a timeout or meet the confidence. >>> rdd = sc.parallelize(range(1000), 10) >>> r = sum(range(1000)) >>> abs(rdd.sumApprox(1000) - r) / r < 0.05 True
[ "..", "note", "::", "Experimental" ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L2316-L2331
train
Return the sum of the elements within a given timeout.
apache/spark
python/pyspark/rdd.py
RDD.meanApprox
def meanApprox(self, timeout, confidence=0.95): """ .. note:: Experimental Approximate operation to return the mean within a timeout or meet the confidence. >>> rdd = sc.parallelize(range(1000), 10) >>> r = sum(range(1000)) / 1000.0 >>> abs(rdd.meanApprox(1000) ...
python
def meanApprox(self, timeout, confidence=0.95): """ .. note:: Experimental Approximate operation to return the mean within a timeout or meet the confidence. >>> rdd = sc.parallelize(range(1000), 10) >>> r = sum(range(1000)) / 1000.0 >>> abs(rdd.meanApprox(1000) ...
[ "def", "meanApprox", "(", "self", ",", "timeout", ",", "confidence", "=", "0.95", ")", ":", "jrdd", "=", "self", ".", "map", "(", "float", ")", ".", "_to_java_object_rdd", "(", ")", "jdrdd", "=", "self", ".", "ctx", ".", "_jvm", ".", "JavaDoubleRDD", ...
.. note:: Experimental Approximate operation to return the mean within a timeout or meet the confidence. >>> rdd = sc.parallelize(range(1000), 10) >>> r = sum(range(1000)) / 1000.0 >>> abs(rdd.meanApprox(1000) - r) / r < 0.05 True
[ "..", "note", "::", "Experimental" ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L2333-L2348
train
Return the mean of the set of entries within a given timeout.
apache/spark
python/pyspark/rdd.py
RDD.countApproxDistinct
def countApproxDistinct(self, relativeSD=0.05): """ .. note:: Experimental Return approximate number of distinct elements in the RDD. The algorithm used is based on streamlib's implementation of `"HyperLogLog in Practice: Algorithmic Engineering of a State of The Art Ca...
python
def countApproxDistinct(self, relativeSD=0.05): """ .. note:: Experimental Return approximate number of distinct elements in the RDD. The algorithm used is based on streamlib's implementation of `"HyperLogLog in Practice: Algorithmic Engineering of a State of The Art Ca...
[ "def", "countApproxDistinct", "(", "self", ",", "relativeSD", "=", "0.05", ")", ":", "if", "relativeSD", "<", "0.000017", ":", "raise", "ValueError", "(", "\"relativeSD should be greater than 0.000017\"", ")", "# the hash space in Java is 2^32", "hashRDD", "=", "self", ...
.. note:: Experimental Return approximate number of distinct elements in the RDD. The algorithm used is based on streamlib's implementation of `"HyperLogLog in Practice: Algorithmic Engineering of a State of The Art Cardinality Estimation Algorithm", available here <https://doi...
[ "..", "note", "::", "Experimental" ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L2350-L2376
train
Return approximate number of distinct elements in the RDD.
apache/spark
python/pyspark/rdd.py
RDD.toLocalIterator
def toLocalIterator(self): """ Return an iterator that contains all of the elements in this RDD. The iterator will consume as much memory as the largest partition in this RDD. >>> rdd = sc.parallelize(range(10)) >>> [x for x in rdd.toLocalIterator()] [0, 1, 2, 3, 4, 5, 6...
python
def toLocalIterator(self): """ Return an iterator that contains all of the elements in this RDD. The iterator will consume as much memory as the largest partition in this RDD. >>> rdd = sc.parallelize(range(10)) >>> [x for x in rdd.toLocalIterator()] [0, 1, 2, 3, 4, 5, 6...
[ "def", "toLocalIterator", "(", "self", ")", ":", "with", "SCCallSiteSync", "(", "self", ".", "context", ")", "as", "css", ":", "sock_info", "=", "self", ".", "ctx", ".", "_jvm", ".", "PythonRDD", ".", "toLocalIteratorAndServe", "(", "self", ".", "_jrdd", ...
Return an iterator that contains all of the elements in this RDD. The iterator will consume as much memory as the largest partition in this RDD. >>> rdd = sc.parallelize(range(10)) >>> [x for x in rdd.toLocalIterator()] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[ "Return", "an", "iterator", "that", "contains", "all", "of", "the", "elements", "in", "this", "RDD", ".", "The", "iterator", "will", "consume", "as", "much", "memory", "as", "the", "largest", "partition", "in", "this", "RDD", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L2378-L2389
train
Returns an iterator that contains all of the elements in this RDD.
apache/spark
python/pyspark/rdd.py
RDDBarrier.mapPartitions
def mapPartitions(self, f, preservesPartitioning=False): """ .. note:: Experimental Returns a new RDD by applying a function to each partition of the wrapped RDD, where tasks are launched together in a barrier stage. The interface is the same as :func:`RDD.mapPartitions`. ...
python
def mapPartitions(self, f, preservesPartitioning=False): """ .. note:: Experimental Returns a new RDD by applying a function to each partition of the wrapped RDD, where tasks are launched together in a barrier stage. The interface is the same as :func:`RDD.mapPartitions`. ...
[ "def", "mapPartitions", "(", "self", ",", "f", ",", "preservesPartitioning", "=", "False", ")", ":", "def", "func", "(", "s", ",", "iterator", ")", ":", "return", "f", "(", "iterator", ")", "return", "PipelinedRDD", "(", "self", ".", "rdd", ",", "func"...
.. note:: Experimental Returns a new RDD by applying a function to each partition of the wrapped RDD, where tasks are launched together in a barrier stage. The interface is the same as :func:`RDD.mapPartitions`. Please see the API doc there. .. versionadded:: 2.4.0
[ "..", "note", "::", "Experimental" ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L2455-L2468
train
Returns a new RDD by applying a function to each partition of the wrapped RDD.
apache/spark
python/pyspark/sql/column.py
Column.substr
def substr(self, startPos, length): """ Return a :class:`Column` which is a substring of the column. :param startPos: start position (int or Column) :param length: length of the substring (int or Column) >>> df.select(df.name.substr(1, 3).alias("col")).collect() [Row(c...
python
def substr(self, startPos, length): """ Return a :class:`Column` which is a substring of the column. :param startPos: start position (int or Column) :param length: length of the substring (int or Column) >>> df.select(df.name.substr(1, 3).alias("col")).collect() [Row(c...
[ "def", "substr", "(", "self", ",", "startPos", ",", "length", ")", ":", "if", "type", "(", "startPos", ")", "!=", "type", "(", "length", ")", ":", "raise", "TypeError", "(", "\"startPos and length must be the same type. \"", "\"Got {startPos_t} and {length_t}, respe...
Return a :class:`Column` which is a substring of the column. :param startPos: start position (int or Column) :param length: length of the substring (int or Column) >>> df.select(df.name.substr(1, 3).alias("col")).collect() [Row(col=u'Ali'), Row(col=u'Bob')]
[ "Return", "a", ":", "class", ":", "Column", "which", "is", "a", "substring", "of", "the", "column", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/sql/column.py#L403-L427
train
Return a Column which is a substring of the column.
apache/spark
python/pyspark/sql/column.py
Column.isin
def isin(self, *cols): """ A boolean expression that is evaluated to true if the value of this expression is contained by the evaluated values of the arguments. >>> df[df.name.isin("Bob", "Mike")].collect() [Row(age=5, name=u'Bob')] >>> df[df.age.isin([1, 2, 3])].collect...
python
def isin(self, *cols): """ A boolean expression that is evaluated to true if the value of this expression is contained by the evaluated values of the arguments. >>> df[df.name.isin("Bob", "Mike")].collect() [Row(age=5, name=u'Bob')] >>> df[df.age.isin([1, 2, 3])].collect...
[ "def", "isin", "(", "self", ",", "*", "cols", ")", ":", "if", "len", "(", "cols", ")", "==", "1", "and", "isinstance", "(", "cols", "[", "0", "]", ",", "(", "list", ",", "set", ")", ")", ":", "cols", "=", "cols", "[", "0", "]", "cols", "=",...
A boolean expression that is evaluated to true if the value of this expression is contained by the evaluated values of the arguments. >>> df[df.name.isin("Bob", "Mike")].collect() [Row(age=5, name=u'Bob')] >>> df[df.age.isin([1, 2, 3])].collect() [Row(age=2, name=u'Alice')]
[ "A", "boolean", "expression", "that", "is", "evaluated", "to", "true", "if", "the", "value", "of", "this", "expression", "is", "contained", "by", "the", "evaluated", "values", "of", "the", "arguments", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/sql/column.py#L431-L446
train
A boolean expression that is evaluated to true if the value of this expression is contained by the evaluated values of the arguments.
apache/spark
python/pyspark/sql/column.py
Column.alias
def alias(self, *alias, **kwargs): """ Returns this column aliased with a new name or names (in the case of expressions that return more than one column, such as explode). :param alias: strings of desired column names (collects all positional arguments passed) :param metadata: a...
python
def alias(self, *alias, **kwargs): """ Returns this column aliased with a new name or names (in the case of expressions that return more than one column, such as explode). :param alias: strings of desired column names (collects all positional arguments passed) :param metadata: a...
[ "def", "alias", "(", "self", ",", "*", "alias", ",", "*", "*", "kwargs", ")", ":", "metadata", "=", "kwargs", ".", "pop", "(", "'metadata'", ",", "None", ")", "assert", "not", "kwargs", ",", "'Unexpected kwargs where passed: %s'", "%", "kwargs", "sc", "=...
Returns this column aliased with a new name or names (in the case of expressions that return more than one column, such as explode). :param alias: strings of desired column names (collects all positional arguments passed) :param metadata: a dict of information to be stored in ``metadata`` attri...
[ "Returns", "this", "column", "aliased", "with", "a", "new", "name", "or", "names", "(", "in", "the", "case", "of", "expressions", "that", "return", "more", "than", "one", "column", "such", "as", "explode", ")", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/sql/column.py#L538-L570
train
Returns this column aliased with a new name or names.
apache/spark
python/pyspark/sql/column.py
Column.when
def when(self, condition, value): """ Evaluates a list of conditions and returns one of multiple possible result expressions. If :func:`Column.otherwise` is not invoked, None is returned for unmatched conditions. See :func:`pyspark.sql.functions.when` for example usage. :param ...
python
def when(self, condition, value): """ Evaluates a list of conditions and returns one of multiple possible result expressions. If :func:`Column.otherwise` is not invoked, None is returned for unmatched conditions. See :func:`pyspark.sql.functions.when` for example usage. :param ...
[ "def", "when", "(", "self", ",", "condition", ",", "value", ")", ":", "if", "not", "isinstance", "(", "condition", ",", "Column", ")", ":", "raise", "TypeError", "(", "\"condition should be a Column\"", ")", "v", "=", "value", ".", "_jc", "if", "isinstance...
Evaluates a list of conditions and returns one of multiple possible result expressions. If :func:`Column.otherwise` is not invoked, None is returned for unmatched conditions. See :func:`pyspark.sql.functions.when` for example usage. :param condition: a boolean :class:`Column` expression. ...
[ "Evaluates", "a", "list", "of", "conditions", "and", "returns", "one", "of", "multiple", "possible", "result", "expressions", ".", "If", ":", "func", ":", "Column", ".", "otherwise", "is", "not", "invoked", "None", "is", "returned", "for", "unmatched", "cond...
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/sql/column.py#L614-L637
train
Evaluates a list of conditions and returns one of multiple possible result expressions.
apache/spark
python/pyspark/sql/column.py
Column.otherwise
def otherwise(self, value): """ Evaluates a list of conditions and returns one of multiple possible result expressions. If :func:`Column.otherwise` is not invoked, None is returned for unmatched conditions. See :func:`pyspark.sql.functions.when` for example usage. :param value:...
python
def otherwise(self, value): """ Evaluates a list of conditions and returns one of multiple possible result expressions. If :func:`Column.otherwise` is not invoked, None is returned for unmatched conditions. See :func:`pyspark.sql.functions.when` for example usage. :param value:...
[ "def", "otherwise", "(", "self", ",", "value", ")", ":", "v", "=", "value", ".", "_jc", "if", "isinstance", "(", "value", ",", "Column", ")", "else", "value", "jc", "=", "self", ".", "_jc", ".", "otherwise", "(", "v", ")", "return", "Column", "(", ...
Evaluates a list of conditions and returns one of multiple possible result expressions. If :func:`Column.otherwise` is not invoked, None is returned for unmatched conditions. See :func:`pyspark.sql.functions.when` for example usage. :param value: a literal value, or a :class:`Column` expressio...
[ "Evaluates", "a", "list", "of", "conditions", "and", "returns", "one", "of", "multiple", "possible", "result", "expressions", ".", "If", ":", "func", ":", "Column", ".", "otherwise", "is", "not", "invoked", "None", "is", "returned", "for", "unmatched", "cond...
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/sql/column.py#L640-L660
train
Evaluates a list of conditions and returns one of multiple possible result expressions.
apache/spark
python/pyspark/sql/column.py
Column.over
def over(self, window): """ Define a windowing column. :param window: a :class:`WindowSpec` :return: a Column >>> from pyspark.sql import Window >>> window = Window.partitionBy("name").orderBy("age").rowsBetween(-1, 1) >>> from pyspark.sql.functions import rank,...
python
def over(self, window): """ Define a windowing column. :param window: a :class:`WindowSpec` :return: a Column >>> from pyspark.sql import Window >>> window = Window.partitionBy("name").orderBy("age").rowsBetween(-1, 1) >>> from pyspark.sql.functions import rank,...
[ "def", "over", "(", "self", ",", "window", ")", ":", "from", "pyspark", ".", "sql", ".", "window", "import", "WindowSpec", "if", "not", "isinstance", "(", "window", ",", "WindowSpec", ")", ":", "raise", "TypeError", "(", "\"window should be WindowSpec\"", ")...
Define a windowing column. :param window: a :class:`WindowSpec` :return: a Column >>> from pyspark.sql import Window >>> window = Window.partitionBy("name").orderBy("age").rowsBetween(-1, 1) >>> from pyspark.sql.functions import rank, min >>> # df.select(rank().over(win...
[ "Define", "a", "windowing", "column", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/sql/column.py#L663-L679
train
Define a windowing column.
apache/spark
python/pyspark/mllib/feature.py
JavaVectorTransformer.transform
def transform(self, vector): """ Applies transformation on a vector or an RDD[Vector]. .. note:: In Python, transform cannot currently be used within an RDD transformation or action. Call transform directly on the RDD instead. :param vector: Vector or RDD of Vec...
python
def transform(self, vector): """ Applies transformation on a vector or an RDD[Vector]. .. note:: In Python, transform cannot currently be used within an RDD transformation or action. Call transform directly on the RDD instead. :param vector: Vector or RDD of Vec...
[ "def", "transform", "(", "self", ",", "vector", ")", ":", "if", "isinstance", "(", "vector", ",", "RDD", ")", ":", "vector", "=", "vector", ".", "map", "(", "_convert_to_vector", ")", "else", ":", "vector", "=", "_convert_to_vector", "(", "vector", ")", ...
Applies transformation on a vector or an RDD[Vector]. .. note:: In Python, transform cannot currently be used within an RDD transformation or action. Call transform directly on the RDD instead. :param vector: Vector or RDD of Vector to be transformed.
[ "Applies", "transformation", "on", "a", "vector", "or", "an", "RDD", "[", "Vector", "]", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/mllib/feature.py#L111-L125
train
Applies transformation on a vector or an RDD of Vectors.
apache/spark
python/pyspark/mllib/feature.py
StandardScaler.fit
def fit(self, dataset): """ Computes the mean and variance and stores as a model to be used for later scaling. :param dataset: The data used to compute the mean and variance to build the transformation model. :return: a StandardScalarModel """ ...
python
def fit(self, dataset): """ Computes the mean and variance and stores as a model to be used for later scaling. :param dataset: The data used to compute the mean and variance to build the transformation model. :return: a StandardScalarModel """ ...
[ "def", "fit", "(", "self", ",", "dataset", ")", ":", "dataset", "=", "dataset", ".", "map", "(", "_convert_to_vector", ")", "jmodel", "=", "callMLlibFunc", "(", "\"fitStandardScaler\"", ",", "self", ".", "withMean", ",", "self", ".", "withStd", ",", "datas...
Computes the mean and variance and stores as a model to be used for later scaling. :param dataset: The data used to compute the mean and variance to build the transformation model. :return: a StandardScalarModel
[ "Computes", "the", "mean", "and", "variance", "and", "stores", "as", "a", "model", "to", "be", "used", "for", "later", "scaling", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/mllib/feature.py#L240-L251
train
Fits the model to the given dataset.
apache/spark
python/pyspark/mllib/feature.py
ChiSqSelector.fit
def fit(self, data): """ Returns a ChiSquared feature selector. :param data: an `RDD[LabeledPoint]` containing the labeled dataset with categorical features. Real-valued features will be treated as categorical for each distinct value. ...
python
def fit(self, data): """ Returns a ChiSquared feature selector. :param data: an `RDD[LabeledPoint]` containing the labeled dataset with categorical features. Real-valued features will be treated as categorical for each distinct value. ...
[ "def", "fit", "(", "self", ",", "data", ")", ":", "jmodel", "=", "callMLlibFunc", "(", "\"fitChiSqSelector\"", ",", "self", ".", "selectorType", ",", "self", ".", "numTopFeatures", ",", "self", ".", "percentile", ",", "self", ".", "fpr", ",", "self", "."...
Returns a ChiSquared feature selector. :param data: an `RDD[LabeledPoint]` containing the labeled dataset with categorical features. Real-valued features will be treated as categorical for each distinct value. Apply feature discretizer before using...
[ "Returns", "a", "ChiSquared", "feature", "selector", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/mllib/feature.py#L383-L394
train
Fits a ChiSquared feature selector.
apache/spark
python/pyspark/mllib/feature.py
HashingTF.transform
def transform(self, document): """ Transforms the input document (list of terms) to term frequency vectors, or transform the RDD of document to RDD of term frequency vectors. """ if isinstance(document, RDD): return document.map(self.transform) freq =...
python
def transform(self, document): """ Transforms the input document (list of terms) to term frequency vectors, or transform the RDD of document to RDD of term frequency vectors. """ if isinstance(document, RDD): return document.map(self.transform) freq =...
[ "def", "transform", "(", "self", ",", "document", ")", ":", "if", "isinstance", "(", "document", ",", "RDD", ")", ":", "return", "document", ".", "map", "(", "self", ".", "transform", ")", "freq", "=", "{", "}", "for", "term", "in", "document", ":", ...
Transforms the input document (list of terms) to term frequency vectors, or transform the RDD of document to RDD of term frequency vectors.
[ "Transforms", "the", "input", "document", "(", "list", "of", "terms", ")", "to", "term", "frequency", "vectors", "or", "transform", "the", "RDD", "of", "document", "to", "RDD", "of", "term", "frequency", "vectors", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/mllib/feature.py#L473-L486
train
Transforms the input document to term frequency vectors or transform the RDD of document to RDD of term frequency vectors or transform the input document to RDD of term frequency vectors or transform the RDD of document to RDD of term frequency vectors.
apache/spark
python/pyspark/mllib/feature.py
Word2VecModel.findSynonyms
def findSynonyms(self, word, num): """ Find synonyms of a word :param word: a word or a vector representation of word :param num: number of synonyms to find :return: array of (word, cosineSimilarity) .. note:: Local use only """ if not isinstance(word, b...
python
def findSynonyms(self, word, num): """ Find synonyms of a word :param word: a word or a vector representation of word :param num: number of synonyms to find :return: array of (word, cosineSimilarity) .. note:: Local use only """ if not isinstance(word, b...
[ "def", "findSynonyms", "(", "self", ",", "word", ",", "num", ")", ":", "if", "not", "isinstance", "(", "word", ",", "basestring", ")", ":", "word", "=", "_convert_to_vector", "(", "word", ")", "words", ",", "similarity", "=", "self", ".", "call", "(", ...
Find synonyms of a word :param word: a word or a vector representation of word :param num: number of synonyms to find :return: array of (word, cosineSimilarity) .. note:: Local use only
[ "Find", "synonyms", "of", "a", "word" ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/mllib/feature.py#L611-L624
train
Find synonyms of a word.
apache/spark
python/pyspark/mllib/tree.py
TreeEnsembleModel.predict
def predict(self, x): """ Predict values for a single data point or an RDD of points using the model trained. .. note:: In Python, predict cannot currently be used within an RDD transformation or action. Call predict directly on the RDD instead. """ ...
python
def predict(self, x): """ Predict values for a single data point or an RDD of points using the model trained. .. note:: In Python, predict cannot currently be used within an RDD transformation or action. Call predict directly on the RDD instead. """ ...
[ "def", "predict", "(", "self", ",", "x", ")", ":", "if", "isinstance", "(", "x", ",", "RDD", ")", ":", "return", "self", ".", "call", "(", "\"predict\"", ",", "x", ".", "map", "(", "_convert_to_vector", ")", ")", "else", ":", "return", "self", ".",...
Predict values for a single data point or an RDD of points using the model trained. .. note:: In Python, predict cannot currently be used within an RDD transformation or action. Call predict directly on the RDD instead.
[ "Predict", "values", "for", "a", "single", "data", "point", "or", "an", "RDD", "of", "points", "using", "the", "model", "trained", "." ]
618d6bff71073c8c93501ab7392c3cc579730f0b
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/mllib/tree.py#L39-L52
train
Predict values for a single data point or an RDD of points.