[ { "instruction": "Write or improve a Python function based on this description:\n\nTrains a k-nearest neighbors classifier for face recognition.\n\n :param train_dir: directory that contains a sub-directory for each known person, with its name.\n\n (View in source code to see train_dir example tree structure)\n\n Structure:\n /\n ├── /\n │ ├── .jpeg\n │ ├── .jpeg\n │ ├── ...\n ├── /\n │ ├── .jpeg\n │ └── .jpeg\n └── ...\n\n :param model_save_path: (optional) path to save model on disk\n :param n_neighbors: (optional) number of neighbors to weigh in classification. Chosen automatically if not specified\n :param knn_algo: (optional) underlying data structure to support knn.default is ball_tree\n :param verbose: verbosity of training\n :return: returns knn classifier that was trained on the given data.", "output": "def train(train_dir, model_save_path=None, n_neighbors=None, knn_algo='ball_tree', verbose=False):\n \"\"\"\n Trains a k-nearest neighbors classifier for face recognition.\n\n :param train_dir: directory that contains a sub-directory for each known person, with its name.\n\n (View in source code to see train_dir example tree structure)\n\n Structure:\n /\n ├── /\n │ ├── .jpeg\n │ ├── .jpeg\n │ ├── ...\n ├── /\n │ ├── .jpeg\n │ └── .jpeg\n └── ...\n\n :param model_save_path: (optional) path to save model on disk\n :param n_neighbors: (optional) number of neighbors to weigh in classification. Chosen automatically if not specified\n :param knn_algo: (optional) underlying data structure to support knn.default is ball_tree\n :param verbose: verbosity of training\n :return: returns knn classifier that was trained on the given data.\n \"\"\"\n X = []\n y = []\n\n # Loop through each person in the training set\n for class_dir in os.listdir(train_dir):\n if not os.path.isdir(os.path.join(train_dir, class_dir)):\n continue\n\n # Loop through each training image for the current person\n for img_path in image_files_in_folder(os.path.join(train_dir, class_dir)):\n image = face_recognition.load_image_file(img_path)\n face_bounding_boxes = face_recognition.face_locations(image)\n\n if len(face_bounding_boxes) != 1:\n # If there are no people (or too many people) in a training image, skip the image.\n if verbose:\n print(\"Image {} not suitable for training: {}\".format(img_path, \"Didn't find a face\" if len(face_bounding_boxes) < 1 else \"Found more than one face\"))\n else:\n # Add face encoding for current image to the training set\n X.append(face_recognition.face_encodings(image, known_face_locations=face_bounding_boxes)[0])\n y.append(class_dir)\n\n # Determine how many neighbors to use for weighting in the KNN classifier\n if n_neighbors is None:\n n_neighbors = int(round(math.sqrt(len(X))))\n if verbose:\n print(\"Chose n_neighbors automatically:\", n_neighbors)\n\n # Create and train the KNN classifier\n knn_clf = neighbors.KNeighborsClassifier(n_neighbors=n_neighbors, algorithm=knn_algo, weights='distance')\n knn_clf.fit(X, y)\n\n # Save the trained KNN classifier\n if model_save_path is not None:\n with open(model_save_path, 'wb') as f:\n pickle.dump(knn_clf, f)\n\n return knn_clf" }, { "instruction": "Write or improve a Python function based on this description:\n\nRecognizes faces in given image using a trained KNN classifier\n\n :param X_img_path: path to image to be recognized\n :param knn_clf: (optional) a knn classifier object. if not specified, model_save_path must be specified.\n :param model_path: (optional) path to a pickled knn classifier. if not specified, model_save_path must be knn_clf.\n :param distance_threshold: (optional) distance threshold for face classification. the larger it is, the more chance\n of mis-classifying an unknown person as a known one.\n :return: a list of names and face locations for the recognized faces in the image: [(name, bounding box), ...].\n For faces of unrecognized persons, the name 'unknown' will be returned.", "output": "def predict(X_img_path, knn_clf=None, model_path=None, distance_threshold=0.6):\n \"\"\"\n Recognizes faces in given image using a trained KNN classifier\n\n :param X_img_path: path to image to be recognized\n :param knn_clf: (optional) a knn classifier object. if not specified, model_save_path must be specified.\n :param model_path: (optional) path to a pickled knn classifier. if not specified, model_save_path must be knn_clf.\n :param distance_threshold: (optional) distance threshold for face classification. the larger it is, the more chance\n of mis-classifying an unknown person as a known one.\n :return: a list of names and face locations for the recognized faces in the image: [(name, bounding box), ...].\n For faces of unrecognized persons, the name 'unknown' will be returned.\n \"\"\"\n if not os.path.isfile(X_img_path) or os.path.splitext(X_img_path)[1][1:] not in ALLOWED_EXTENSIONS:\n raise Exception(\"Invalid image path: {}\".format(X_img_path))\n\n if knn_clf is None and model_path is None:\n raise Exception(\"Must supply knn classifier either thourgh knn_clf or model_path\")\n\n # Load a trained KNN model (if one was passed in)\n if knn_clf is None:\n with open(model_path, 'rb') as f:\n knn_clf = pickle.load(f)\n\n # Load image file and find face locations\n X_img = face_recognition.load_image_file(X_img_path)\n X_face_locations = face_recognition.face_locations(X_img)\n\n # If no faces are found in the image, return an empty result.\n if len(X_face_locations) == 0:\n return []\n\n # Find encodings for faces in the test iamge\n faces_encodings = face_recognition.face_encodings(X_img, known_face_locations=X_face_locations)\n\n # Use the KNN model to find the best matches for the test face\n closest_distances = knn_clf.kneighbors(faces_encodings, n_neighbors=1)\n are_matches = [closest_distances[0][i][0] <= distance_threshold for i in range(len(X_face_locations))]\n\n # Predict classes and remove classifications that aren't within the threshold\n return [(pred, loc) if rec else (\"unknown\", loc) for pred, loc, rec in zip(knn_clf.predict(faces_encodings), X_face_locations, are_matches)]" }, { "instruction": "Write or improve a Python function based on this description:\n\nShows the face recognition results visually.\n\n :param img_path: path to image to be recognized\n :param predictions: results of the predict function\n :return:", "output": "def show_prediction_labels_on_image(img_path, predictions):\n \"\"\"\n Shows the face recognition results visually.\n\n :param img_path: path to image to be recognized\n :param predictions: results of the predict function\n :return:\n \"\"\"\n pil_image = Image.open(img_path).convert(\"RGB\")\n draw = ImageDraw.Draw(pil_image)\n\n for name, (top, right, bottom, left) in predictions:\n # Draw a box around the face using the Pillow module\n draw.rectangle(((left, top), (right, bottom)), outline=(0, 0, 255))\n\n # There's a bug in Pillow where it blows up with non-UTF-8 text\n # when using the default bitmap font\n name = name.encode(\"UTF-8\")\n\n # Draw a label with a name below the face\n text_width, text_height = draw.textsize(name)\n draw.rectangle(((left, bottom - text_height - 10), (right, bottom)), fill=(0, 0, 255), outline=(0, 0, 255))\n draw.text((left + 6, bottom - text_height - 5), name, fill=(255, 255, 255, 255))\n\n # Remove the drawing library from memory as per the Pillow docs\n del draw\n\n # Display the resulting image\n pil_image.show()" }, { "instruction": "Write or improve a Python function based on this description:\n\nConvert a dlib 'rect' object to a plain tuple in (top, right, bottom, left) order\n\n :param rect: a dlib 'rect' object\n :return: a plain tuple representation of the rect in (top, right, bottom, left) order", "output": "def _rect_to_css(rect):\n \"\"\"\n Convert a dlib 'rect' object to a plain tuple in (top, right, bottom, left) order\n\n :param rect: a dlib 'rect' object\n :return: a plain tuple representation of the rect in (top, right, bottom, left) order\n \"\"\"\n return rect.top(), rect.right(), rect.bottom(), rect.left()" }, { "instruction": "Write or improve a Python function based on this description:\n\nMake sure a tuple in (top, right, bottom, left) order is within the bounds of the image.\n\n :param css: plain tuple representation of the rect in (top, right, bottom, left) order\n :param image_shape: numpy shape of the image array\n :return: a trimmed plain tuple representation of the rect in (top, right, bottom, left) order", "output": "def _trim_css_to_bounds(css, image_shape):\n \"\"\"\n Make sure a tuple in (top, right, bottom, left) order is within the bounds of the image.\n\n :param css: plain tuple representation of the rect in (top, right, bottom, left) order\n :param image_shape: numpy shape of the image array\n :return: a trimmed plain tuple representation of the rect in (top, right, bottom, left) order\n \"\"\"\n return max(css[0], 0), min(css[1], image_shape[1]), min(css[2], image_shape[0]), max(css[3], 0)" }, { "instruction": "Write or improve a Python function based on this description:\n\nGiven a list of face encodings, compare them to a known face encoding and get a euclidean distance\n for each comparison face. The distance tells you how similar the faces are.\n\n :param faces: List of face encodings to compare\n :param face_to_compare: A face encoding to compare against\n :return: A numpy ndarray with the distance for each face in the same order as the 'faces' array", "output": "def face_distance(face_encodings, face_to_compare):\n \"\"\"\n Given a list of face encodings, compare them to a known face encoding and get a euclidean distance\n for each comparison face. The distance tells you how similar the faces are.\n\n :param faces: List of face encodings to compare\n :param face_to_compare: A face encoding to compare against\n :return: A numpy ndarray with the distance for each face in the same order as the 'faces' array\n \"\"\"\n if len(face_encodings) == 0:\n return np.empty((0))\n\n return np.linalg.norm(face_encodings - face_to_compare, axis=1)" }, { "instruction": "Write or improve a Python function based on this description:\n\nLoads an image file (.jpg, .png, etc) into a numpy array\n\n :param file: image file name or file object to load\n :param mode: format to convert the image to. Only 'RGB' (8-bit RGB, 3 channels) and 'L' (black and white) are supported.\n :return: image contents as numpy array", "output": "def load_image_file(file, mode='RGB'):\n \"\"\"\n Loads an image file (.jpg, .png, etc) into a numpy array\n\n :param file: image file name or file object to load\n :param mode: format to convert the image to. Only 'RGB' (8-bit RGB, 3 channels) and 'L' (black and white) are supported.\n :return: image contents as numpy array\n \"\"\"\n im = PIL.Image.open(file)\n if mode:\n im = im.convert(mode)\n return np.array(im)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns an array of bounding boxes of human faces in a image\n\n :param img: An image (as a numpy array)\n :param number_of_times_to_upsample: How many times to upsample the image looking for faces. Higher numbers find smaller faces.\n :param model: Which face detection model to use. \"hog\" is less accurate but faster on CPUs. \"cnn\" is a more accurate\n deep-learning model which is GPU/CUDA accelerated (if available). The default is \"hog\".\n :return: A list of dlib 'rect' objects of found face locations", "output": "def _raw_face_locations(img, number_of_times_to_upsample=1, model=\"hog\"):\n \"\"\"\n Returns an array of bounding boxes of human faces in a image\n\n :param img: An image (as a numpy array)\n :param number_of_times_to_upsample: How many times to upsample the image looking for faces. Higher numbers find smaller faces.\n :param model: Which face detection model to use. \"hog\" is less accurate but faster on CPUs. \"cnn\" is a more accurate\n deep-learning model which is GPU/CUDA accelerated (if available). The default is \"hog\".\n :return: A list of dlib 'rect' objects of found face locations\n \"\"\"\n if model == \"cnn\":\n return cnn_face_detector(img, number_of_times_to_upsample)\n else:\n return face_detector(img, number_of_times_to_upsample)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns an array of bounding boxes of human faces in a image\n\n :param img: An image (as a numpy array)\n :param number_of_times_to_upsample: How many times to upsample the image looking for faces. Higher numbers find smaller faces.\n :param model: Which face detection model to use. \"hog\" is less accurate but faster on CPUs. \"cnn\" is a more accurate\n deep-learning model which is GPU/CUDA accelerated (if available). The default is \"hog\".\n :return: A list of tuples of found face locations in css (top, right, bottom, left) order", "output": "def face_locations(img, number_of_times_to_upsample=1, model=\"hog\"):\n \"\"\"\n Returns an array of bounding boxes of human faces in a image\n\n :param img: An image (as a numpy array)\n :param number_of_times_to_upsample: How many times to upsample the image looking for faces. Higher numbers find smaller faces.\n :param model: Which face detection model to use. \"hog\" is less accurate but faster on CPUs. \"cnn\" is a more accurate\n deep-learning model which is GPU/CUDA accelerated (if available). The default is \"hog\".\n :return: A list of tuples of found face locations in css (top, right, bottom, left) order\n \"\"\"\n if model == \"cnn\":\n return [_trim_css_to_bounds(_rect_to_css(face.rect), img.shape) for face in _raw_face_locations(img, number_of_times_to_upsample, \"cnn\")]\n else:\n return [_trim_css_to_bounds(_rect_to_css(face), img.shape) for face in _raw_face_locations(img, number_of_times_to_upsample, model)]" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns an 2d array of bounding boxes of human faces in a image using the cnn face detector\n If you are using a GPU, this can give you much faster results since the GPU\n can process batches of images at once. If you aren't using a GPU, you don't need this function.\n\n :param img: A list of images (each as a numpy array)\n :param number_of_times_to_upsample: How many times to upsample the image looking for faces. Higher numbers find smaller faces.\n :param batch_size: How many images to include in each GPU processing batch.\n :return: A list of tuples of found face locations in css (top, right, bottom, left) order", "output": "def batch_face_locations(images, number_of_times_to_upsample=1, batch_size=128):\n \"\"\"\n Returns an 2d array of bounding boxes of human faces in a image using the cnn face detector\n If you are using a GPU, this can give you much faster results since the GPU\n can process batches of images at once. If you aren't using a GPU, you don't need this function.\n\n :param img: A list of images (each as a numpy array)\n :param number_of_times_to_upsample: How many times to upsample the image looking for faces. Higher numbers find smaller faces.\n :param batch_size: How many images to include in each GPU processing batch.\n :return: A list of tuples of found face locations in css (top, right, bottom, left) order\n \"\"\"\n def convert_cnn_detections_to_css(detections):\n return [_trim_css_to_bounds(_rect_to_css(face.rect), images[0].shape) for face in detections]\n\n raw_detections_batched = _raw_face_locations_batched(images, number_of_times_to_upsample, batch_size)\n\n return list(map(convert_cnn_detections_to_css, raw_detections_batched))" }, { "instruction": "Write or improve a Python function based on this description:\n\nGiven an image, returns a dict of face feature locations (eyes, nose, etc) for each face in the image\n\n :param face_image: image to search\n :param face_locations: Optionally provide a list of face locations to check.\n :param model: Optional - which model to use. \"large\" (default) or \"small\" which only returns 5 points but is faster.\n :return: A list of dicts of face feature locations (eyes, nose, etc)", "output": "def face_landmarks(face_image, face_locations=None, model=\"large\"):\n \"\"\"\n Given an image, returns a dict of face feature locations (eyes, nose, etc) for each face in the image\n\n :param face_image: image to search\n :param face_locations: Optionally provide a list of face locations to check.\n :param model: Optional - which model to use. \"large\" (default) or \"small\" which only returns 5 points but is faster.\n :return: A list of dicts of face feature locations (eyes, nose, etc)\n \"\"\"\n landmarks = _raw_face_landmarks(face_image, face_locations, model)\n landmarks_as_tuples = [[(p.x, p.y) for p in landmark.parts()] for landmark in landmarks]\n\n # For a definition of each point index, see https://cdn-images-1.medium.com/max/1600/1*AbEg31EgkbXSQehuNJBlWg.png\n if model == 'large':\n return [{\n \"chin\": points[0:17],\n \"left_eyebrow\": points[17:22],\n \"right_eyebrow\": points[22:27],\n \"nose_bridge\": points[27:31],\n \"nose_tip\": points[31:36],\n \"left_eye\": points[36:42],\n \"right_eye\": points[42:48],\n \"top_lip\": points[48:55] + [points[64]] + [points[63]] + [points[62]] + [points[61]] + [points[60]],\n \"bottom_lip\": points[54:60] + [points[48]] + [points[60]] + [points[67]] + [points[66]] + [points[65]] + [points[64]]\n } for points in landmarks_as_tuples]\n elif model == 'small':\n return [{\n \"nose_tip\": [points[4]],\n \"left_eye\": points[2:4],\n \"right_eye\": points[0:2],\n } for points in landmarks_as_tuples]\n else:\n raise ValueError(\"Invalid landmarks model type. Supported models are ['small', 'large'].\")" }, { "instruction": "Write or improve a Python function based on this description:\n\nGiven an image, return the 128-dimension face encoding for each face in the image.\n\n :param face_image: The image that contains one or more faces\n :param known_face_locations: Optional - the bounding boxes of each face if you already know them.\n :param num_jitters: How many times to re-sample the face when calculating encoding. Higher is more accurate, but slower (i.e. 100 is 100x slower)\n :return: A list of 128-dimensional face encodings (one for each face in the image)", "output": "def face_encodings(face_image, known_face_locations=None, num_jitters=1):\n \"\"\"\n Given an image, return the 128-dimension face encoding for each face in the image.\n\n :param face_image: The image that contains one or more faces\n :param known_face_locations: Optional - the bounding boxes of each face if you already know them.\n :param num_jitters: How many times to re-sample the face when calculating encoding. Higher is more accurate, but slower (i.e. 100 is 100x slower)\n :return: A list of 128-dimensional face encodings (one for each face in the image)\n \"\"\"\n raw_landmarks = _raw_face_landmarks(face_image, known_face_locations, model=\"small\")\n return [np.array(face_encoder.compute_face_descriptor(face_image, raw_landmark_set, num_jitters)) for raw_landmark_set in raw_landmarks]" }, { "instruction": "Write or improve a Python function based on this description:\n\nParses the given data type string to a :class:`DataType`. The data type string format equals\n to :class:`DataType.simpleString`, except that top level struct type can omit\n the ``struct<>`` and atomic types use ``typeName()`` as their format, e.g. use ``byte`` instead\n of ``tinyint`` for :class:`ByteType`. We can also use ``int`` as a short name\n for :class:`IntegerType`. Since Spark 2.3, this also supports a schema in a DDL-formatted\n string and case-insensitive strings.\n\n >>> _parse_datatype_string(\"int \")\n IntegerType\n >>> _parse_datatype_string(\"INT \")\n IntegerType\n >>> _parse_datatype_string(\"a: byte, b: decimal( 16 , 8 ) \")\n StructType(List(StructField(a,ByteType,true),StructField(b,DecimalType(16,8),true)))\n >>> _parse_datatype_string(\"a DOUBLE, b STRING\")\n StructType(List(StructField(a,DoubleType,true),StructField(b,StringType,true)))\n >>> _parse_datatype_string(\"a: array< short>\")\n StructType(List(StructField(a,ArrayType(ShortType,true),true)))\n >>> _parse_datatype_string(\" map \")\n MapType(StringType,StringType,true)\n\n >>> # Error cases\n >>> _parse_datatype_string(\"blabla\") # doctest: +IGNORE_EXCEPTION_DETAIL\n Traceback (most recent call last):\n ...\n ParseException:...\n >>> _parse_datatype_string(\"a: int,\") # doctest: +IGNORE_EXCEPTION_DETAIL\n Traceback (most recent call last):\n ...\n ParseException:...\n >>> _parse_datatype_string(\"array>> _parse_datatype_string(\"map>\") # doctest: +IGNORE_EXCEPTION_DETAIL\n Traceback (most recent call last):\n ...\n ParseException:...", "output": "def _parse_datatype_string(s):\n \"\"\"\n Parses the given data type string to a :class:`DataType`. The data type string format equals\n to :class:`DataType.simpleString`, except that top level struct type can omit\n the ``struct<>`` and atomic types use ``typeName()`` as their format, e.g. use ``byte`` instead\n of ``tinyint`` for :class:`ByteType`. We can also use ``int`` as a short name\n for :class:`IntegerType`. Since Spark 2.3, this also supports a schema in a DDL-formatted\n string and case-insensitive strings.\n\n >>> _parse_datatype_string(\"int \")\n IntegerType\n >>> _parse_datatype_string(\"INT \")\n IntegerType\n >>> _parse_datatype_string(\"a: byte, b: decimal( 16 , 8 ) \")\n StructType(List(StructField(a,ByteType,true),StructField(b,DecimalType(16,8),true)))\n >>> _parse_datatype_string(\"a DOUBLE, b STRING\")\n StructType(List(StructField(a,DoubleType,true),StructField(b,StringType,true)))\n >>> _parse_datatype_string(\"a: array< short>\")\n StructType(List(StructField(a,ArrayType(ShortType,true),true)))\n >>> _parse_datatype_string(\" map \")\n MapType(StringType,StringType,true)\n\n >>> # Error cases\n >>> _parse_datatype_string(\"blabla\") # doctest: +IGNORE_EXCEPTION_DETAIL\n Traceback (most recent call last):\n ...\n ParseException:...\n >>> _parse_datatype_string(\"a: int,\") # doctest: +IGNORE_EXCEPTION_DETAIL\n Traceback (most recent call last):\n ...\n ParseException:...\n >>> _parse_datatype_string(\"array>> _parse_datatype_string(\"map>\") # doctest: +IGNORE_EXCEPTION_DETAIL\n Traceback (most recent call last):\n ...\n ParseException:...\n \"\"\"\n sc = SparkContext._active_spark_context\n\n def from_ddl_schema(type_str):\n return _parse_datatype_json_string(\n sc._jvm.org.apache.spark.sql.types.StructType.fromDDL(type_str).json())\n\n def from_ddl_datatype(type_str):\n return _parse_datatype_json_string(\n sc._jvm.org.apache.spark.sql.api.python.PythonSQLUtils.parseDataType(type_str).json())\n\n try:\n # DDL format, \"fieldname datatype, fieldname datatype\".\n return from_ddl_schema(s)\n except Exception as e:\n try:\n # For backwards compatibility, \"integer\", \"struct\" and etc.\n return from_ddl_datatype(s)\n except:\n try:\n # For backwards compatibility, \"fieldname: datatype, fieldname: datatype\" case.\n return from_ddl_datatype(\"struct<%s>\" % s.strip())\n except:\n raise e" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn the Catalyst datatype from the size of integers.", "output": "def _int_size_to_type(size):\n \"\"\"\n Return the Catalyst datatype from the size of integers.\n \"\"\"\n if size <= 8:\n return ByteType\n if size <= 16:\n return ShortType\n if size <= 32:\n return IntegerType\n if size <= 64:\n return LongType" }, { "instruction": "Write or improve a Python function based on this description:\n\nInfer the DataType from obj", "output": "def _infer_type(obj):\n \"\"\"Infer the DataType from obj\n \"\"\"\n if obj is None:\n return NullType()\n\n if hasattr(obj, '__UDT__'):\n return obj.__UDT__\n\n dataType = _type_mappings.get(type(obj))\n if dataType is DecimalType:\n # the precision and scale of `obj` may be different from row to row.\n return DecimalType(38, 18)\n elif dataType is not None:\n return dataType()\n\n if isinstance(obj, dict):\n for key, value in obj.items():\n if key is not None and value is not None:\n return MapType(_infer_type(key), _infer_type(value), True)\n return MapType(NullType(), NullType(), True)\n elif isinstance(obj, list):\n for v in obj:\n if v is not None:\n return ArrayType(_infer_type(obj[0]), True)\n return ArrayType(NullType(), True)\n elif isinstance(obj, array):\n if obj.typecode in _array_type_mappings:\n return ArrayType(_array_type_mappings[obj.typecode](), False)\n else:\n raise TypeError(\"not supported type: array(%s)\" % obj.typecode)\n else:\n try:\n return _infer_schema(obj)\n except TypeError:\n raise TypeError(\"not supported type: %s\" % type(obj))" }, { "instruction": "Write or improve a Python function based on this description:\n\nInfer the schema from dict/namedtuple/object", "output": "def _infer_schema(row, names=None):\n \"\"\"Infer the schema from dict/namedtuple/object\"\"\"\n if isinstance(row, dict):\n items = sorted(row.items())\n\n elif isinstance(row, (tuple, list)):\n if hasattr(row, \"__fields__\"): # Row\n items = zip(row.__fields__, tuple(row))\n elif hasattr(row, \"_fields\"): # namedtuple\n items = zip(row._fields, tuple(row))\n else:\n if names is None:\n names = ['_%d' % i for i in range(1, len(row) + 1)]\n elif len(names) < len(row):\n names.extend('_%d' % i for i in range(len(names) + 1, len(row) + 1))\n items = zip(names, row)\n\n elif hasattr(row, \"__dict__\"): # object\n items = sorted(row.__dict__.items())\n\n else:\n raise TypeError(\"Can not infer schema for type: %s\" % type(row))\n\n fields = [StructField(k, _infer_type(v), True) for k, v in items]\n return StructType(fields)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn whether there is NullType in `dt` or not", "output": "def _has_nulltype(dt):\n \"\"\" Return whether there is NullType in `dt` or not \"\"\"\n if isinstance(dt, StructType):\n return any(_has_nulltype(f.dataType) for f in dt.fields)\n elif isinstance(dt, ArrayType):\n return _has_nulltype((dt.elementType))\n elif isinstance(dt, MapType):\n return _has_nulltype(dt.keyType) or _has_nulltype(dt.valueType)\n else:\n return isinstance(dt, NullType)" }, { "instruction": "Write or improve a Python function based on this description:\n\nCreate a converter to drop the names of fields in obj", "output": "def _create_converter(dataType):\n \"\"\"Create a converter to drop the names of fields in obj \"\"\"\n if not _need_converter(dataType):\n return lambda x: x\n\n if isinstance(dataType, ArrayType):\n conv = _create_converter(dataType.elementType)\n return lambda row: [conv(v) for v in row]\n\n elif isinstance(dataType, MapType):\n kconv = _create_converter(dataType.keyType)\n vconv = _create_converter(dataType.valueType)\n return lambda row: dict((kconv(k), vconv(v)) for k, v in row.items())\n\n elif isinstance(dataType, NullType):\n return lambda x: None\n\n elif not isinstance(dataType, StructType):\n return lambda x: x\n\n # dataType must be StructType\n names = [f.name for f in dataType.fields]\n converters = [_create_converter(f.dataType) for f in dataType.fields]\n convert_fields = any(_need_converter(f.dataType) for f in dataType.fields)\n\n def convert_struct(obj):\n if obj is None:\n return\n\n if isinstance(obj, (tuple, list)):\n if convert_fields:\n return tuple(conv(v) for v, conv in zip(obj, converters))\n else:\n return tuple(obj)\n\n if isinstance(obj, dict):\n d = obj\n elif hasattr(obj, \"__dict__\"): # object\n d = obj.__dict__\n else:\n raise TypeError(\"Unexpected obj type: %s\" % type(obj))\n\n if convert_fields:\n return tuple([conv(d.get(name)) for name, conv in zip(names, converters)])\n else:\n return tuple([d.get(name) for name in names])\n\n return convert_struct" }, { "instruction": "Write or improve a Python function based on this description:\n\nMake a verifier that checks the type of obj against dataType and raises a TypeError if they do\n not match.\n\n This verifier also checks the value of obj against datatype and raises a ValueError if it's not\n within the allowed range, e.g. using 128 as ByteType will overflow. Note that, Python float is\n not checked, so it will become infinity when cast to Java float if it overflows.\n\n >>> _make_type_verifier(StructType([]))(None)\n >>> _make_type_verifier(StringType())(\"\")\n >>> _make_type_verifier(LongType())(0)\n >>> _make_type_verifier(ArrayType(ShortType()))(list(range(3)))\n >>> _make_type_verifier(ArrayType(StringType()))(set()) # doctest: +IGNORE_EXCEPTION_DETAIL\n Traceback (most recent call last):\n ...\n TypeError:...\n >>> _make_type_verifier(MapType(StringType(), IntegerType()))({})\n >>> _make_type_verifier(StructType([]))(())\n >>> _make_type_verifier(StructType([]))([])\n >>> _make_type_verifier(StructType([]))([1]) # doctest: +IGNORE_EXCEPTION_DETAIL\n Traceback (most recent call last):\n ...\n ValueError:...\n >>> # Check if numeric values are within the allowed range.\n >>> _make_type_verifier(ByteType())(12)\n >>> _make_type_verifier(ByteType())(1234) # doctest: +IGNORE_EXCEPTION_DETAIL\n Traceback (most recent call last):\n ...\n ValueError:...\n >>> _make_type_verifier(ByteType(), False)(None) # doctest: +IGNORE_EXCEPTION_DETAIL\n Traceback (most recent call last):\n ...\n ValueError:...\n >>> _make_type_verifier(\n ... ArrayType(ShortType(), False))([1, None]) # doctest: +IGNORE_EXCEPTION_DETAIL\n Traceback (most recent call last):\n ...\n ValueError:...\n >>> _make_type_verifier(MapType(StringType(), IntegerType()))({None: 1})\n Traceback (most recent call last):\n ...\n ValueError:...\n >>> schema = StructType().add(\"a\", IntegerType()).add(\"b\", StringType(), False)\n >>> _make_type_verifier(schema)((1, None)) # doctest: +IGNORE_EXCEPTION_DETAIL\n Traceback (most recent call last):\n ...\n ValueError:...", "output": "def _make_type_verifier(dataType, nullable=True, name=None):\n \"\"\"\n Make a verifier that checks the type of obj against dataType and raises a TypeError if they do\n not match.\n\n This verifier also checks the value of obj against datatype and raises a ValueError if it's not\n within the allowed range, e.g. using 128 as ByteType will overflow. Note that, Python float is\n not checked, so it will become infinity when cast to Java float if it overflows.\n\n >>> _make_type_verifier(StructType([]))(None)\n >>> _make_type_verifier(StringType())(\"\")\n >>> _make_type_verifier(LongType())(0)\n >>> _make_type_verifier(ArrayType(ShortType()))(list(range(3)))\n >>> _make_type_verifier(ArrayType(StringType()))(set()) # doctest: +IGNORE_EXCEPTION_DETAIL\n Traceback (most recent call last):\n ...\n TypeError:...\n >>> _make_type_verifier(MapType(StringType(), IntegerType()))({})\n >>> _make_type_verifier(StructType([]))(())\n >>> _make_type_verifier(StructType([]))([])\n >>> _make_type_verifier(StructType([]))([1]) # doctest: +IGNORE_EXCEPTION_DETAIL\n Traceback (most recent call last):\n ...\n ValueError:...\n >>> # Check if numeric values are within the allowed range.\n >>> _make_type_verifier(ByteType())(12)\n >>> _make_type_verifier(ByteType())(1234) # doctest: +IGNORE_EXCEPTION_DETAIL\n Traceback (most recent call last):\n ...\n ValueError:...\n >>> _make_type_verifier(ByteType(), False)(None) # doctest: +IGNORE_EXCEPTION_DETAIL\n Traceback (most recent call last):\n ...\n ValueError:...\n >>> _make_type_verifier(\n ... ArrayType(ShortType(), False))([1, None]) # doctest: +IGNORE_EXCEPTION_DETAIL\n Traceback (most recent call last):\n ...\n ValueError:...\n >>> _make_type_verifier(MapType(StringType(), IntegerType()))({None: 1})\n Traceback (most recent call last):\n ...\n ValueError:...\n >>> schema = StructType().add(\"a\", IntegerType()).add(\"b\", StringType(), False)\n >>> _make_type_verifier(schema)((1, None)) # doctest: +IGNORE_EXCEPTION_DETAIL\n Traceback (most recent call last):\n ...\n ValueError:...\n \"\"\"\n\n if name is None:\n new_msg = lambda msg: msg\n new_name = lambda n: \"field %s\" % n\n else:\n new_msg = lambda msg: \"%s: %s\" % (name, msg)\n new_name = lambda n: \"field %s in %s\" % (n, name)\n\n def verify_nullability(obj):\n if obj is None:\n if nullable:\n return True\n else:\n raise ValueError(new_msg(\"This field is not nullable, but got None\"))\n else:\n return False\n\n _type = type(dataType)\n\n def assert_acceptable_types(obj):\n assert _type in _acceptable_types, \\\n new_msg(\"unknown datatype: %s for object %r\" % (dataType, obj))\n\n def verify_acceptable_types(obj):\n # subclass of them can not be fromInternal in JVM\n if type(obj) not in _acceptable_types[_type]:\n raise TypeError(new_msg(\"%s can not accept object %r in type %s\"\n % (dataType, obj, type(obj))))\n\n if isinstance(dataType, StringType):\n # StringType can work with any types\n verify_value = lambda _: _\n\n elif isinstance(dataType, UserDefinedType):\n verifier = _make_type_verifier(dataType.sqlType(), name=name)\n\n def verify_udf(obj):\n if not (hasattr(obj, '__UDT__') and obj.__UDT__ == dataType):\n raise ValueError(new_msg(\"%r is not an instance of type %r\" % (obj, dataType)))\n verifier(dataType.toInternal(obj))\n\n verify_value = verify_udf\n\n elif isinstance(dataType, ByteType):\n def verify_byte(obj):\n assert_acceptable_types(obj)\n verify_acceptable_types(obj)\n if obj < -128 or obj > 127:\n raise ValueError(new_msg(\"object of ByteType out of range, got: %s\" % obj))\n\n verify_value = verify_byte\n\n elif isinstance(dataType, ShortType):\n def verify_short(obj):\n assert_acceptable_types(obj)\n verify_acceptable_types(obj)\n if obj < -32768 or obj > 32767:\n raise ValueError(new_msg(\"object of ShortType out of range, got: %s\" % obj))\n\n verify_value = verify_short\n\n elif isinstance(dataType, IntegerType):\n def verify_integer(obj):\n assert_acceptable_types(obj)\n verify_acceptable_types(obj)\n if obj < -2147483648 or obj > 2147483647:\n raise ValueError(\n new_msg(\"object of IntegerType out of range, got: %s\" % obj))\n\n verify_value = verify_integer\n\n elif isinstance(dataType, ArrayType):\n element_verifier = _make_type_verifier(\n dataType.elementType, dataType.containsNull, name=\"element in array %s\" % name)\n\n def verify_array(obj):\n assert_acceptable_types(obj)\n verify_acceptable_types(obj)\n for i in obj:\n element_verifier(i)\n\n verify_value = verify_array\n\n elif isinstance(dataType, MapType):\n key_verifier = _make_type_verifier(dataType.keyType, False, name=\"key of map %s\" % name)\n value_verifier = _make_type_verifier(\n dataType.valueType, dataType.valueContainsNull, name=\"value of map %s\" % name)\n\n def verify_map(obj):\n assert_acceptable_types(obj)\n verify_acceptable_types(obj)\n for k, v in obj.items():\n key_verifier(k)\n value_verifier(v)\n\n verify_value = verify_map\n\n elif isinstance(dataType, StructType):\n verifiers = []\n for f in dataType.fields:\n verifier = _make_type_verifier(f.dataType, f.nullable, name=new_name(f.name))\n verifiers.append((f.name, verifier))\n\n def verify_struct(obj):\n assert_acceptable_types(obj)\n\n if isinstance(obj, dict):\n for f, verifier in verifiers:\n verifier(obj.get(f))\n elif isinstance(obj, Row) and getattr(obj, \"__from_dict__\", False):\n # the order in obj could be different than dataType.fields\n for f, verifier in verifiers:\n verifier(obj[f])\n elif isinstance(obj, (tuple, list)):\n if len(obj) != len(verifiers):\n raise ValueError(\n new_msg(\"Length of object (%d) does not match with \"\n \"length of fields (%d)\" % (len(obj), len(verifiers))))\n for v, (_, verifier) in zip(obj, verifiers):\n verifier(v)\n elif hasattr(obj, \"__dict__\"):\n d = obj.__dict__\n for f, verifier in verifiers:\n verifier(d.get(f))\n else:\n raise TypeError(new_msg(\"StructType can not accept object %r in type %s\"\n % (obj, type(obj))))\n verify_value = verify_struct\n\n else:\n def verify_default(obj):\n assert_acceptable_types(obj)\n verify_acceptable_types(obj)\n\n verify_value = verify_default\n\n def verify(obj):\n if not verify_nullability(obj):\n verify_value(obj)\n\n return verify" }, { "instruction": "Write or improve a Python function based on this description:\n\nConvert Spark data type to pyarrow type", "output": "def to_arrow_type(dt):\n \"\"\" Convert Spark data type to pyarrow type\n \"\"\"\n import pyarrow as pa\n if type(dt) == BooleanType:\n arrow_type = pa.bool_()\n elif type(dt) == ByteType:\n arrow_type = pa.int8()\n elif type(dt) == ShortType:\n arrow_type = pa.int16()\n elif type(dt) == IntegerType:\n arrow_type = pa.int32()\n elif type(dt) == LongType:\n arrow_type = pa.int64()\n elif type(dt) == FloatType:\n arrow_type = pa.float32()\n elif type(dt) == DoubleType:\n arrow_type = pa.float64()\n elif type(dt) == DecimalType:\n arrow_type = pa.decimal128(dt.precision, dt.scale)\n elif type(dt) == StringType:\n arrow_type = pa.string()\n elif type(dt) == BinaryType:\n arrow_type = pa.binary()\n elif type(dt) == DateType:\n arrow_type = pa.date32()\n elif type(dt) == TimestampType:\n # Timestamps should be in UTC, JVM Arrow timestamps require a timezone to be read\n arrow_type = pa.timestamp('us', tz='UTC')\n elif type(dt) == ArrayType:\n if type(dt.elementType) in [StructType, TimestampType]:\n raise TypeError(\"Unsupported type in conversion to Arrow: \" + str(dt))\n arrow_type = pa.list_(to_arrow_type(dt.elementType))\n elif type(dt) == StructType:\n if any(type(field.dataType) == StructType for field in dt):\n raise TypeError(\"Nested StructType not supported in conversion to Arrow\")\n fields = [pa.field(field.name, to_arrow_type(field.dataType), nullable=field.nullable)\n for field in dt]\n arrow_type = pa.struct(fields)\n else:\n raise TypeError(\"Unsupported type in conversion to Arrow: \" + str(dt))\n return arrow_type" }, { "instruction": "Write or improve a Python function based on this description:\n\nConvert a schema from Spark to Arrow", "output": "def to_arrow_schema(schema):\n \"\"\" Convert a schema from Spark to Arrow\n \"\"\"\n import pyarrow as pa\n fields = [pa.field(field.name, to_arrow_type(field.dataType), nullable=field.nullable)\n for field in schema]\n return pa.schema(fields)" }, { "instruction": "Write or improve a Python function based on this description:\n\nConvert pyarrow type to Spark data type.", "output": "def from_arrow_type(at):\n \"\"\" Convert pyarrow type to Spark data type.\n \"\"\"\n import pyarrow.types as types\n if types.is_boolean(at):\n spark_type = BooleanType()\n elif types.is_int8(at):\n spark_type = ByteType()\n elif types.is_int16(at):\n spark_type = ShortType()\n elif types.is_int32(at):\n spark_type = IntegerType()\n elif types.is_int64(at):\n spark_type = LongType()\n elif types.is_float32(at):\n spark_type = FloatType()\n elif types.is_float64(at):\n spark_type = DoubleType()\n elif types.is_decimal(at):\n spark_type = DecimalType(precision=at.precision, scale=at.scale)\n elif types.is_string(at):\n spark_type = StringType()\n elif types.is_binary(at):\n spark_type = BinaryType()\n elif types.is_date32(at):\n spark_type = DateType()\n elif types.is_timestamp(at):\n spark_type = TimestampType()\n elif types.is_list(at):\n if types.is_timestamp(at.value_type):\n raise TypeError(\"Unsupported type in conversion from Arrow: \" + str(at))\n spark_type = ArrayType(from_arrow_type(at.value_type))\n elif types.is_struct(at):\n if any(types.is_struct(field.type) for field in at):\n raise TypeError(\"Nested StructType not supported in conversion from Arrow: \" + str(at))\n return StructType(\n [StructField(field.name, from_arrow_type(field.type), nullable=field.nullable)\n for field in at])\n else:\n raise TypeError(\"Unsupported type in conversion from Arrow: \" + str(at))\n return spark_type" }, { "instruction": "Write or improve a Python function based on this description:\n\nConvert schema from Arrow to Spark.", "output": "def from_arrow_schema(arrow_schema):\n \"\"\" Convert schema from Arrow to Spark.\n \"\"\"\n return StructType(\n [StructField(field.name, from_arrow_type(field.type), nullable=field.nullable)\n for field in arrow_schema])" }, { "instruction": "Write or improve a Python function based on this description:\n\nConvert timezone aware timestamps to timezone-naive in the specified timezone or local timezone.\n\n If the input series is not a timestamp series, then the same series is returned. If the input\n series is a timestamp series, then a converted series is returned.\n\n :param s: pandas.Series\n :param timezone: the timezone to convert. if None then use local timezone\n :return pandas.Series that have been converted to tz-naive", "output": "def _check_series_localize_timestamps(s, timezone):\n \"\"\"\n Convert timezone aware timestamps to timezone-naive in the specified timezone or local timezone.\n\n If the input series is not a timestamp series, then the same series is returned. If the input\n series is a timestamp series, then a converted series is returned.\n\n :param s: pandas.Series\n :param timezone: the timezone to convert. if None then use local timezone\n :return pandas.Series that have been converted to tz-naive\n \"\"\"\n from pyspark.sql.utils import require_minimum_pandas_version\n require_minimum_pandas_version()\n\n from pandas.api.types import is_datetime64tz_dtype\n tz = timezone or _get_local_timezone()\n # TODO: handle nested timestamps, such as ArrayType(TimestampType())?\n if is_datetime64tz_dtype(s.dtype):\n return s.dt.tz_convert(tz).dt.tz_localize(None)\n else:\n return s" }, { "instruction": "Write or improve a Python function based on this description:\n\nConvert timezone aware timestamps to timezone-naive in the specified timezone or local timezone\n\n :param pdf: pandas.DataFrame\n :param timezone: the timezone to convert. if None then use local timezone\n :return pandas.DataFrame where any timezone aware columns have been converted to tz-naive", "output": "def _check_dataframe_localize_timestamps(pdf, timezone):\n \"\"\"\n Convert timezone aware timestamps to timezone-naive in the specified timezone or local timezone\n\n :param pdf: pandas.DataFrame\n :param timezone: the timezone to convert. if None then use local timezone\n :return pandas.DataFrame where any timezone aware columns have been converted to tz-naive\n \"\"\"\n from pyspark.sql.utils import require_minimum_pandas_version\n require_minimum_pandas_version()\n\n for column, series in pdf.iteritems():\n pdf[column] = _check_series_localize_timestamps(series, timezone)\n return pdf" }, { "instruction": "Write or improve a Python function based on this description:\n\nConvert a tz-naive timestamp in the specified timezone or local timezone to UTC normalized for\n Spark internal storage\n\n :param s: a pandas.Series\n :param timezone: the timezone to convert. if None then use local timezone\n :return pandas.Series where if it is a timestamp, has been UTC normalized without a time zone", "output": "def _check_series_convert_timestamps_internal(s, timezone):\n \"\"\"\n Convert a tz-naive timestamp in the specified timezone or local timezone to UTC normalized for\n Spark internal storage\n\n :param s: a pandas.Series\n :param timezone: the timezone to convert. if None then use local timezone\n :return pandas.Series where if it is a timestamp, has been UTC normalized without a time zone\n \"\"\"\n from pyspark.sql.utils import require_minimum_pandas_version\n require_minimum_pandas_version()\n\n from pandas.api.types import is_datetime64_dtype, is_datetime64tz_dtype\n # TODO: handle nested timestamps, such as ArrayType(TimestampType())?\n if is_datetime64_dtype(s.dtype):\n # When tz_localize a tz-naive timestamp, the result is ambiguous if the tz-naive\n # timestamp is during the hour when the clock is adjusted backward during due to\n # daylight saving time (dst).\n # E.g., for America/New_York, the clock is adjusted backward on 2015-11-01 2:00 to\n # 2015-11-01 1:00 from dst-time to standard time, and therefore, when tz_localize\n # a tz-naive timestamp 2015-11-01 1:30 with America/New_York timezone, it can be either\n # dst time (2015-01-01 1:30-0400) or standard time (2015-11-01 1:30-0500).\n #\n # Here we explicit choose to use standard time. This matches the default behavior of\n # pytz.\n #\n # Here are some code to help understand this behavior:\n # >>> import datetime\n # >>> import pandas as pd\n # >>> import pytz\n # >>>\n # >>> t = datetime.datetime(2015, 11, 1, 1, 30)\n # >>> ts = pd.Series([t])\n # >>> tz = pytz.timezone('America/New_York')\n # >>>\n # >>> ts.dt.tz_localize(tz, ambiguous=True)\n # 0 2015-11-01 01:30:00-04:00\n # dtype: datetime64[ns, America/New_York]\n # >>>\n # >>> ts.dt.tz_localize(tz, ambiguous=False)\n # 0 2015-11-01 01:30:00-05:00\n # dtype: datetime64[ns, America/New_York]\n # >>>\n # >>> str(tz.localize(t))\n # '2015-11-01 01:30:00-05:00'\n tz = timezone or _get_local_timezone()\n return s.dt.tz_localize(tz, ambiguous=False).dt.tz_convert('UTC')\n elif is_datetime64tz_dtype(s.dtype):\n return s.dt.tz_convert('UTC')\n else:\n return s" }, { "instruction": "Write or improve a Python function based on this description:\n\nConvert timestamp to timezone-naive in the specified timezone or local timezone\n\n :param s: a pandas.Series\n :param from_timezone: the timezone to convert from. if None then use local timezone\n :param to_timezone: the timezone to convert to. if None then use local timezone\n :return pandas.Series where if it is a timestamp, has been converted to tz-naive", "output": "def _check_series_convert_timestamps_localize(s, from_timezone, to_timezone):\n \"\"\"\n Convert timestamp to timezone-naive in the specified timezone or local timezone\n\n :param s: a pandas.Series\n :param from_timezone: the timezone to convert from. if None then use local timezone\n :param to_timezone: the timezone to convert to. if None then use local timezone\n :return pandas.Series where if it is a timestamp, has been converted to tz-naive\n \"\"\"\n from pyspark.sql.utils import require_minimum_pandas_version\n require_minimum_pandas_version()\n\n import pandas as pd\n from pandas.api.types import is_datetime64tz_dtype, is_datetime64_dtype\n from_tz = from_timezone or _get_local_timezone()\n to_tz = to_timezone or _get_local_timezone()\n # TODO: handle nested timestamps, such as ArrayType(TimestampType())?\n if is_datetime64tz_dtype(s.dtype):\n return s.dt.tz_convert(to_tz).dt.tz_localize(None)\n elif is_datetime64_dtype(s.dtype) and from_tz != to_tz:\n # `s.dt.tz_localize('tzlocal()')` doesn't work properly when including NaT.\n return s.apply(\n lambda ts: ts.tz_localize(from_tz, ambiguous=False).tz_convert(to_tz).tz_localize(None)\n if ts is not pd.NaT else pd.NaT)\n else:\n return s" }, { "instruction": "Write or improve a Python function based on this description:\n\nConstruct a StructType by adding new elements to it to define the schema. The method accepts\n either:\n\n a) A single parameter which is a StructField object.\n b) Between 2 and 4 parameters as (name, data_type, nullable (optional),\n metadata(optional). The data_type parameter may be either a String or a\n DataType object.\n\n >>> struct1 = StructType().add(\"f1\", StringType(), True).add(\"f2\", StringType(), True, None)\n >>> struct2 = StructType([StructField(\"f1\", StringType(), True), \\\\\n ... StructField(\"f2\", StringType(), True, None)])\n >>> struct1 == struct2\n True\n >>> struct1 = StructType().add(StructField(\"f1\", StringType(), True))\n >>> struct2 = StructType([StructField(\"f1\", StringType(), True)])\n >>> struct1 == struct2\n True\n >>> struct1 = StructType().add(\"f1\", \"string\", True)\n >>> struct2 = StructType([StructField(\"f1\", StringType(), True)])\n >>> struct1 == struct2\n True\n\n :param field: Either the name of the field or a StructField object\n :param data_type: If present, the DataType of the StructField to create\n :param nullable: Whether the field to add should be nullable (default True)\n :param metadata: Any additional metadata (default None)\n :return: a new updated StructType", "output": "def add(self, field, data_type=None, nullable=True, metadata=None):\n \"\"\"\n Construct a StructType by adding new elements to it to define the schema. The method accepts\n either:\n\n a) A single parameter which is a StructField object.\n b) Between 2 and 4 parameters as (name, data_type, nullable (optional),\n metadata(optional). The data_type parameter may be either a String or a\n DataType object.\n\n >>> struct1 = StructType().add(\"f1\", StringType(), True).add(\"f2\", StringType(), True, None)\n >>> struct2 = StructType([StructField(\"f1\", StringType(), True), \\\\\n ... StructField(\"f2\", StringType(), True, None)])\n >>> struct1 == struct2\n True\n >>> struct1 = StructType().add(StructField(\"f1\", StringType(), True))\n >>> struct2 = StructType([StructField(\"f1\", StringType(), True)])\n >>> struct1 == struct2\n True\n >>> struct1 = StructType().add(\"f1\", \"string\", True)\n >>> struct2 = StructType([StructField(\"f1\", StringType(), True)])\n >>> struct1 == struct2\n True\n\n :param field: Either the name of the field or a StructField object\n :param data_type: If present, the DataType of the StructField to create\n :param nullable: Whether the field to add should be nullable (default True)\n :param metadata: Any additional metadata (default None)\n :return: a new updated StructType\n \"\"\"\n if isinstance(field, StructField):\n self.fields.append(field)\n self.names.append(field.name)\n else:\n if isinstance(field, str) and data_type is None:\n raise ValueError(\"Must specify DataType if passing name of struct_field to create.\")\n\n if isinstance(data_type, str):\n data_type_f = _parse_datatype_json_value(data_type)\n else:\n data_type_f = data_type\n self.fields.append(StructField(field, data_type_f, nullable, metadata))\n self.names.append(field)\n # Precalculated list of fields that need conversion with fromInternal/toInternal functions\n self._needConversion = [f.needConversion() for f in self]\n self._needSerializeAnyField = any(self._needConversion)\n return self" }, { "instruction": "Write or improve a Python function based on this description:\n\nCache the sqlType() into class, because it's heavy used in `toInternal`.", "output": "def _cachedSqlType(cls):\n \"\"\"\n Cache the sqlType() into class, because it's heavy used in `toInternal`.\n \"\"\"\n if not hasattr(cls, \"_cached_sql_type\"):\n cls._cached_sql_type = cls.sqlType()\n return cls._cached_sql_type" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn as an dict\n\n :param recursive: turns the nested Row as dict (default: False).\n\n >>> Row(name=\"Alice\", age=11).asDict() == {'name': 'Alice', 'age': 11}\n True\n >>> row = Row(key=1, value=Row(name='a', age=2))\n >>> row.asDict() == {'key': 1, 'value': Row(age=2, name='a')}\n True\n >>> row.asDict(True) == {'key': 1, 'value': {'name': 'a', 'age': 2}}\n True", "output": "def asDict(self, recursive=False):\n \"\"\"\n Return as an dict\n\n :param recursive: turns the nested Row as dict (default: False).\n\n >>> Row(name=\"Alice\", age=11).asDict() == {'name': 'Alice', 'age': 11}\n True\n >>> row = Row(key=1, value=Row(name='a', age=2))\n >>> row.asDict() == {'key': 1, 'value': Row(age=2, name='a')}\n True\n >>> row.asDict(True) == {'key': 1, 'value': {'name': 'a', 'age': 2}}\n True\n \"\"\"\n if not hasattr(self, \"__fields__\"):\n raise TypeError(\"Cannot convert a Row class into dict\")\n\n if recursive:\n def conv(obj):\n if isinstance(obj, Row):\n return obj.asDict(True)\n elif isinstance(obj, list):\n return [conv(o) for o in obj]\n elif isinstance(obj, dict):\n return dict((k, conv(v)) for k, v in obj.items())\n else:\n return obj\n return dict(zip(self.__fields__, (conv(o) for o in self)))\n else:\n return dict(zip(self.__fields__, self))" }, { "instruction": "Write or improve a Python function based on this description:\n\nGets summary (e.g. residuals, mse, r-squared ) of model on\n training set. An exception is thrown if\n `trainingSummary is None`.", "output": "def summary(self):\n \"\"\"\n Gets summary (e.g. residuals, mse, r-squared ) of model on\n training set. An exception is thrown if\n `trainingSummary is None`.\n \"\"\"\n if self.hasSummary:\n return LinearRegressionTrainingSummary(super(LinearRegressionModel, self).summary)\n else:\n raise RuntimeError(\"No training summary available for this %s\" %\n self.__class__.__name__)" }, { "instruction": "Write or improve a Python function based on this description:\n\nEvaluates the model on a test dataset.\n\n :param dataset:\n Test dataset to evaluate model on, where dataset is an\n instance of :py:class:`pyspark.sql.DataFrame`", "output": "def evaluate(self, dataset):\n \"\"\"\n Evaluates the model on a test dataset.\n\n :param dataset:\n Test dataset to evaluate model on, where dataset is an\n instance of :py:class:`pyspark.sql.DataFrame`\n \"\"\"\n if not isinstance(dataset, DataFrame):\n raise ValueError(\"dataset must be a DataFrame but got %s.\" % type(dataset))\n java_lr_summary = self._call_java(\"evaluate\", dataset)\n return LinearRegressionSummary(java_lr_summary)" }, { "instruction": "Write or improve a Python function based on this description:\n\nGets summary (e.g. residuals, deviance, pValues) of model on\n training set. An exception is thrown if\n `trainingSummary is None`.", "output": "def summary(self):\n \"\"\"\n Gets summary (e.g. residuals, deviance, pValues) of model on\n training set. An exception is thrown if\n `trainingSummary is None`.\n \"\"\"\n if self.hasSummary:\n return GeneralizedLinearRegressionTrainingSummary(\n super(GeneralizedLinearRegressionModel, self).summary)\n else:\n raise RuntimeError(\"No training summary available for this %s\" %\n self.__class__.__name__)" }, { "instruction": "Write or improve a Python function based on this description:\n\nEvaluates the model on a test dataset.\n\n :param dataset:\n Test dataset to evaluate model on, where dataset is an\n instance of :py:class:`pyspark.sql.DataFrame`", "output": "def evaluate(self, dataset):\n \"\"\"\n Evaluates the model on a test dataset.\n\n :param dataset:\n Test dataset to evaluate model on, where dataset is an\n instance of :py:class:`pyspark.sql.DataFrame`\n \"\"\"\n if not isinstance(dataset, DataFrame):\n raise ValueError(\"dataset must be a DataFrame but got %s.\" % type(dataset))\n java_glr_summary = self._call_java(\"evaluate\", dataset)\n return GeneralizedLinearRegressionSummary(java_glr_summary)" }, { "instruction": "Write or improve a Python function based on this description:\n\nGet all the directories", "output": "def _get_local_dirs(sub):\n \"\"\" Get all the directories \"\"\"\n path = os.environ.get(\"SPARK_LOCAL_DIRS\", \"/tmp\")\n dirs = path.split(\",\")\n if len(dirs) > 1:\n # different order in different processes and instances\n rnd = random.Random(os.getpid() + id(dirs))\n random.shuffle(dirs, rnd.random)\n return [os.path.join(d, \"python\", str(os.getpid()), sub) for d in dirs]" }, { "instruction": "Write or improve a Python function based on this description:\n\nChoose one directory for spill by number n", "output": "def _get_spill_dir(self, n):\n \"\"\" Choose one directory for spill by number n \"\"\"\n return os.path.join(self.localdirs[n % len(self.localdirs)], str(n))" }, { "instruction": "Write or improve a Python function based on this description:\n\nCombine the items by creator and combiner", "output": "def mergeValues(self, iterator):\n \"\"\" Combine the items by creator and combiner \"\"\"\n # speedup attribute lookup\n creator, comb = self.agg.createCombiner, self.agg.mergeValue\n c, data, pdata, hfun, batch = 0, self.data, self.pdata, self._partition, self.batch\n limit = self.memory_limit\n\n for k, v in iterator:\n d = pdata[hfun(k)] if pdata else data\n d[k] = comb(d[k], v) if k in d else creator(v)\n\n c += 1\n if c >= batch:\n if get_used_memory() >= limit:\n self._spill()\n limit = self._next_limit()\n batch /= 2\n c = 0\n else:\n batch *= 1.5\n\n if get_used_memory() >= limit:\n self._spill()" }, { "instruction": "Write or improve a Python function based on this description:\n\nMerge (K,V) pair by mergeCombiner", "output": "def mergeCombiners(self, iterator, limit=None):\n \"\"\" Merge (K,V) pair by mergeCombiner \"\"\"\n if limit is None:\n limit = self.memory_limit\n # speedup attribute lookup\n comb, hfun, objsize = self.agg.mergeCombiners, self._partition, self._object_size\n c, data, pdata, batch = 0, self.data, self.pdata, self.batch\n for k, v in iterator:\n d = pdata[hfun(k)] if pdata else data\n d[k] = comb(d[k], v) if k in d else v\n if not limit:\n continue\n\n c += objsize(v)\n if c > batch:\n if get_used_memory() > limit:\n self._spill()\n limit = self._next_limit()\n batch /= 2\n c = 0\n else:\n batch *= 1.5\n\n if limit and get_used_memory() >= limit:\n self._spill()" }, { "instruction": "Write or improve a Python function based on this description:\n\ndump already partitioned data into disks.\n\n It will dump the data in batch for better performance.", "output": "def _spill(self):\n \"\"\"\n dump already partitioned data into disks.\n\n It will dump the data in batch for better performance.\n \"\"\"\n global MemoryBytesSpilled, DiskBytesSpilled\n path = self._get_spill_dir(self.spills)\n if not os.path.exists(path):\n os.makedirs(path)\n\n used_memory = get_used_memory()\n if not self.pdata:\n # The data has not been partitioned, it will iterator the\n # dataset once, write them into different files, has no\n # additional memory. It only called when the memory goes\n # above limit at the first time.\n\n # open all the files for writing\n streams = [open(os.path.join(path, str(i)), 'wb')\n for i in range(self.partitions)]\n\n for k, v in self.data.items():\n h = self._partition(k)\n # put one item in batch, make it compatible with load_stream\n # it will increase the memory if dump them in batch\n self.serializer.dump_stream([(k, v)], streams[h])\n\n for s in streams:\n DiskBytesSpilled += s.tell()\n s.close()\n\n self.data.clear()\n self.pdata.extend([{} for i in range(self.partitions)])\n\n else:\n for i in range(self.partitions):\n p = os.path.join(path, str(i))\n with open(p, \"wb\") as f:\n # dump items in batch\n self.serializer.dump_stream(iter(self.pdata[i].items()), f)\n self.pdata[i].clear()\n DiskBytesSpilled += os.path.getsize(p)\n\n self.spills += 1\n gc.collect() # release the memory as much as possible\n MemoryBytesSpilled += max(used_memory - get_used_memory(), 0) << 20" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn all merged items as iterator", "output": "def items(self):\n \"\"\" Return all merged items as iterator \"\"\"\n if not self.pdata and not self.spills:\n return iter(self.data.items())\n return self._external_items()" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn all partitioned items as iterator", "output": "def _external_items(self):\n \"\"\" Return all partitioned items as iterator \"\"\"\n assert not self.data\n if any(self.pdata):\n self._spill()\n # disable partitioning and spilling when merge combiners from disk\n self.pdata = []\n\n try:\n for i in range(self.partitions):\n for v in self._merged_items(i):\n yield v\n self.data.clear()\n\n # remove the merged partition\n for j in range(self.spills):\n path = self._get_spill_dir(j)\n os.remove(os.path.join(path, str(i)))\n finally:\n self._cleanup()" }, { "instruction": "Write or improve a Python function based on this description:\n\nmerge the partitioned items and return the as iterator\n\n If one partition can not be fit in memory, then them will be\n partitioned and merged recursively.", "output": "def _recursive_merged_items(self, index):\n \"\"\"\n merge the partitioned items and return the as iterator\n\n If one partition can not be fit in memory, then them will be\n partitioned and merged recursively.\n \"\"\"\n subdirs = [os.path.join(d, \"parts\", str(index)) for d in self.localdirs]\n m = ExternalMerger(self.agg, self.memory_limit, self.serializer, subdirs,\n self.scale * self.partitions, self.partitions, self.batch)\n m.pdata = [{} for _ in range(self.partitions)]\n limit = self._next_limit()\n\n for j in range(self.spills):\n path = self._get_spill_dir(j)\n p = os.path.join(path, str(index))\n with open(p, 'rb') as f:\n m.mergeCombiners(self.serializer.load_stream(f), 0)\n\n if get_used_memory() > limit:\n m._spill()\n limit = self._next_limit()\n\n return m._external_items()" }, { "instruction": "Write or improve a Python function based on this description:\n\nChoose one directory for spill by number n", "output": "def _get_path(self, n):\n \"\"\" Choose one directory for spill by number n \"\"\"\n d = self.local_dirs[n % len(self.local_dirs)]\n if not os.path.exists(d):\n os.makedirs(d)\n return os.path.join(d, str(n))" }, { "instruction": "Write or improve a Python function based on this description:\n\nSort the elements in iterator, do external sort when the memory\n goes above the limit.", "output": "def sorted(self, iterator, key=None, reverse=False):\n \"\"\"\n Sort the elements in iterator, do external sort when the memory\n goes above the limit.\n \"\"\"\n global MemoryBytesSpilled, DiskBytesSpilled\n batch, limit = 100, self._next_limit()\n chunks, current_chunk = [], []\n iterator = iter(iterator)\n while True:\n # pick elements in batch\n chunk = list(itertools.islice(iterator, batch))\n current_chunk.extend(chunk)\n if len(chunk) < batch:\n break\n\n used_memory = get_used_memory()\n if used_memory > limit:\n # sort them inplace will save memory\n current_chunk.sort(key=key, reverse=reverse)\n path = self._get_path(len(chunks))\n with open(path, 'wb') as f:\n self.serializer.dump_stream(current_chunk, f)\n\n def load(f):\n for v in self.serializer.load_stream(f):\n yield v\n # close the file explicit once we consume all the items\n # to avoid ResourceWarning in Python3\n f.close()\n chunks.append(load(open(path, 'rb')))\n current_chunk = []\n MemoryBytesSpilled += max(used_memory - get_used_memory(), 0) << 20\n DiskBytesSpilled += os.path.getsize(path)\n os.unlink(path) # data will be deleted after close\n\n elif not chunks:\n batch = min(int(batch * 1.5), 10000)\n\n current_chunk.sort(key=key, reverse=reverse)\n if not chunks:\n return current_chunk\n\n if current_chunk:\n chunks.append(iter(current_chunk))\n\n return heapq.merge(chunks, key=key, reverse=reverse)" }, { "instruction": "Write or improve a Python function based on this description:\n\ndump the values into disk", "output": "def _spill(self):\n \"\"\" dump the values into disk \"\"\"\n global MemoryBytesSpilled, DiskBytesSpilled\n if self._file is None:\n self._open_file()\n\n used_memory = get_used_memory()\n pos = self._file.tell()\n self._ser.dump_stream(self.values, self._file)\n self.values = []\n gc.collect()\n DiskBytesSpilled += self._file.tell() - pos\n MemoryBytesSpilled += max(used_memory - get_used_memory(), 0) << 20" }, { "instruction": "Write or improve a Python function based on this description:\n\ndump already partitioned data into disks.", "output": "def _spill(self):\n \"\"\"\n dump already partitioned data into disks.\n \"\"\"\n global MemoryBytesSpilled, DiskBytesSpilled\n path = self._get_spill_dir(self.spills)\n if not os.path.exists(path):\n os.makedirs(path)\n\n used_memory = get_used_memory()\n if not self.pdata:\n # The data has not been partitioned, it will iterator the\n # data once, write them into different files, has no\n # additional memory. It only called when the memory goes\n # above limit at the first time.\n\n # open all the files for writing\n streams = [open(os.path.join(path, str(i)), 'wb')\n for i in range(self.partitions)]\n\n # If the number of keys is small, then the overhead of sort is small\n # sort them before dumping into disks\n self._sorted = len(self.data) < self.SORT_KEY_LIMIT\n if self._sorted:\n self.serializer = self.flattened_serializer()\n for k in sorted(self.data.keys()):\n h = self._partition(k)\n self.serializer.dump_stream([(k, self.data[k])], streams[h])\n else:\n for k, v in self.data.items():\n h = self._partition(k)\n self.serializer.dump_stream([(k, v)], streams[h])\n\n for s in streams:\n DiskBytesSpilled += s.tell()\n s.close()\n\n self.data.clear()\n # self.pdata is cached in `mergeValues` and `mergeCombiners`\n self.pdata.extend([{} for i in range(self.partitions)])\n\n else:\n for i in range(self.partitions):\n p = os.path.join(path, str(i))\n with open(p, \"wb\") as f:\n # dump items in batch\n if self._sorted:\n # sort by key only (stable)\n sorted_items = sorted(self.pdata[i].items(), key=operator.itemgetter(0))\n self.serializer.dump_stream(sorted_items, f)\n else:\n self.serializer.dump_stream(self.pdata[i].items(), f)\n self.pdata[i].clear()\n DiskBytesSpilled += os.path.getsize(p)\n\n self.spills += 1\n gc.collect() # release the memory as much as possible\n MemoryBytesSpilled += max(used_memory - get_used_memory(), 0) << 20" }, { "instruction": "Write or improve a Python function based on this description:\n\nload a partition from disk, then sort and group by key", "output": "def _merge_sorted_items(self, index):\n \"\"\" load a partition from disk, then sort and group by key \"\"\"\n def load_partition(j):\n path = self._get_spill_dir(j)\n p = os.path.join(path, str(index))\n with open(p, 'rb', 65536) as f:\n for v in self.serializer.load_stream(f):\n yield v\n\n disk_items = [load_partition(j) for j in range(self.spills)]\n\n if self._sorted:\n # all the partitions are already sorted\n sorted_items = heapq.merge(disk_items, key=operator.itemgetter(0))\n\n else:\n # Flatten the combined values, so it will not consume huge\n # memory during merging sort.\n ser = self.flattened_serializer()\n sorter = ExternalSorter(self.memory_limit, ser)\n sorted_items = sorter.sorted(itertools.chain(*disk_items),\n key=operator.itemgetter(0))\n return ((k, vs) for k, vs in GroupByKey(sorted_items))" }, { "instruction": "Write or improve a Python function based on this description:\n\nCalled by a worker process after the fork().", "output": "def worker(sock, authenticated):\n \"\"\"\n Called by a worker process after the fork().\n \"\"\"\n signal.signal(SIGHUP, SIG_DFL)\n signal.signal(SIGCHLD, SIG_DFL)\n signal.signal(SIGTERM, SIG_DFL)\n # restore the handler for SIGINT,\n # it's useful for debugging (show the stacktrace before exit)\n signal.signal(SIGINT, signal.default_int_handler)\n\n # Read the socket using fdopen instead of socket.makefile() because the latter\n # seems to be very slow; note that we need to dup() the file descriptor because\n # otherwise writes also cause a seek that makes us miss data on the read side.\n infile = os.fdopen(os.dup(sock.fileno()), \"rb\", 65536)\n outfile = os.fdopen(os.dup(sock.fileno()), \"wb\", 65536)\n\n if not authenticated:\n client_secret = UTF8Deserializer().loads(infile)\n if os.environ[\"PYTHON_WORKER_FACTORY_SECRET\"] == client_secret:\n write_with_length(\"ok\".encode(\"utf-8\"), outfile)\n outfile.flush()\n else:\n write_with_length(\"err\".encode(\"utf-8\"), outfile)\n outfile.flush()\n sock.close()\n return 1\n\n exit_code = 0\n try:\n worker_main(infile, outfile)\n except SystemExit as exc:\n exit_code = compute_real_exit_code(exc.code)\n finally:\n try:\n outfile.flush()\n except Exception:\n pass\n return exit_code" }, { "instruction": "Write or improve a Python function based on this description:\n\nThis function returns consistent hash code for builtin types, especially\n for None and tuple with None.\n\n The algorithm is similar to that one used by CPython 2.7\n\n >>> portable_hash(None)\n 0\n >>> portable_hash((None, 1)) & 0xffffffff\n 219750521", "output": "def portable_hash(x):\n \"\"\"\n This function returns consistent hash code for builtin types, especially\n for None and tuple with None.\n\n The algorithm is similar to that one used by CPython 2.7\n\n >>> portable_hash(None)\n 0\n >>> portable_hash((None, 1)) & 0xffffffff\n 219750521\n \"\"\"\n\n if sys.version_info >= (3, 2, 3) and 'PYTHONHASHSEED' not in os.environ:\n raise Exception(\"Randomness of hash of string should be disabled via PYTHONHASHSEED\")\n\n if x is None:\n return 0\n if isinstance(x, tuple):\n h = 0x345678\n for i in x:\n h ^= portable_hash(i)\n h *= 1000003\n h &= sys.maxsize\n h ^= len(x)\n if h == -1:\n h = -2\n return int(h)\n return hash(x)" }, { "instruction": "Write or improve a Python function based on this description:\n\nParse a memory string in the format supported by Java (e.g. 1g, 200m) and\n return the value in MiB\n\n >>> _parse_memory(\"256m\")\n 256\n >>> _parse_memory(\"2g\")\n 2048", "output": "def _parse_memory(s):\n \"\"\"\n Parse a memory string in the format supported by Java (e.g. 1g, 200m) and\n return the value in MiB\n\n >>> _parse_memory(\"256m\")\n 256\n >>> _parse_memory(\"2g\")\n 2048\n \"\"\"\n units = {'g': 1024, 'm': 1, 't': 1 << 20, 'k': 1.0 / 1024}\n if s[-1].lower() not in units:\n raise ValueError(\"invalid format: \" + s)\n return int(float(s[:-1]) * units[s[-1].lower()])" }, { "instruction": "Write or improve a Python function based on this description:\n\nIgnore the 'u' prefix of string in doc tests, to make it works\n in both python 2 and 3", "output": "def ignore_unicode_prefix(f):\n \"\"\"\n Ignore the 'u' prefix of string in doc tests, to make it works\n in both python 2 and 3\n \"\"\"\n if sys.version >= '3':\n # the representation of unicode string in Python 3 does not have prefix 'u',\n # so remove the prefix 'u' for doc tests\n literal_re = re.compile(r\"(\\W|^)[uU](['])\", re.UNICODE)\n f.__doc__ = literal_re.sub(r'\\1\\2', f.__doc__)\n return f" }, { "instruction": "Write or improve a Python function based on this description:\n\nPersist this RDD with the default storage level (C{MEMORY_ONLY}).", "output": "def cache(self):\n \"\"\"\n Persist this RDD with the default storage level (C{MEMORY_ONLY}).\n \"\"\"\n self.is_cached = True\n self.persist(StorageLevel.MEMORY_ONLY)\n return self" }, { "instruction": "Write or improve a Python function based on this description:\n\nSet this RDD's storage level to persist its values across operations\n after the first time it is computed. This can only be used to assign\n a new storage level if the RDD does not have a storage level set yet.\n If no storage level is specified defaults to (C{MEMORY_ONLY}).\n\n >>> rdd = sc.parallelize([\"b\", \"a\", \"c\"])\n >>> rdd.persist().is_cached\n True", "output": "def persist(self, storageLevel=StorageLevel.MEMORY_ONLY):\n \"\"\"\n Set this RDD's storage level to persist its values across operations\n after the first time it is computed. This can only be used to assign\n a new storage level if the RDD does not have a storage level set yet.\n If no storage level is specified defaults to (C{MEMORY_ONLY}).\n\n >>> rdd = sc.parallelize([\"b\", \"a\", \"c\"])\n >>> rdd.persist().is_cached\n True\n \"\"\"\n self.is_cached = True\n javaStorageLevel = self.ctx._getJavaStorageLevel(storageLevel)\n self._jrdd.persist(javaStorageLevel)\n return self" }, { "instruction": "Write or improve a Python function based on this description:\n\nMark the RDD as non-persistent, and remove all blocks for it from\n memory and disk.\n\n .. versionchanged:: 3.0.0\n Added optional argument `blocking` to specify whether to block until all\n blocks are deleted.", "output": "def unpersist(self, blocking=False):\n \"\"\"\n Mark the RDD as non-persistent, and remove all blocks for it from\n memory and disk.\n\n .. versionchanged:: 3.0.0\n Added optional argument `blocking` to specify whether to block until all\n blocks are deleted.\n \"\"\"\n self.is_cached = False\n self._jrdd.unpersist(blocking)\n return self" }, { "instruction": "Write or improve a Python function based on this description:\n\nGets the name of the file to which this RDD was checkpointed\n\n Not defined if RDD is checkpointed locally.", "output": "def getCheckpointFile(self):\n \"\"\"\n Gets the name of the file to which this RDD was checkpointed\n\n Not defined if RDD is checkpointed locally.\n \"\"\"\n checkpointFile = self._jrdd.rdd().getCheckpointFile()\n if checkpointFile.isDefined():\n return checkpointFile.get()" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn a new RDD by applying a function to each element of this RDD.\n\n >>> rdd = sc.parallelize([\"b\", \"a\", \"c\"])\n >>> sorted(rdd.map(lambda x: (x, 1)).collect())\n [('a', 1), ('b', 1), ('c', 1)]", "output": "def map(self, f, preservesPartitioning=False):\n \"\"\"\n Return a new RDD by applying a function to each element of this RDD.\n\n >>> rdd = sc.parallelize([\"b\", \"a\", \"c\"])\n >>> sorted(rdd.map(lambda x: (x, 1)).collect())\n [('a', 1), ('b', 1), ('c', 1)]\n \"\"\"\n def func(_, iterator):\n return map(fail_on_stopiteration(f), iterator)\n return self.mapPartitionsWithIndex(func, preservesPartitioning)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn a new RDD by first applying a function to all elements of this\n RDD, and then flattening the results.\n\n >>> rdd = sc.parallelize([2, 3, 4])\n >>> sorted(rdd.flatMap(lambda x: range(1, x)).collect())\n [1, 1, 1, 2, 2, 3]\n >>> sorted(rdd.flatMap(lambda x: [(x, x), (x, x)]).collect())\n [(2, 2), (2, 2), (3, 3), (3, 3), (4, 4), (4, 4)]", "output": "def flatMap(self, f, preservesPartitioning=False):\n \"\"\"\n Return a new RDD by first applying a function to all elements of this\n RDD, and then flattening the results.\n\n >>> rdd = sc.parallelize([2, 3, 4])\n >>> sorted(rdd.flatMap(lambda x: range(1, x)).collect())\n [1, 1, 1, 2, 2, 3]\n >>> sorted(rdd.flatMap(lambda x: [(x, x), (x, x)]).collect())\n [(2, 2), (2, 2), (3, 3), (3, 3), (4, 4), (4, 4)]\n \"\"\"\n def func(s, iterator):\n return chain.from_iterable(map(fail_on_stopiteration(f), iterator))\n return self.mapPartitionsWithIndex(func, preservesPartitioning)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn a new RDD by applying a function to each partition of this RDD.\n\n >>> rdd = sc.parallelize([1, 2, 3, 4], 2)\n >>> def f(iterator): yield sum(iterator)\n >>> rdd.mapPartitions(f).collect()\n [3, 7]", "output": "def mapPartitions(self, f, preservesPartitioning=False):\n \"\"\"\n Return a new RDD by applying a function to each partition of this RDD.\n\n >>> rdd = sc.parallelize([1, 2, 3, 4], 2)\n >>> def f(iterator): yield sum(iterator)\n >>> rdd.mapPartitions(f).collect()\n [3, 7]\n \"\"\"\n def func(s, iterator):\n return f(iterator)\n return self.mapPartitionsWithIndex(func, preservesPartitioning)" }, { "instruction": "Write or improve a Python function based on this description:\n\nDeprecated: use mapPartitionsWithIndex instead.\n\n Return a new RDD by applying a function to each partition of this RDD,\n while tracking the index of the original partition.\n\n >>> rdd = sc.parallelize([1, 2, 3, 4], 4)\n >>> def f(splitIndex, iterator): yield splitIndex\n >>> rdd.mapPartitionsWithSplit(f).sum()\n 6", "output": "def mapPartitionsWithSplit(self, f, preservesPartitioning=False):\n \"\"\"\n Deprecated: use mapPartitionsWithIndex instead.\n\n Return a new RDD by applying a function to each partition of this RDD,\n while tracking the index of the original partition.\n\n >>> rdd = sc.parallelize([1, 2, 3, 4], 4)\n >>> def f(splitIndex, iterator): yield splitIndex\n >>> rdd.mapPartitionsWithSplit(f).sum()\n 6\n \"\"\"\n warnings.warn(\"mapPartitionsWithSplit is deprecated; \"\n \"use mapPartitionsWithIndex instead\", DeprecationWarning, stacklevel=2)\n return self.mapPartitionsWithIndex(f, preservesPartitioning)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn a new RDD containing the distinct elements in this RDD.\n\n >>> sorted(sc.parallelize([1, 1, 2, 3]).distinct().collect())\n [1, 2, 3]", "output": "def distinct(self, numPartitions=None):\n \"\"\"\n Return a new RDD containing the distinct elements in this RDD.\n\n >>> sorted(sc.parallelize([1, 1, 2, 3]).distinct().collect())\n [1, 2, 3]\n \"\"\"\n return self.map(lambda x: (x, None)) \\\n .reduceByKey(lambda x, _: x, numPartitions) \\\n .map(lambda x: x[0])" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn a sampled subset of this RDD.\n\n :param withReplacement: can elements be sampled multiple times (replaced when sampled out)\n :param fraction: expected size of the sample as a fraction of this RDD's size\n without replacement: probability that each element is chosen; fraction must be [0, 1]\n with replacement: expected number of times each element is chosen; fraction must be >= 0\n :param seed: seed for the random number generator\n\n .. note:: This is not guaranteed to provide exactly the fraction specified of the total\n count of the given :class:`DataFrame`.\n\n >>> rdd = sc.parallelize(range(100), 4)\n >>> 6 <= rdd.sample(False, 0.1, 81).count() <= 14\n True", "output": "def sample(self, withReplacement, fraction, seed=None):\n \"\"\"\n Return a sampled subset of this RDD.\n\n :param withReplacement: can elements be sampled multiple times (replaced when sampled out)\n :param fraction: expected size of the sample as a fraction of this RDD's size\n without replacement: probability that each element is chosen; fraction must be [0, 1]\n with replacement: expected number of times each element is chosen; fraction must be >= 0\n :param seed: seed for the random number generator\n\n .. note:: This is not guaranteed to provide exactly the fraction specified of the total\n count of the given :class:`DataFrame`.\n\n >>> rdd = sc.parallelize(range(100), 4)\n >>> 6 <= rdd.sample(False, 0.1, 81).count() <= 14\n True\n \"\"\"\n assert fraction >= 0.0, \"Negative fraction value: %s\" % fraction\n return self.mapPartitionsWithIndex(RDDSampler(withReplacement, fraction, seed).func, True)" }, { "instruction": "Write or improve a Python function based on this description:\n\nRandomly splits this RDD with the provided weights.\n\n :param weights: weights for splits, will be normalized if they don't sum to 1\n :param seed: random seed\n :return: split RDDs in a list\n\n >>> rdd = sc.parallelize(range(500), 1)\n >>> rdd1, rdd2 = rdd.randomSplit([2, 3], 17)\n >>> len(rdd1.collect() + rdd2.collect())\n 500\n >>> 150 < rdd1.count() < 250\n True\n >>> 250 < rdd2.count() < 350\n True", "output": "def randomSplit(self, weights, seed=None):\n \"\"\"\n Randomly splits this RDD with the provided weights.\n\n :param weights: weights for splits, will be normalized if they don't sum to 1\n :param seed: random seed\n :return: split RDDs in a list\n\n >>> rdd = sc.parallelize(range(500), 1)\n >>> rdd1, rdd2 = rdd.randomSplit([2, 3], 17)\n >>> len(rdd1.collect() + rdd2.collect())\n 500\n >>> 150 < rdd1.count() < 250\n True\n >>> 250 < rdd2.count() < 350\n True\n \"\"\"\n s = float(sum(weights))\n cweights = [0.0]\n for w in weights:\n cweights.append(cweights[-1] + w / s)\n if seed is None:\n seed = random.randint(0, 2 ** 32 - 1)\n return [self.mapPartitionsWithIndex(RDDRangeSampler(lb, ub, seed).func, True)\n for lb, ub in zip(cweights, cweights[1:])]" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn a fixed-size sampled subset of this RDD.\n\n .. note:: This method should only be used if the resulting array is expected\n to be small, as all the data is loaded into the driver's memory.\n\n >>> rdd = sc.parallelize(range(0, 10))\n >>> len(rdd.takeSample(True, 20, 1))\n 20\n >>> len(rdd.takeSample(False, 5, 2))\n 5\n >>> len(rdd.takeSample(False, 15, 3))\n 10", "output": "def takeSample(self, withReplacement, num, seed=None):\n \"\"\"\n Return a fixed-size sampled subset of this RDD.\n\n .. note:: This method should only be used if the resulting array is expected\n to be small, as all the data is loaded into the driver's memory.\n\n >>> rdd = sc.parallelize(range(0, 10))\n >>> len(rdd.takeSample(True, 20, 1))\n 20\n >>> len(rdd.takeSample(False, 5, 2))\n 5\n >>> len(rdd.takeSample(False, 15, 3))\n 10\n \"\"\"\n numStDev = 10.0\n\n if num < 0:\n raise ValueError(\"Sample size cannot be negative.\")\n elif num == 0:\n return []\n\n initialCount = self.count()\n if initialCount == 0:\n return []\n\n rand = random.Random(seed)\n\n if (not withReplacement) and num >= initialCount:\n # shuffle current RDD and return\n samples = self.collect()\n rand.shuffle(samples)\n return samples\n\n maxSampleSize = sys.maxsize - int(numStDev * sqrt(sys.maxsize))\n if num > maxSampleSize:\n raise ValueError(\n \"Sample size cannot be greater than %d.\" % maxSampleSize)\n\n fraction = RDD._computeFractionForSampleSize(\n num, initialCount, withReplacement)\n samples = self.sample(withReplacement, fraction, seed).collect()\n\n # If the first sample didn't turn out large enough, keep trying to take samples;\n # this shouldn't happen often because we use a big multiplier for their initial size.\n # See: scala/spark/RDD.scala\n while len(samples) < num:\n # TODO: add log warning for when more than one iteration was run\n seed = rand.randint(0, sys.maxsize)\n samples = self.sample(withReplacement, fraction, seed).collect()\n\n rand.shuffle(samples)\n\n return samples[0:num]" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns a sampling rate that guarantees a sample of\n size >= sampleSizeLowerBound 99.99% of the time.\n\n How the sampling rate is determined:\n Let p = num / total, where num is the sample size and total is the\n total number of data points in the RDD. We're trying to compute\n q > p such that\n - when sampling with replacement, we're drawing each data point\n with prob_i ~ Pois(q), where we want to guarantee\n Pr[s < num] < 0.0001 for s = sum(prob_i for i from 0 to\n total), i.e. the failure rate of not having a sufficiently large\n sample < 0.0001. Setting q = p + 5 * sqrt(p/total) is sufficient\n to guarantee 0.9999 success rate for num > 12, but we need a\n slightly larger q (9 empirically determined).\n - when sampling without replacement, we're drawing each data point\n with prob_i ~ Binomial(total, fraction) and our choice of q\n guarantees 1-delta, or 0.9999 success rate, where success rate is\n defined the same as in sampling with replacement.", "output": "def _computeFractionForSampleSize(sampleSizeLowerBound, total, withReplacement):\n \"\"\"\n Returns a sampling rate that guarantees a sample of\n size >= sampleSizeLowerBound 99.99% of the time.\n\n How the sampling rate is determined:\n Let p = num / total, where num is the sample size and total is the\n total number of data points in the RDD. We're trying to compute\n q > p such that\n - when sampling with replacement, we're drawing each data point\n with prob_i ~ Pois(q), where we want to guarantee\n Pr[s < num] < 0.0001 for s = sum(prob_i for i from 0 to\n total), i.e. the failure rate of not having a sufficiently large\n sample < 0.0001. Setting q = p + 5 * sqrt(p/total) is sufficient\n to guarantee 0.9999 success rate for num > 12, but we need a\n slightly larger q (9 empirically determined).\n - when sampling without replacement, we're drawing each data point\n with prob_i ~ Binomial(total, fraction) and our choice of q\n guarantees 1-delta, or 0.9999 success rate, where success rate is\n defined the same as in sampling with replacement.\n \"\"\"\n fraction = float(sampleSizeLowerBound) / total\n if withReplacement:\n numStDev = 5\n if (sampleSizeLowerBound < 12):\n numStDev = 9\n return fraction + numStDev * sqrt(fraction / total)\n else:\n delta = 0.00005\n gamma = - log(delta) / total\n return min(1, fraction + gamma + sqrt(gamma * gamma + 2 * gamma * fraction))" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn the union of this RDD and another one.\n\n >>> rdd = sc.parallelize([1, 1, 2, 3])\n >>> rdd.union(rdd).collect()\n [1, 1, 2, 3, 1, 1, 2, 3]", "output": "def union(self, other):\n \"\"\"\n Return the union of this RDD and another one.\n\n >>> rdd = sc.parallelize([1, 1, 2, 3])\n >>> rdd.union(rdd).collect()\n [1, 1, 2, 3, 1, 1, 2, 3]\n \"\"\"\n if self._jrdd_deserializer == other._jrdd_deserializer:\n rdd = RDD(self._jrdd.union(other._jrdd), self.ctx,\n self._jrdd_deserializer)\n else:\n # These RDDs contain data in different serialized formats, so we\n # must normalize them to the default serializer.\n self_copy = self._reserialize()\n other_copy = other._reserialize()\n rdd = RDD(self_copy._jrdd.union(other_copy._jrdd), self.ctx,\n self.ctx.serializer)\n if (self.partitioner == other.partitioner and\n self.getNumPartitions() == rdd.getNumPartitions()):\n rdd.partitioner = self.partitioner\n return rdd" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn the intersection of this RDD and another one. The output will\n not contain any duplicate elements, even if the input RDDs did.\n\n .. note:: This method performs a shuffle internally.\n\n >>> rdd1 = sc.parallelize([1, 10, 2, 3, 4, 5])\n >>> rdd2 = sc.parallelize([1, 6, 2, 3, 7, 8])\n >>> rdd1.intersection(rdd2).collect()\n [1, 2, 3]", "output": "def intersection(self, other):\n \"\"\"\n Return the intersection of this RDD and another one. The output will\n not contain any duplicate elements, even if the input RDDs did.\n\n .. note:: This method performs a shuffle internally.\n\n >>> rdd1 = sc.parallelize([1, 10, 2, 3, 4, 5])\n >>> rdd2 = sc.parallelize([1, 6, 2, 3, 7, 8])\n >>> rdd1.intersection(rdd2).collect()\n [1, 2, 3]\n \"\"\"\n return self.map(lambda v: (v, None)) \\\n .cogroup(other.map(lambda v: (v, None))) \\\n .filter(lambda k_vs: all(k_vs[1])) \\\n .keys()" }, { "instruction": "Write or improve a Python function based on this description:\n\nRepartition the RDD according to the given partitioner and, within each resulting partition,\n sort records by their keys.\n\n >>> rdd = sc.parallelize([(0, 5), (3, 8), (2, 6), (0, 8), (3, 8), (1, 3)])\n >>> rdd2 = rdd.repartitionAndSortWithinPartitions(2, lambda x: x % 2, True)\n >>> rdd2.glom().collect()\n [[(0, 5), (0, 8), (2, 6)], [(1, 3), (3, 8), (3, 8)]]", "output": "def repartitionAndSortWithinPartitions(self, numPartitions=None, partitionFunc=portable_hash,\n ascending=True, keyfunc=lambda x: x):\n \"\"\"\n Repartition the RDD according to the given partitioner and, within each resulting partition,\n sort records by their keys.\n\n >>> rdd = sc.parallelize([(0, 5), (3, 8), (2, 6), (0, 8), (3, 8), (1, 3)])\n >>> rdd2 = rdd.repartitionAndSortWithinPartitions(2, lambda x: x % 2, True)\n >>> rdd2.glom().collect()\n [[(0, 5), (0, 8), (2, 6)], [(1, 3), (3, 8), (3, 8)]]\n \"\"\"\n if numPartitions is None:\n numPartitions = self._defaultReducePartitions()\n\n memory = _parse_memory(self.ctx._conf.get(\"spark.python.worker.memory\", \"512m\"))\n serializer = self._jrdd_deserializer\n\n def sortPartition(iterator):\n sort = ExternalSorter(memory * 0.9, serializer).sorted\n return iter(sort(iterator, key=lambda k_v: keyfunc(k_v[0]), reverse=(not ascending)))\n\n return self.partitionBy(numPartitions, partitionFunc).mapPartitions(sortPartition, True)" }, { "instruction": "Write or improve a Python function based on this description:\n\nSorts this RDD, which is assumed to consist of (key, value) pairs.\n\n >>> tmp = [('a', 1), ('b', 2), ('1', 3), ('d', 4), ('2', 5)]\n >>> sc.parallelize(tmp).sortByKey().first()\n ('1', 3)\n >>> sc.parallelize(tmp).sortByKey(True, 1).collect()\n [('1', 3), ('2', 5), ('a', 1), ('b', 2), ('d', 4)]\n >>> sc.parallelize(tmp).sortByKey(True, 2).collect()\n [('1', 3), ('2', 5), ('a', 1), ('b', 2), ('d', 4)]\n >>> tmp2 = [('Mary', 1), ('had', 2), ('a', 3), ('little', 4), ('lamb', 5)]\n >>> tmp2.extend([('whose', 6), ('fleece', 7), ('was', 8), ('white', 9)])\n >>> sc.parallelize(tmp2).sortByKey(True, 3, keyfunc=lambda k: k.lower()).collect()\n [('a', 3), ('fleece', 7), ('had', 2), ('lamb', 5),...('white', 9), ('whose', 6)]", "output": "def sortByKey(self, ascending=True, numPartitions=None, keyfunc=lambda x: x):\n \"\"\"\n Sorts this RDD, which is assumed to consist of (key, value) pairs.\n\n >>> tmp = [('a', 1), ('b', 2), ('1', 3), ('d', 4), ('2', 5)]\n >>> sc.parallelize(tmp).sortByKey().first()\n ('1', 3)\n >>> sc.parallelize(tmp).sortByKey(True, 1).collect()\n [('1', 3), ('2', 5), ('a', 1), ('b', 2), ('d', 4)]\n >>> sc.parallelize(tmp).sortByKey(True, 2).collect()\n [('1', 3), ('2', 5), ('a', 1), ('b', 2), ('d', 4)]\n >>> tmp2 = [('Mary', 1), ('had', 2), ('a', 3), ('little', 4), ('lamb', 5)]\n >>> tmp2.extend([('whose', 6), ('fleece', 7), ('was', 8), ('white', 9)])\n >>> sc.parallelize(tmp2).sortByKey(True, 3, keyfunc=lambda k: k.lower()).collect()\n [('a', 3), ('fleece', 7), ('had', 2), ('lamb', 5),...('white', 9), ('whose', 6)]\n \"\"\"\n if numPartitions is None:\n numPartitions = self._defaultReducePartitions()\n\n memory = self._memory_limit()\n serializer = self._jrdd_deserializer\n\n def sortPartition(iterator):\n sort = ExternalSorter(memory * 0.9, serializer).sorted\n return iter(sort(iterator, key=lambda kv: keyfunc(kv[0]), reverse=(not ascending)))\n\n if numPartitions == 1:\n if self.getNumPartitions() > 1:\n self = self.coalesce(1)\n return self.mapPartitions(sortPartition, True)\n\n # first compute the boundary of each part via sampling: we want to partition\n # the key-space into bins such that the bins have roughly the same\n # number of (key, value) pairs falling into them\n rddSize = self.count()\n if not rddSize:\n return self # empty RDD\n maxSampleSize = numPartitions * 20.0 # constant from Spark's RangePartitioner\n fraction = min(maxSampleSize / max(rddSize, 1), 1.0)\n samples = self.sample(False, fraction, 1).map(lambda kv: kv[0]).collect()\n samples = sorted(samples, key=keyfunc)\n\n # we have numPartitions many parts but one of the them has\n # an implicit boundary\n bounds = [samples[int(len(samples) * (i + 1) / numPartitions)]\n for i in range(0, numPartitions - 1)]\n\n def rangePartitioner(k):\n p = bisect.bisect_left(bounds, keyfunc(k))\n if ascending:\n return p\n else:\n return numPartitions - 1 - p\n\n return self.partitionBy(numPartitions, rangePartitioner).mapPartitions(sortPartition, True)" }, { "instruction": "Write or improve a Python function based on this description:\n\nSorts this RDD by the given keyfunc\n\n >>> tmp = [('a', 1), ('b', 2), ('1', 3), ('d', 4), ('2', 5)]\n >>> sc.parallelize(tmp).sortBy(lambda x: x[0]).collect()\n [('1', 3), ('2', 5), ('a', 1), ('b', 2), ('d', 4)]\n >>> sc.parallelize(tmp).sortBy(lambda x: x[1]).collect()\n [('a', 1), ('b', 2), ('1', 3), ('d', 4), ('2', 5)]", "output": "def sortBy(self, keyfunc, ascending=True, numPartitions=None):\n \"\"\"\n Sorts this RDD by the given keyfunc\n\n >>> tmp = [('a', 1), ('b', 2), ('1', 3), ('d', 4), ('2', 5)]\n >>> sc.parallelize(tmp).sortBy(lambda x: x[0]).collect()\n [('1', 3), ('2', 5), ('a', 1), ('b', 2), ('d', 4)]\n >>> sc.parallelize(tmp).sortBy(lambda x: x[1]).collect()\n [('a', 1), ('b', 2), ('1', 3), ('d', 4), ('2', 5)]\n \"\"\"\n return self.keyBy(keyfunc).sortByKey(ascending, numPartitions).values()" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn the Cartesian product of this RDD and another one, that is, the\n RDD of all pairs of elements C{(a, b)} where C{a} is in C{self} and\n C{b} is in C{other}.\n\n >>> rdd = sc.parallelize([1, 2])\n >>> sorted(rdd.cartesian(rdd).collect())\n [(1, 1), (1, 2), (2, 1), (2, 2)]", "output": "def cartesian(self, other):\n \"\"\"\n Return the Cartesian product of this RDD and another one, that is, the\n RDD of all pairs of elements C{(a, b)} where C{a} is in C{self} and\n C{b} is in C{other}.\n\n >>> rdd = sc.parallelize([1, 2])\n >>> sorted(rdd.cartesian(rdd).collect())\n [(1, 1), (1, 2), (2, 1), (2, 2)]\n \"\"\"\n # Due to batching, we can't use the Java cartesian method.\n deserializer = CartesianDeserializer(self._jrdd_deserializer,\n other._jrdd_deserializer)\n return RDD(self._jrdd.cartesian(other._jrdd), self.ctx, deserializer)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn an RDD of grouped items.\n\n >>> rdd = sc.parallelize([1, 1, 2, 3, 5, 8])\n >>> result = rdd.groupBy(lambda x: x % 2).collect()\n >>> sorted([(x, sorted(y)) for (x, y) in result])\n [(0, [2, 8]), (1, [1, 1, 3, 5])]", "output": "def groupBy(self, f, numPartitions=None, partitionFunc=portable_hash):\n \"\"\"\n Return an RDD of grouped items.\n\n >>> rdd = sc.parallelize([1, 1, 2, 3, 5, 8])\n >>> result = rdd.groupBy(lambda x: x % 2).collect()\n >>> sorted([(x, sorted(y)) for (x, y) in result])\n [(0, [2, 8]), (1, [1, 1, 3, 5])]\n \"\"\"\n return self.map(lambda x: (f(x), x)).groupByKey(numPartitions, partitionFunc)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn an RDD created by piping elements to a forked external process.\n\n >>> sc.parallelize(['1', '2', '', '3']).pipe('cat').collect()\n [u'1', u'2', u'', u'3']\n\n :param checkCode: whether or not to check the return value of the shell command.", "output": "def pipe(self, command, env=None, checkCode=False):\n \"\"\"\n Return an RDD created by piping elements to a forked external process.\n\n >>> sc.parallelize(['1', '2', '', '3']).pipe('cat').collect()\n [u'1', u'2', u'', u'3']\n\n :param checkCode: whether or not to check the return value of the shell command.\n \"\"\"\n if env is None:\n env = dict()\n\n def func(iterator):\n pipe = Popen(\n shlex.split(command), env=env, stdin=PIPE, stdout=PIPE)\n\n def pipe_objs(out):\n for obj in iterator:\n s = unicode(obj).rstrip('\\n') + '\\n'\n out.write(s.encode('utf-8'))\n out.close()\n Thread(target=pipe_objs, args=[pipe.stdin]).start()\n\n def check_return_code():\n pipe.wait()\n if checkCode and pipe.returncode:\n raise Exception(\"Pipe function `%s' exited \"\n \"with error code %d\" % (command, pipe.returncode))\n else:\n for i in range(0):\n yield i\n return (x.rstrip(b'\\n').decode('utf-8') for x in\n chain(iter(pipe.stdout.readline, b''), check_return_code()))\n return self.mapPartitions(func)" }, { "instruction": "Write or improve a Python function based on this description:\n\nApplies a function to all elements of this RDD.\n\n >>> def f(x): print(x)\n >>> sc.parallelize([1, 2, 3, 4, 5]).foreach(f)", "output": "def foreach(self, f):\n \"\"\"\n Applies a function to all elements of this RDD.\n\n >>> def f(x): print(x)\n >>> sc.parallelize([1, 2, 3, 4, 5]).foreach(f)\n \"\"\"\n f = fail_on_stopiteration(f)\n\n def processPartition(iterator):\n for x in iterator:\n f(x)\n return iter([])\n self.mapPartitions(processPartition).count()" }, { "instruction": "Write or improve a Python function based on this description:\n\nApplies a function to each partition of this RDD.\n\n >>> def f(iterator):\n ... for x in iterator:\n ... print(x)\n >>> sc.parallelize([1, 2, 3, 4, 5]).foreachPartition(f)", "output": "def foreachPartition(self, f):\n \"\"\"\n Applies a function to each partition of this RDD.\n\n >>> def f(iterator):\n ... for x in iterator:\n ... print(x)\n >>> sc.parallelize([1, 2, 3, 4, 5]).foreachPartition(f)\n \"\"\"\n def func(it):\n r = f(it)\n try:\n return iter(r)\n except TypeError:\n return iter([])\n self.mapPartitions(func).count()" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn a list that contains all of the elements in this RDD.\n\n .. note:: This method should only be used if the resulting array is expected\n to be small, as all the data is loaded into the driver's memory.", "output": "def collect(self):\n \"\"\"\n Return a list that contains all of the elements in this RDD.\n\n .. note:: This method should only be used if the resulting array is expected\n to be small, as all the data is loaded into the driver's memory.\n \"\"\"\n with SCCallSiteSync(self.context) as css:\n sock_info = self.ctx._jvm.PythonRDD.collectAndServe(self._jrdd.rdd())\n return list(_load_from_socket(sock_info, self._jrdd_deserializer))" }, { "instruction": "Write or improve a Python function based on this description:\n\nReduces the elements of this RDD using the specified commutative and\n associative binary operator. Currently reduces partitions locally.\n\n >>> from operator import add\n >>> sc.parallelize([1, 2, 3, 4, 5]).reduce(add)\n 15\n >>> sc.parallelize((2 for _ in range(10))).map(lambda x: 1).cache().reduce(add)\n 10\n >>> sc.parallelize([]).reduce(add)\n Traceback (most recent call last):\n ...\n ValueError: Can not reduce() empty RDD", "output": "def reduce(self, f):\n \"\"\"\n Reduces the elements of this RDD using the specified commutative and\n associative binary operator. Currently reduces partitions locally.\n\n >>> from operator import add\n >>> sc.parallelize([1, 2, 3, 4, 5]).reduce(add)\n 15\n >>> sc.parallelize((2 for _ in range(10))).map(lambda x: 1).cache().reduce(add)\n 10\n >>> sc.parallelize([]).reduce(add)\n Traceback (most recent call last):\n ...\n ValueError: Can not reduce() empty RDD\n \"\"\"\n f = fail_on_stopiteration(f)\n\n def func(iterator):\n iterator = iter(iterator)\n try:\n initial = next(iterator)\n except StopIteration:\n return\n yield reduce(f, iterator, initial)\n\n vals = self.mapPartitions(func).collect()\n if vals:\n return reduce(f, vals)\n raise ValueError(\"Can not reduce() empty RDD\")" }, { "instruction": "Write or improve a Python function based on this description:\n\nReduces the elements of this RDD in a multi-level tree pattern.\n\n :param depth: suggested depth of the tree (default: 2)\n\n >>> add = lambda x, y: x + y\n >>> rdd = sc.parallelize([-5, -4, -3, -2, -1, 1, 2, 3, 4], 10)\n >>> rdd.treeReduce(add)\n -5\n >>> rdd.treeReduce(add, 1)\n -5\n >>> rdd.treeReduce(add, 2)\n -5\n >>> rdd.treeReduce(add, 5)\n -5\n >>> rdd.treeReduce(add, 10)\n -5", "output": "def treeReduce(self, f, depth=2):\n \"\"\"\n Reduces the elements of this RDD in a multi-level tree pattern.\n\n :param depth: suggested depth of the tree (default: 2)\n\n >>> add = lambda x, y: x + y\n >>> rdd = sc.parallelize([-5, -4, -3, -2, -1, 1, 2, 3, 4], 10)\n >>> rdd.treeReduce(add)\n -5\n >>> rdd.treeReduce(add, 1)\n -5\n >>> rdd.treeReduce(add, 2)\n -5\n >>> rdd.treeReduce(add, 5)\n -5\n >>> rdd.treeReduce(add, 10)\n -5\n \"\"\"\n if depth < 1:\n raise ValueError(\"Depth cannot be smaller than 1 but got %d.\" % depth)\n\n zeroValue = None, True # Use the second entry to indicate whether this is a dummy value.\n\n def op(x, y):\n if x[1]:\n return y\n elif y[1]:\n return x\n else:\n return f(x[0], y[0]), False\n\n reduced = self.map(lambda x: (x, False)).treeAggregate(zeroValue, op, op, depth)\n if reduced[1]:\n raise ValueError(\"Cannot reduce empty RDD.\")\n return reduced[0]" }, { "instruction": "Write or improve a Python function based on this description:\n\nAggregate the elements of each partition, and then the results for all\n the partitions, using a given associative function and a neutral \"zero value.\"\n\n The function C{op(t1, t2)} is allowed to modify C{t1} and return it\n as its result value to avoid object allocation; however, it should not\n modify C{t2}.\n\n This behaves somewhat differently from fold operations implemented\n for non-distributed collections in functional languages like Scala.\n This fold operation may be applied to partitions individually, and then\n fold those results into the final result, rather than apply the fold\n to each element sequentially in some defined ordering. For functions\n that are not commutative, the result may differ from that of a fold\n applied to a non-distributed collection.\n\n >>> from operator import add\n >>> sc.parallelize([1, 2, 3, 4, 5]).fold(0, add)\n 15", "output": "def fold(self, zeroValue, op):\n \"\"\"\n Aggregate the elements of each partition, and then the results for all\n the partitions, using a given associative function and a neutral \"zero value.\"\n\n The function C{op(t1, t2)} is allowed to modify C{t1} and return it\n as its result value to avoid object allocation; however, it should not\n modify C{t2}.\n\n This behaves somewhat differently from fold operations implemented\n for non-distributed collections in functional languages like Scala.\n This fold operation may be applied to partitions individually, and then\n fold those results into the final result, rather than apply the fold\n to each element sequentially in some defined ordering. For functions\n that are not commutative, the result may differ from that of a fold\n applied to a non-distributed collection.\n\n >>> from operator import add\n >>> sc.parallelize([1, 2, 3, 4, 5]).fold(0, add)\n 15\n \"\"\"\n op = fail_on_stopiteration(op)\n\n def func(iterator):\n acc = zeroValue\n for obj in iterator:\n acc = op(acc, obj)\n yield acc\n # collecting result of mapPartitions here ensures that the copy of\n # zeroValue provided to each partition is unique from the one provided\n # to the final reduce call\n vals = self.mapPartitions(func).collect()\n return reduce(op, vals, zeroValue)" }, { "instruction": "Write or improve a Python function based on this description:\n\nAggregate the elements of each partition, and then the results for all\n the partitions, using a given combine functions and a neutral \"zero\n value.\"\n\n The functions C{op(t1, t2)} is allowed to modify C{t1} and return it\n as its result value to avoid object allocation; however, it should not\n modify C{t2}.\n\n The first function (seqOp) can return a different result type, U, than\n the type of this RDD. Thus, we need one operation for merging a T into\n an U and one operation for merging two U\n\n >>> seqOp = (lambda x, y: (x[0] + y, x[1] + 1))\n >>> combOp = (lambda x, y: (x[0] + y[0], x[1] + y[1]))\n >>> sc.parallelize([1, 2, 3, 4]).aggregate((0, 0), seqOp, combOp)\n (10, 4)\n >>> sc.parallelize([]).aggregate((0, 0), seqOp, combOp)\n (0, 0)", "output": "def aggregate(self, zeroValue, seqOp, combOp):\n \"\"\"\n Aggregate the elements of each partition, and then the results for all\n the partitions, using a given combine functions and a neutral \"zero\n value.\"\n\n The functions C{op(t1, t2)} is allowed to modify C{t1} and return it\n as its result value to avoid object allocation; however, it should not\n modify C{t2}.\n\n The first function (seqOp) can return a different result type, U, than\n the type of this RDD. Thus, we need one operation for merging a T into\n an U and one operation for merging two U\n\n >>> seqOp = (lambda x, y: (x[0] + y, x[1] + 1))\n >>> combOp = (lambda x, y: (x[0] + y[0], x[1] + y[1]))\n >>> sc.parallelize([1, 2, 3, 4]).aggregate((0, 0), seqOp, combOp)\n (10, 4)\n >>> sc.parallelize([]).aggregate((0, 0), seqOp, combOp)\n (0, 0)\n \"\"\"\n seqOp = fail_on_stopiteration(seqOp)\n combOp = fail_on_stopiteration(combOp)\n\n def func(iterator):\n acc = zeroValue\n for obj in iterator:\n acc = seqOp(acc, obj)\n yield acc\n # collecting result of mapPartitions here ensures that the copy of\n # zeroValue provided to each partition is unique from the one provided\n # to the final reduce call\n vals = self.mapPartitions(func).collect()\n return reduce(combOp, vals, zeroValue)" }, { "instruction": "Write or improve a Python function based on this description:\n\nAggregates the elements of this RDD in a multi-level tree\n pattern.\n\n :param depth: suggested depth of the tree (default: 2)\n\n >>> add = lambda x, y: x + y\n >>> rdd = sc.parallelize([-5, -4, -3, -2, -1, 1, 2, 3, 4], 10)\n >>> rdd.treeAggregate(0, add, add)\n -5\n >>> rdd.treeAggregate(0, add, add, 1)\n -5\n >>> rdd.treeAggregate(0, add, add, 2)\n -5\n >>> rdd.treeAggregate(0, add, add, 5)\n -5\n >>> rdd.treeAggregate(0, add, add, 10)\n -5", "output": "def treeAggregate(self, zeroValue, seqOp, combOp, depth=2):\n \"\"\"\n Aggregates the elements of this RDD in a multi-level tree\n pattern.\n\n :param depth: suggested depth of the tree (default: 2)\n\n >>> add = lambda x, y: x + y\n >>> rdd = sc.parallelize([-5, -4, -3, -2, -1, 1, 2, 3, 4], 10)\n >>> rdd.treeAggregate(0, add, add)\n -5\n >>> rdd.treeAggregate(0, add, add, 1)\n -5\n >>> rdd.treeAggregate(0, add, add, 2)\n -5\n >>> rdd.treeAggregate(0, add, add, 5)\n -5\n >>> rdd.treeAggregate(0, add, add, 10)\n -5\n \"\"\"\n if depth < 1:\n raise ValueError(\"Depth cannot be smaller than 1 but got %d.\" % depth)\n\n if self.getNumPartitions() == 0:\n return zeroValue\n\n def aggregatePartition(iterator):\n acc = zeroValue\n for obj in iterator:\n acc = seqOp(acc, obj)\n yield acc\n\n partiallyAggregated = self.mapPartitions(aggregatePartition)\n numPartitions = partiallyAggregated.getNumPartitions()\n scale = max(int(ceil(pow(numPartitions, 1.0 / depth))), 2)\n # If creating an extra level doesn't help reduce the wall-clock time, we stop the tree\n # aggregation.\n while numPartitions > scale + numPartitions / scale:\n numPartitions /= scale\n curNumPartitions = int(numPartitions)\n\n def mapPartition(i, iterator):\n for obj in iterator:\n yield (i % curNumPartitions, obj)\n\n partiallyAggregated = partiallyAggregated \\\n .mapPartitionsWithIndex(mapPartition) \\\n .reduceByKey(combOp, curNumPartitions) \\\n .values()\n\n return partiallyAggregated.reduce(combOp)" }, { "instruction": "Write or improve a Python function based on this description:\n\nFind the maximum item in this RDD.\n\n :param key: A function used to generate key for comparing\n\n >>> rdd = sc.parallelize([1.0, 5.0, 43.0, 10.0])\n >>> rdd.max()\n 43.0\n >>> rdd.max(key=str)\n 5.0", "output": "def max(self, key=None):\n \"\"\"\n Find the maximum item in this RDD.\n\n :param key: A function used to generate key for comparing\n\n >>> rdd = sc.parallelize([1.0, 5.0, 43.0, 10.0])\n >>> rdd.max()\n 43.0\n >>> rdd.max(key=str)\n 5.0\n \"\"\"\n if key is None:\n return self.reduce(max)\n return self.reduce(lambda a, b: max(a, b, key=key))" }, { "instruction": "Write or improve a Python function based on this description:\n\nFind the minimum item in this RDD.\n\n :param key: A function used to generate key for comparing\n\n >>> rdd = sc.parallelize([2.0, 5.0, 43.0, 10.0])\n >>> rdd.min()\n 2.0\n >>> rdd.min(key=str)\n 10.0", "output": "def min(self, key=None):\n \"\"\"\n Find the minimum item in this RDD.\n\n :param key: A function used to generate key for comparing\n\n >>> rdd = sc.parallelize([2.0, 5.0, 43.0, 10.0])\n >>> rdd.min()\n 2.0\n >>> rdd.min(key=str)\n 10.0\n \"\"\"\n if key is None:\n return self.reduce(min)\n return self.reduce(lambda a, b: min(a, b, key=key))" }, { "instruction": "Write or improve a Python function based on this description:\n\nAdd up the elements in this RDD.\n\n >>> sc.parallelize([1.0, 2.0, 3.0]).sum()\n 6.0", "output": "def sum(self):\n \"\"\"\n Add up the elements in this RDD.\n\n >>> sc.parallelize([1.0, 2.0, 3.0]).sum()\n 6.0\n \"\"\"\n return self.mapPartitions(lambda x: [sum(x)]).fold(0, operator.add)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn a L{StatCounter} object that captures the mean, variance\n and count of the RDD's elements in one operation.", "output": "def stats(self):\n \"\"\"\n Return a L{StatCounter} object that captures the mean, variance\n and count of the RDD's elements in one operation.\n \"\"\"\n def redFunc(left_counter, right_counter):\n return left_counter.mergeStats(right_counter)\n\n return self.mapPartitions(lambda i: [StatCounter(i)]).reduce(redFunc)" }, { "instruction": "Write or improve a Python function based on this description:\n\nCompute a histogram using the provided buckets. The buckets\n are all open to the right except for the last which is closed.\n e.g. [1,10,20,50] means the buckets are [1,10) [10,20) [20,50],\n which means 1<=x<10, 10<=x<20, 20<=x<=50. And on the input of 1\n and 50 we would have a histogram of 1,0,1.\n\n If your histogram is evenly spaced (e.g. [0, 10, 20, 30]),\n this can be switched from an O(log n) inseration to O(1) per\n element (where n is the number of buckets).\n\n Buckets must be sorted, not contain any duplicates, and have\n at least two elements.\n\n If `buckets` is a number, it will generate buckets which are\n evenly spaced between the minimum and maximum of the RDD. For\n example, if the min value is 0 and the max is 100, given `buckets`\n as 2, the resulting buckets will be [0,50) [50,100]. `buckets` must\n be at least 1. An exception is raised if the RDD contains infinity.\n If the elements in the RDD do not vary (max == min), a single bucket\n will be used.\n\n The return value is a tuple of buckets and histogram.\n\n >>> rdd = sc.parallelize(range(51))\n >>> rdd.histogram(2)\n ([0, 25, 50], [25, 26])\n >>> rdd.histogram([0, 5, 25, 50])\n ([0, 5, 25, 50], [5, 20, 26])\n >>> rdd.histogram([0, 15, 30, 45, 60]) # evenly spaced buckets\n ([0, 15, 30, 45, 60], [15, 15, 15, 6])\n >>> rdd = sc.parallelize([\"ab\", \"ac\", \"b\", \"bd\", \"ef\"])\n >>> rdd.histogram((\"a\", \"b\", \"c\"))\n (('a', 'b', 'c'), [2, 2])", "output": "def histogram(self, buckets):\n \"\"\"\n Compute a histogram using the provided buckets. The buckets\n are all open to the right except for the last which is closed.\n e.g. [1,10,20,50] means the buckets are [1,10) [10,20) [20,50],\n which means 1<=x<10, 10<=x<20, 20<=x<=50. And on the input of 1\n and 50 we would have a histogram of 1,0,1.\n\n If your histogram is evenly spaced (e.g. [0, 10, 20, 30]),\n this can be switched from an O(log n) inseration to O(1) per\n element (where n is the number of buckets).\n\n Buckets must be sorted, not contain any duplicates, and have\n at least two elements.\n\n If `buckets` is a number, it will generate buckets which are\n evenly spaced between the minimum and maximum of the RDD. For\n example, if the min value is 0 and the max is 100, given `buckets`\n as 2, the resulting buckets will be [0,50) [50,100]. `buckets` must\n be at least 1. An exception is raised if the RDD contains infinity.\n If the elements in the RDD do not vary (max == min), a single bucket\n will be used.\n\n The return value is a tuple of buckets and histogram.\n\n >>> rdd = sc.parallelize(range(51))\n >>> rdd.histogram(2)\n ([0, 25, 50], [25, 26])\n >>> rdd.histogram([0, 5, 25, 50])\n ([0, 5, 25, 50], [5, 20, 26])\n >>> rdd.histogram([0, 15, 30, 45, 60]) # evenly spaced buckets\n ([0, 15, 30, 45, 60], [15, 15, 15, 6])\n >>> rdd = sc.parallelize([\"ab\", \"ac\", \"b\", \"bd\", \"ef\"])\n >>> rdd.histogram((\"a\", \"b\", \"c\"))\n (('a', 'b', 'c'), [2, 2])\n \"\"\"\n\n if isinstance(buckets, int):\n if buckets < 1:\n raise ValueError(\"number of buckets must be >= 1\")\n\n # filter out non-comparable elements\n def comparable(x):\n if x is None:\n return False\n if type(x) is float and isnan(x):\n return False\n return True\n\n filtered = self.filter(comparable)\n\n # faster than stats()\n def minmax(a, b):\n return min(a[0], b[0]), max(a[1], b[1])\n try:\n minv, maxv = filtered.map(lambda x: (x, x)).reduce(minmax)\n except TypeError as e:\n if \" empty \" in str(e):\n raise ValueError(\"can not generate buckets from empty RDD\")\n raise\n\n if minv == maxv or buckets == 1:\n return [minv, maxv], [filtered.count()]\n\n try:\n inc = (maxv - minv) / buckets\n except TypeError:\n raise TypeError(\"Can not generate buckets with non-number in RDD\")\n\n if isinf(inc):\n raise ValueError(\"Can not generate buckets with infinite value\")\n\n # keep them as integer if possible\n inc = int(inc)\n if inc * buckets != maxv - minv:\n inc = (maxv - minv) * 1.0 / buckets\n\n buckets = [i * inc + minv for i in range(buckets)]\n buckets.append(maxv) # fix accumulated error\n even = True\n\n elif isinstance(buckets, (list, tuple)):\n if len(buckets) < 2:\n raise ValueError(\"buckets should have more than one value\")\n\n if any(i is None or isinstance(i, float) and isnan(i) for i in buckets):\n raise ValueError(\"can not have None or NaN in buckets\")\n\n if sorted(buckets) != list(buckets):\n raise ValueError(\"buckets should be sorted\")\n\n if len(set(buckets)) != len(buckets):\n raise ValueError(\"buckets should not contain duplicated values\")\n\n minv = buckets[0]\n maxv = buckets[-1]\n even = False\n inc = None\n try:\n steps = [buckets[i + 1] - buckets[i] for i in range(len(buckets) - 1)]\n except TypeError:\n pass # objects in buckets do not support '-'\n else:\n if max(steps) - min(steps) < 1e-10: # handle precision errors\n even = True\n inc = (maxv - minv) / (len(buckets) - 1)\n\n else:\n raise TypeError(\"buckets should be a list or tuple or number(int or long)\")\n\n def histogram(iterator):\n counters = [0] * len(buckets)\n for i in iterator:\n if i is None or (type(i) is float and isnan(i)) or i > maxv or i < minv:\n continue\n t = (int((i - minv) / inc) if even\n else bisect.bisect_right(buckets, i) - 1)\n counters[t] += 1\n # add last two together\n last = counters.pop()\n counters[-1] += last\n return [counters]\n\n def mergeCounters(a, b):\n return [i + j for i, j in zip(a, b)]\n\n return buckets, self.mapPartitions(histogram).reduce(mergeCounters)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn the count of each unique value in this RDD as a dictionary of\n (value, count) pairs.\n\n >>> sorted(sc.parallelize([1, 2, 1, 2, 2], 2).countByValue().items())\n [(1, 2), (2, 3)]", "output": "def countByValue(self):\n \"\"\"\n Return the count of each unique value in this RDD as a dictionary of\n (value, count) pairs.\n\n >>> sorted(sc.parallelize([1, 2, 1, 2, 2], 2).countByValue().items())\n [(1, 2), (2, 3)]\n \"\"\"\n def countPartition(iterator):\n counts = defaultdict(int)\n for obj in iterator:\n counts[obj] += 1\n yield counts\n\n def mergeMaps(m1, m2):\n for k, v in m2.items():\n m1[k] += v\n return m1\n return self.mapPartitions(countPartition).reduce(mergeMaps)" }, { "instruction": "Write or improve a Python function based on this description:\n\nGet the top N elements from an RDD.\n\n .. note:: This method should only be used if the resulting array is expected\n to be small, as all the data is loaded into the driver's memory.\n\n .. note:: It returns the list sorted in descending order.\n\n >>> sc.parallelize([10, 4, 2, 12, 3]).top(1)\n [12]\n >>> sc.parallelize([2, 3, 4, 5, 6], 2).top(2)\n [6, 5]\n >>> sc.parallelize([10, 4, 2, 12, 3]).top(3, key=str)\n [4, 3, 2]", "output": "def top(self, num, key=None):\n \"\"\"\n Get the top N elements from an RDD.\n\n .. note:: This method should only be used if the resulting array is expected\n to be small, as all the data is loaded into the driver's memory.\n\n .. note:: It returns the list sorted in descending order.\n\n >>> sc.parallelize([10, 4, 2, 12, 3]).top(1)\n [12]\n >>> sc.parallelize([2, 3, 4, 5, 6], 2).top(2)\n [6, 5]\n >>> sc.parallelize([10, 4, 2, 12, 3]).top(3, key=str)\n [4, 3, 2]\n \"\"\"\n def topIterator(iterator):\n yield heapq.nlargest(num, iterator, key=key)\n\n def merge(a, b):\n return heapq.nlargest(num, a + b, key=key)\n\n return self.mapPartitions(topIterator).reduce(merge)" }, { "instruction": "Write or improve a Python function based on this description:\n\nGet the N elements from an RDD ordered in ascending order or as\n specified by the optional key function.\n\n .. note:: this method should only be used if the resulting array is expected\n to be small, as all the data is loaded into the driver's memory.\n\n >>> sc.parallelize([10, 1, 2, 9, 3, 4, 5, 6, 7]).takeOrdered(6)\n [1, 2, 3, 4, 5, 6]\n >>> sc.parallelize([10, 1, 2, 9, 3, 4, 5, 6, 7], 2).takeOrdered(6, key=lambda x: -x)\n [10, 9, 7, 6, 5, 4]", "output": "def takeOrdered(self, num, key=None):\n \"\"\"\n Get the N elements from an RDD ordered in ascending order or as\n specified by the optional key function.\n\n .. note:: this method should only be used if the resulting array is expected\n to be small, as all the data is loaded into the driver's memory.\n\n >>> sc.parallelize([10, 1, 2, 9, 3, 4, 5, 6, 7]).takeOrdered(6)\n [1, 2, 3, 4, 5, 6]\n >>> sc.parallelize([10, 1, 2, 9, 3, 4, 5, 6, 7], 2).takeOrdered(6, key=lambda x: -x)\n [10, 9, 7, 6, 5, 4]\n \"\"\"\n\n def merge(a, b):\n return heapq.nsmallest(num, a + b, key)\n\n return self.mapPartitions(lambda it: [heapq.nsmallest(num, it, key)]).reduce(merge)" }, { "instruction": "Write or improve a Python function based on this description:\n\nTake the first num elements of the RDD.\n\n It works by first scanning one partition, and use the results from\n that partition to estimate the number of additional partitions needed\n to satisfy the limit.\n\n Translated from the Scala implementation in RDD#take().\n\n .. note:: this method should only be used if the resulting array is expected\n to be small, as all the data is loaded into the driver's memory.\n\n >>> sc.parallelize([2, 3, 4, 5, 6]).cache().take(2)\n [2, 3]\n >>> sc.parallelize([2, 3, 4, 5, 6]).take(10)\n [2, 3, 4, 5, 6]\n >>> sc.parallelize(range(100), 100).filter(lambda x: x > 90).take(3)\n [91, 92, 93]", "output": "def take(self, num):\n \"\"\"\n Take the first num elements of the RDD.\n\n It works by first scanning one partition, and use the results from\n that partition to estimate the number of additional partitions needed\n to satisfy the limit.\n\n Translated from the Scala implementation in RDD#take().\n\n .. note:: this method should only be used if the resulting array is expected\n to be small, as all the data is loaded into the driver's memory.\n\n >>> sc.parallelize([2, 3, 4, 5, 6]).cache().take(2)\n [2, 3]\n >>> sc.parallelize([2, 3, 4, 5, 6]).take(10)\n [2, 3, 4, 5, 6]\n >>> sc.parallelize(range(100), 100).filter(lambda x: x > 90).take(3)\n [91, 92, 93]\n \"\"\"\n items = []\n totalParts = self.getNumPartitions()\n partsScanned = 0\n\n while len(items) < num and partsScanned < totalParts:\n # The number of partitions to try in this iteration.\n # It is ok for this number to be greater than totalParts because\n # we actually cap it at totalParts in runJob.\n numPartsToTry = 1\n if partsScanned > 0:\n # If we didn't find any rows after the previous iteration,\n # quadruple and retry. Otherwise, interpolate the number of\n # partitions we need to try, but overestimate it by 50%.\n # We also cap the estimation in the end.\n if len(items) == 0:\n numPartsToTry = partsScanned * 4\n else:\n # the first parameter of max is >=1 whenever partsScanned >= 2\n numPartsToTry = int(1.5 * num * partsScanned / len(items)) - partsScanned\n numPartsToTry = min(max(numPartsToTry, 1), partsScanned * 4)\n\n left = num - len(items)\n\n def takeUpToNumLeft(iterator):\n iterator = iter(iterator)\n taken = 0\n while taken < left:\n try:\n yield next(iterator)\n except StopIteration:\n return\n taken += 1\n\n p = range(partsScanned, min(partsScanned + numPartsToTry, totalParts))\n res = self.context.runJob(self, takeUpToNumLeft, p)\n\n items += res\n partsScanned += numPartsToTry\n\n return items[:num]" }, { "instruction": "Write or improve a Python function based on this description:\n\nOutput a Python RDD of key-value pairs (of form C{RDD[(K, V)]}) to any Hadoop file\n system, using the new Hadoop OutputFormat API (mapreduce package). Keys/values are\n converted for output using either user specified converters or, by default,\n L{org.apache.spark.api.python.JavaToWritableConverter}.\n\n :param conf: Hadoop job configuration, passed in as a dict\n :param keyConverter: (None by default)\n :param valueConverter: (None by default)", "output": "def saveAsNewAPIHadoopDataset(self, conf, keyConverter=None, valueConverter=None):\n \"\"\"\n Output a Python RDD of key-value pairs (of form C{RDD[(K, V)]}) to any Hadoop file\n system, using the new Hadoop OutputFormat API (mapreduce package). Keys/values are\n converted for output using either user specified converters or, by default,\n L{org.apache.spark.api.python.JavaToWritableConverter}.\n\n :param conf: Hadoop job configuration, passed in as a dict\n :param keyConverter: (None by default)\n :param valueConverter: (None by default)\n \"\"\"\n jconf = self.ctx._dictToJavaMap(conf)\n pickledRDD = self._pickled()\n self.ctx._jvm.PythonRDD.saveAsHadoopDataset(pickledRDD._jrdd, True, jconf,\n keyConverter, valueConverter, True)" }, { "instruction": "Write or improve a Python function based on this description:\n\nOutput a Python RDD of key-value pairs (of form C{RDD[(K, V)]}) to any Hadoop file\n system, using the new Hadoop OutputFormat API (mapreduce package). Key and value types\n will be inferred if not specified. Keys and values are converted for output using either\n user specified converters or L{org.apache.spark.api.python.JavaToWritableConverter}. The\n C{conf} is applied on top of the base Hadoop conf associated with the SparkContext\n of this RDD to create a merged Hadoop MapReduce job configuration for saving the data.\n\n :param path: path to Hadoop file\n :param outputFormatClass: fully qualified classname of Hadoop OutputFormat\n (e.g. \"org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat\")\n :param keyClass: fully qualified classname of key Writable class\n (e.g. \"org.apache.hadoop.io.IntWritable\", None by default)\n :param valueClass: fully qualified classname of value Writable class\n (e.g. \"org.apache.hadoop.io.Text\", None by default)\n :param keyConverter: (None by default)\n :param valueConverter: (None by default)\n :param conf: Hadoop job configuration, passed in as a dict (None by default)", "output": "def saveAsNewAPIHadoopFile(self, path, outputFormatClass, keyClass=None, valueClass=None,\n keyConverter=None, valueConverter=None, conf=None):\n \"\"\"\n Output a Python RDD of key-value pairs (of form C{RDD[(K, V)]}) to any Hadoop file\n system, using the new Hadoop OutputFormat API (mapreduce package). Key and value types\n will be inferred if not specified. Keys and values are converted for output using either\n user specified converters or L{org.apache.spark.api.python.JavaToWritableConverter}. The\n C{conf} is applied on top of the base Hadoop conf associated with the SparkContext\n of this RDD to create a merged Hadoop MapReduce job configuration for saving the data.\n\n :param path: path to Hadoop file\n :param outputFormatClass: fully qualified classname of Hadoop OutputFormat\n (e.g. \"org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat\")\n :param keyClass: fully qualified classname of key Writable class\n (e.g. \"org.apache.hadoop.io.IntWritable\", None by default)\n :param valueClass: fully qualified classname of value Writable class\n (e.g. \"org.apache.hadoop.io.Text\", None by default)\n :param keyConverter: (None by default)\n :param valueConverter: (None by default)\n :param conf: Hadoop job configuration, passed in as a dict (None by default)\n \"\"\"\n jconf = self.ctx._dictToJavaMap(conf)\n pickledRDD = self._pickled()\n self.ctx._jvm.PythonRDD.saveAsNewAPIHadoopFile(pickledRDD._jrdd, True, path,\n outputFormatClass,\n keyClass, valueClass,\n keyConverter, valueConverter, jconf)" }, { "instruction": "Write or improve a Python function based on this description:\n\nOutput a Python RDD of key-value pairs (of form C{RDD[(K, V)]}) to any Hadoop file\n system, using the L{org.apache.hadoop.io.Writable} types that we convert from the\n RDD's key and value types. The mechanism is as follows:\n\n 1. Pyrolite is used to convert pickled Python RDD into RDD of Java objects.\n 2. Keys and values of this Java RDD are converted to Writables and written out.\n\n :param path: path to sequence file\n :param compressionCodecClass: (None by default)", "output": "def saveAsSequenceFile(self, path, compressionCodecClass=None):\n \"\"\"\n Output a Python RDD of key-value pairs (of form C{RDD[(K, V)]}) to any Hadoop file\n system, using the L{org.apache.hadoop.io.Writable} types that we convert from the\n RDD's key and value types. The mechanism is as follows:\n\n 1. Pyrolite is used to convert pickled Python RDD into RDD of Java objects.\n 2. Keys and values of this Java RDD are converted to Writables and written out.\n\n :param path: path to sequence file\n :param compressionCodecClass: (None by default)\n \"\"\"\n pickledRDD = self._pickled()\n self.ctx._jvm.PythonRDD.saveAsSequenceFile(pickledRDD._jrdd, True,\n path, compressionCodecClass)" }, { "instruction": "Write or improve a Python function based on this description:\n\nSave this RDD as a SequenceFile of serialized objects. The serializer\n used is L{pyspark.serializers.PickleSerializer}, default batch size\n is 10.\n\n >>> tmpFile = NamedTemporaryFile(delete=True)\n >>> tmpFile.close()\n >>> sc.parallelize([1, 2, 'spark', 'rdd']).saveAsPickleFile(tmpFile.name, 3)\n >>> sorted(sc.pickleFile(tmpFile.name, 5).map(str).collect())\n ['1', '2', 'rdd', 'spark']", "output": "def saveAsPickleFile(self, path, batchSize=10):\n \"\"\"\n Save this RDD as a SequenceFile of serialized objects. The serializer\n used is L{pyspark.serializers.PickleSerializer}, default batch size\n is 10.\n\n >>> tmpFile = NamedTemporaryFile(delete=True)\n >>> tmpFile.close()\n >>> sc.parallelize([1, 2, 'spark', 'rdd']).saveAsPickleFile(tmpFile.name, 3)\n >>> sorted(sc.pickleFile(tmpFile.name, 5).map(str).collect())\n ['1', '2', 'rdd', 'spark']\n \"\"\"\n if batchSize == 0:\n ser = AutoBatchedSerializer(PickleSerializer())\n else:\n ser = BatchedSerializer(PickleSerializer(), batchSize)\n self._reserialize(ser)._jrdd.saveAsObjectFile(path)" }, { "instruction": "Write or improve a Python function based on this description:\n\nSave this RDD as a text file, using string representations of elements.\n\n @param path: path to text file\n @param compressionCodecClass: (None by default) string i.e.\n \"org.apache.hadoop.io.compress.GzipCodec\"\n\n >>> tempFile = NamedTemporaryFile(delete=True)\n >>> tempFile.close()\n >>> sc.parallelize(range(10)).saveAsTextFile(tempFile.name)\n >>> from fileinput import input\n >>> from glob import glob\n >>> ''.join(sorted(input(glob(tempFile.name + \"/part-0000*\"))))\n '0\\\\n1\\\\n2\\\\n3\\\\n4\\\\n5\\\\n6\\\\n7\\\\n8\\\\n9\\\\n'\n\n Empty lines are tolerated when saving to text files.\n\n >>> tempFile2 = NamedTemporaryFile(delete=True)\n >>> tempFile2.close()\n >>> sc.parallelize(['', 'foo', '', 'bar', '']).saveAsTextFile(tempFile2.name)\n >>> ''.join(sorted(input(glob(tempFile2.name + \"/part-0000*\"))))\n '\\\\n\\\\n\\\\nbar\\\\nfoo\\\\n'\n\n Using compressionCodecClass\n\n >>> tempFile3 = NamedTemporaryFile(delete=True)\n >>> tempFile3.close()\n >>> codec = \"org.apache.hadoop.io.compress.GzipCodec\"\n >>> sc.parallelize(['foo', 'bar']).saveAsTextFile(tempFile3.name, codec)\n >>> from fileinput import input, hook_compressed\n >>> result = sorted(input(glob(tempFile3.name + \"/part*.gz\"), openhook=hook_compressed))\n >>> b''.join(result).decode('utf-8')\n u'bar\\\\nfoo\\\\n'", "output": "def saveAsTextFile(self, path, compressionCodecClass=None):\n \"\"\"\n Save this RDD as a text file, using string representations of elements.\n\n @param path: path to text file\n @param compressionCodecClass: (None by default) string i.e.\n \"org.apache.hadoop.io.compress.GzipCodec\"\n\n >>> tempFile = NamedTemporaryFile(delete=True)\n >>> tempFile.close()\n >>> sc.parallelize(range(10)).saveAsTextFile(tempFile.name)\n >>> from fileinput import input\n >>> from glob import glob\n >>> ''.join(sorted(input(glob(tempFile.name + \"/part-0000*\"))))\n '0\\\\n1\\\\n2\\\\n3\\\\n4\\\\n5\\\\n6\\\\n7\\\\n8\\\\n9\\\\n'\n\n Empty lines are tolerated when saving to text files.\n\n >>> tempFile2 = NamedTemporaryFile(delete=True)\n >>> tempFile2.close()\n >>> sc.parallelize(['', 'foo', '', 'bar', '']).saveAsTextFile(tempFile2.name)\n >>> ''.join(sorted(input(glob(tempFile2.name + \"/part-0000*\"))))\n '\\\\n\\\\n\\\\nbar\\\\nfoo\\\\n'\n\n Using compressionCodecClass\n\n >>> tempFile3 = NamedTemporaryFile(delete=True)\n >>> tempFile3.close()\n >>> codec = \"org.apache.hadoop.io.compress.GzipCodec\"\n >>> sc.parallelize(['foo', 'bar']).saveAsTextFile(tempFile3.name, codec)\n >>> from fileinput import input, hook_compressed\n >>> result = sorted(input(glob(tempFile3.name + \"/part*.gz\"), openhook=hook_compressed))\n >>> b''.join(result).decode('utf-8')\n u'bar\\\\nfoo\\\\n'\n \"\"\"\n def func(split, iterator):\n for x in iterator:\n if not isinstance(x, (unicode, bytes)):\n x = unicode(x)\n if isinstance(x, unicode):\n x = x.encode(\"utf-8\")\n yield x\n keyed = self.mapPartitionsWithIndex(func)\n keyed._bypass_serializer = True\n if compressionCodecClass:\n compressionCodec = self.ctx._jvm.java.lang.Class.forName(compressionCodecClass)\n keyed._jrdd.map(self.ctx._jvm.BytesToString()).saveAsTextFile(path, compressionCodec)\n else:\n keyed._jrdd.map(self.ctx._jvm.BytesToString()).saveAsTextFile(path)" }, { "instruction": "Write or improve a Python function based on this description:\n\nMerge the values for each key using an associative and commutative reduce function.\n\n This will also perform the merging locally on each mapper before\n sending results to a reducer, similarly to a \"combiner\" in MapReduce.\n\n Output will be partitioned with C{numPartitions} partitions, or\n the default parallelism level if C{numPartitions} is not specified.\n Default partitioner is hash-partition.\n\n >>> from operator import add\n >>> rdd = sc.parallelize([(\"a\", 1), (\"b\", 1), (\"a\", 1)])\n >>> sorted(rdd.reduceByKey(add).collect())\n [('a', 2), ('b', 1)]", "output": "def reduceByKey(self, func, numPartitions=None, partitionFunc=portable_hash):\n \"\"\"\n Merge the values for each key using an associative and commutative reduce function.\n\n This will also perform the merging locally on each mapper before\n sending results to a reducer, similarly to a \"combiner\" in MapReduce.\n\n Output will be partitioned with C{numPartitions} partitions, or\n the default parallelism level if C{numPartitions} is not specified.\n Default partitioner is hash-partition.\n\n >>> from operator import add\n >>> rdd = sc.parallelize([(\"a\", 1), (\"b\", 1), (\"a\", 1)])\n >>> sorted(rdd.reduceByKey(add).collect())\n [('a', 2), ('b', 1)]\n \"\"\"\n return self.combineByKey(lambda x: x, func, func, numPartitions, partitionFunc)" }, { "instruction": "Write or improve a Python function based on this description:\n\nMerge the values for each key using an associative and commutative reduce function, but\n return the results immediately to the master as a dictionary.\n\n This will also perform the merging locally on each mapper before\n sending results to a reducer, similarly to a \"combiner\" in MapReduce.\n\n >>> from operator import add\n >>> rdd = sc.parallelize([(\"a\", 1), (\"b\", 1), (\"a\", 1)])\n >>> sorted(rdd.reduceByKeyLocally(add).items())\n [('a', 2), ('b', 1)]", "output": "def reduceByKeyLocally(self, func):\n \"\"\"\n Merge the values for each key using an associative and commutative reduce function, but\n return the results immediately to the master as a dictionary.\n\n This will also perform the merging locally on each mapper before\n sending results to a reducer, similarly to a \"combiner\" in MapReduce.\n\n >>> from operator import add\n >>> rdd = sc.parallelize([(\"a\", 1), (\"b\", 1), (\"a\", 1)])\n >>> sorted(rdd.reduceByKeyLocally(add).items())\n [('a', 2), ('b', 1)]\n \"\"\"\n func = fail_on_stopiteration(func)\n\n def reducePartition(iterator):\n m = {}\n for k, v in iterator:\n m[k] = func(m[k], v) if k in m else v\n yield m\n\n def mergeMaps(m1, m2):\n for k, v in m2.items():\n m1[k] = func(m1[k], v) if k in m1 else v\n return m1\n return self.mapPartitions(reducePartition).reduce(mergeMaps)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn a copy of the RDD partitioned using the specified partitioner.\n\n >>> pairs = sc.parallelize([1, 2, 3, 4, 2, 4, 1]).map(lambda x: (x, x))\n >>> sets = pairs.partitionBy(2).glom().collect()\n >>> len(set(sets[0]).intersection(set(sets[1])))\n 0", "output": "def partitionBy(self, numPartitions, partitionFunc=portable_hash):\n \"\"\"\n Return a copy of the RDD partitioned using the specified partitioner.\n\n >>> pairs = sc.parallelize([1, 2, 3, 4, 2, 4, 1]).map(lambda x: (x, x))\n >>> sets = pairs.partitionBy(2).glom().collect()\n >>> len(set(sets[0]).intersection(set(sets[1])))\n 0\n \"\"\"\n if numPartitions is None:\n numPartitions = self._defaultReducePartitions()\n partitioner = Partitioner(numPartitions, partitionFunc)\n if self.partitioner == partitioner:\n return self\n\n # Transferring O(n) objects to Java is too expensive.\n # Instead, we'll form the hash buckets in Python,\n # transferring O(numPartitions) objects to Java.\n # Each object is a (splitNumber, [objects]) pair.\n # In order to avoid too huge objects, the objects are\n # grouped into chunks.\n outputSerializer = self.ctx._unbatched_serializer\n\n limit = (_parse_memory(self.ctx._conf.get(\n \"spark.python.worker.memory\", \"512m\")) / 2)\n\n def add_shuffle_key(split, iterator):\n\n buckets = defaultdict(list)\n c, batch = 0, min(10 * numPartitions, 1000)\n\n for k, v in iterator:\n buckets[partitionFunc(k) % numPartitions].append((k, v))\n c += 1\n\n # check used memory and avg size of chunk of objects\n if (c % 1000 == 0 and get_used_memory() > limit\n or c > batch):\n n, size = len(buckets), 0\n for split in list(buckets.keys()):\n yield pack_long(split)\n d = outputSerializer.dumps(buckets[split])\n del buckets[split]\n yield d\n size += len(d)\n\n avg = int(size / n) >> 20\n # let 1M < avg < 10M\n if avg < 1:\n batch *= 1.5\n elif avg > 10:\n batch = max(int(batch / 1.5), 1)\n c = 0\n\n for split, items in buckets.items():\n yield pack_long(split)\n yield outputSerializer.dumps(items)\n\n keyed = self.mapPartitionsWithIndex(add_shuffle_key, preservesPartitioning=True)\n keyed._bypass_serializer = True\n with SCCallSiteSync(self.context) as css:\n pairRDD = self.ctx._jvm.PairwiseRDD(\n keyed._jrdd.rdd()).asJavaPairRDD()\n jpartitioner = self.ctx._jvm.PythonPartitioner(numPartitions,\n id(partitionFunc))\n jrdd = self.ctx._jvm.PythonRDD.valueOfPair(pairRDD.partitionBy(jpartitioner))\n rdd = RDD(jrdd, self.ctx, BatchedSerializer(outputSerializer))\n rdd.partitioner = partitioner\n return rdd" }, { "instruction": "Write or improve a Python function based on this description:\n\nGeneric function to combine the elements for each key using a custom\n set of aggregation functions.\n\n Turns an RDD[(K, V)] into a result of type RDD[(K, C)], for a \"combined\n type\" C.\n\n Users provide three functions:\n\n - C{createCombiner}, which turns a V into a C (e.g., creates\n a one-element list)\n - C{mergeValue}, to merge a V into a C (e.g., adds it to the end of\n a list)\n - C{mergeCombiners}, to combine two C's into a single one (e.g., merges\n the lists)\n\n To avoid memory allocation, both mergeValue and mergeCombiners are allowed to\n modify and return their first argument instead of creating a new C.\n\n In addition, users can control the partitioning of the output RDD.\n\n .. note:: V and C can be different -- for example, one might group an RDD of type\n (Int, Int) into an RDD of type (Int, List[Int]).\n\n >>> x = sc.parallelize([(\"a\", 1), (\"b\", 1), (\"a\", 2)])\n >>> def to_list(a):\n ... return [a]\n ...\n >>> def append(a, b):\n ... a.append(b)\n ... return a\n ...\n >>> def extend(a, b):\n ... a.extend(b)\n ... return a\n ...\n >>> sorted(x.combineByKey(to_list, append, extend).collect())\n [('a', [1, 2]), ('b', [1])]", "output": "def combineByKey(self, createCombiner, mergeValue, mergeCombiners,\n numPartitions=None, partitionFunc=portable_hash):\n \"\"\"\n Generic function to combine the elements for each key using a custom\n set of aggregation functions.\n\n Turns an RDD[(K, V)] into a result of type RDD[(K, C)], for a \"combined\n type\" C.\n\n Users provide three functions:\n\n - C{createCombiner}, which turns a V into a C (e.g., creates\n a one-element list)\n - C{mergeValue}, to merge a V into a C (e.g., adds it to the end of\n a list)\n - C{mergeCombiners}, to combine two C's into a single one (e.g., merges\n the lists)\n\n To avoid memory allocation, both mergeValue and mergeCombiners are allowed to\n modify and return their first argument instead of creating a new C.\n\n In addition, users can control the partitioning of the output RDD.\n\n .. note:: V and C can be different -- for example, one might group an RDD of type\n (Int, Int) into an RDD of type (Int, List[Int]).\n\n >>> x = sc.parallelize([(\"a\", 1), (\"b\", 1), (\"a\", 2)])\n >>> def to_list(a):\n ... return [a]\n ...\n >>> def append(a, b):\n ... a.append(b)\n ... return a\n ...\n >>> def extend(a, b):\n ... a.extend(b)\n ... return a\n ...\n >>> sorted(x.combineByKey(to_list, append, extend).collect())\n [('a', [1, 2]), ('b', [1])]\n \"\"\"\n if numPartitions is None:\n numPartitions = self._defaultReducePartitions()\n\n serializer = self.ctx.serializer\n memory = self._memory_limit()\n agg = Aggregator(createCombiner, mergeValue, mergeCombiners)\n\n def combineLocally(iterator):\n merger = ExternalMerger(agg, memory * 0.9, serializer)\n merger.mergeValues(iterator)\n return merger.items()\n\n locally_combined = self.mapPartitions(combineLocally, preservesPartitioning=True)\n shuffled = locally_combined.partitionBy(numPartitions, partitionFunc)\n\n def _mergeCombiners(iterator):\n merger = ExternalMerger(agg, memory, serializer)\n merger.mergeCombiners(iterator)\n return merger.items()\n\n return shuffled.mapPartitions(_mergeCombiners, preservesPartitioning=True)" }, { "instruction": "Write or improve a Python function based on this description:\n\nAggregate the values of each key, using given combine functions and a neutral\n \"zero value\". This function can return a different result type, U, than the type\n of the values in this RDD, V. Thus, we need one operation for merging a V into\n a U and one operation for merging two U's, The former operation is used for merging\n values within a partition, and the latter is used for merging values between\n partitions. To avoid memory allocation, both of these functions are\n allowed to modify and return their first argument instead of creating a new U.", "output": "def aggregateByKey(self, zeroValue, seqFunc, combFunc, numPartitions=None,\n partitionFunc=portable_hash):\n \"\"\"\n Aggregate the values of each key, using given combine functions and a neutral\n \"zero value\". This function can return a different result type, U, than the type\n of the values in this RDD, V. Thus, we need one operation for merging a V into\n a U and one operation for merging two U's, The former operation is used for merging\n values within a partition, and the latter is used for merging values between\n partitions. To avoid memory allocation, both of these functions are\n allowed to modify and return their first argument instead of creating a new U.\n \"\"\"\n def createZero():\n return copy.deepcopy(zeroValue)\n\n return self.combineByKey(\n lambda v: seqFunc(createZero(), v), seqFunc, combFunc, numPartitions, partitionFunc)" }, { "instruction": "Write or improve a Python function based on this description:\n\nMerge the values for each key using an associative function \"func\"\n and a neutral \"zeroValue\" which may be added to the result an\n arbitrary number of times, and must not change the result\n (e.g., 0 for addition, or 1 for multiplication.).\n\n >>> rdd = sc.parallelize([(\"a\", 1), (\"b\", 1), (\"a\", 1)])\n >>> from operator import add\n >>> sorted(rdd.foldByKey(0, add).collect())\n [('a', 2), ('b', 1)]", "output": "def foldByKey(self, zeroValue, func, numPartitions=None, partitionFunc=portable_hash):\n \"\"\"\n Merge the values for each key using an associative function \"func\"\n and a neutral \"zeroValue\" which may be added to the result an\n arbitrary number of times, and must not change the result\n (e.g., 0 for addition, or 1 for multiplication.).\n\n >>> rdd = sc.parallelize([(\"a\", 1), (\"b\", 1), (\"a\", 1)])\n >>> from operator import add\n >>> sorted(rdd.foldByKey(0, add).collect())\n [('a', 2), ('b', 1)]\n \"\"\"\n def createZero():\n return copy.deepcopy(zeroValue)\n\n return self.combineByKey(lambda v: func(createZero(), v), func, func, numPartitions,\n partitionFunc)" }, { "instruction": "Write or improve a Python function based on this description:\n\nGroup the values for each key in the RDD into a single sequence.\n Hash-partitions the resulting RDD with numPartitions partitions.\n\n .. note:: If you are grouping in order to perform an aggregation (such as a\n sum or average) over each key, using reduceByKey or aggregateByKey will\n provide much better performance.\n\n >>> rdd = sc.parallelize([(\"a\", 1), (\"b\", 1), (\"a\", 1)])\n >>> sorted(rdd.groupByKey().mapValues(len).collect())\n [('a', 2), ('b', 1)]\n >>> sorted(rdd.groupByKey().mapValues(list).collect())\n [('a', [1, 1]), ('b', [1])]", "output": "def groupByKey(self, numPartitions=None, partitionFunc=portable_hash):\n \"\"\"\n Group the values for each key in the RDD into a single sequence.\n Hash-partitions the resulting RDD with numPartitions partitions.\n\n .. note:: If you are grouping in order to perform an aggregation (such as a\n sum or average) over each key, using reduceByKey or aggregateByKey will\n provide much better performance.\n\n >>> rdd = sc.parallelize([(\"a\", 1), (\"b\", 1), (\"a\", 1)])\n >>> sorted(rdd.groupByKey().mapValues(len).collect())\n [('a', 2), ('b', 1)]\n >>> sorted(rdd.groupByKey().mapValues(list).collect())\n [('a', [1, 1]), ('b', [1])]\n \"\"\"\n def createCombiner(x):\n return [x]\n\n def mergeValue(xs, x):\n xs.append(x)\n return xs\n\n def mergeCombiners(a, b):\n a.extend(b)\n return a\n\n memory = self._memory_limit()\n serializer = self._jrdd_deserializer\n agg = Aggregator(createCombiner, mergeValue, mergeCombiners)\n\n def combine(iterator):\n merger = ExternalMerger(agg, memory * 0.9, serializer)\n merger.mergeValues(iterator)\n return merger.items()\n\n locally_combined = self.mapPartitions(combine, preservesPartitioning=True)\n shuffled = locally_combined.partitionBy(numPartitions, partitionFunc)\n\n def groupByKey(it):\n merger = ExternalGroupBy(agg, memory, serializer)\n merger.mergeCombiners(it)\n return merger.items()\n\n return shuffled.mapPartitions(groupByKey, True).mapValues(ResultIterable)" }, { "instruction": "Write or improve a Python function based on this description:\n\nPass each value in the key-value pair RDD through a flatMap function\n without changing the keys; this also retains the original RDD's\n partitioning.\n\n >>> x = sc.parallelize([(\"a\", [\"x\", \"y\", \"z\"]), (\"b\", [\"p\", \"r\"])])\n >>> def f(x): return x\n >>> x.flatMapValues(f).collect()\n [('a', 'x'), ('a', 'y'), ('a', 'z'), ('b', 'p'), ('b', 'r')]", "output": "def flatMapValues(self, f):\n \"\"\"\n Pass each value in the key-value pair RDD through a flatMap function\n without changing the keys; this also retains the original RDD's\n partitioning.\n\n >>> x = sc.parallelize([(\"a\", [\"x\", \"y\", \"z\"]), (\"b\", [\"p\", \"r\"])])\n >>> def f(x): return x\n >>> x.flatMapValues(f).collect()\n [('a', 'x'), ('a', 'y'), ('a', 'z'), ('b', 'p'), ('b', 'r')]\n \"\"\"\n flat_map_fn = lambda kv: ((kv[0], x) for x in f(kv[1]))\n return self.flatMap(flat_map_fn, preservesPartitioning=True)" }, { "instruction": "Write or improve a Python function based on this description:\n\nPass each value in the key-value pair RDD through a map function\n without changing the keys; this also retains the original RDD's\n partitioning.\n\n >>> x = sc.parallelize([(\"a\", [\"apple\", \"banana\", \"lemon\"]), (\"b\", [\"grapes\"])])\n >>> def f(x): return len(x)\n >>> x.mapValues(f).collect()\n [('a', 3), ('b', 1)]", "output": "def mapValues(self, f):\n \"\"\"\n Pass each value in the key-value pair RDD through a map function\n without changing the keys; this also retains the original RDD's\n partitioning.\n\n >>> x = sc.parallelize([(\"a\", [\"apple\", \"banana\", \"lemon\"]), (\"b\", [\"grapes\"])])\n >>> def f(x): return len(x)\n >>> x.mapValues(f).collect()\n [('a', 3), ('b', 1)]\n \"\"\"\n map_values_fn = lambda kv: (kv[0], f(kv[1]))\n return self.map(map_values_fn, preservesPartitioning=True)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn a subset of this RDD sampled by key (via stratified sampling).\n Create a sample of this RDD using variable sampling rates for\n different keys as specified by fractions, a key to sampling rate map.\n\n >>> fractions = {\"a\": 0.2, \"b\": 0.1}\n >>> rdd = sc.parallelize(fractions.keys()).cartesian(sc.parallelize(range(0, 1000)))\n >>> sample = dict(rdd.sampleByKey(False, fractions, 2).groupByKey().collect())\n >>> 100 < len(sample[\"a\"]) < 300 and 50 < len(sample[\"b\"]) < 150\n True\n >>> max(sample[\"a\"]) <= 999 and min(sample[\"a\"]) >= 0\n True\n >>> max(sample[\"b\"]) <= 999 and min(sample[\"b\"]) >= 0\n True", "output": "def sampleByKey(self, withReplacement, fractions, seed=None):\n \"\"\"\n Return a subset of this RDD sampled by key (via stratified sampling).\n Create a sample of this RDD using variable sampling rates for\n different keys as specified by fractions, a key to sampling rate map.\n\n >>> fractions = {\"a\": 0.2, \"b\": 0.1}\n >>> rdd = sc.parallelize(fractions.keys()).cartesian(sc.parallelize(range(0, 1000)))\n >>> sample = dict(rdd.sampleByKey(False, fractions, 2).groupByKey().collect())\n >>> 100 < len(sample[\"a\"]) < 300 and 50 < len(sample[\"b\"]) < 150\n True\n >>> max(sample[\"a\"]) <= 999 and min(sample[\"a\"]) >= 0\n True\n >>> max(sample[\"b\"]) <= 999 and min(sample[\"b\"]) >= 0\n True\n \"\"\"\n for fraction in fractions.values():\n assert fraction >= 0.0, \"Negative fraction value: %s\" % fraction\n return self.mapPartitionsWithIndex(\n RDDStratifiedSampler(withReplacement, fractions, seed).func, True)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn each (key, value) pair in C{self} that has no pair with matching\n key in C{other}.\n\n >>> x = sc.parallelize([(\"a\", 1), (\"b\", 4), (\"b\", 5), (\"a\", 2)])\n >>> y = sc.parallelize([(\"a\", 3), (\"c\", None)])\n >>> sorted(x.subtractByKey(y).collect())\n [('b', 4), ('b', 5)]", "output": "def subtractByKey(self, other, numPartitions=None):\n \"\"\"\n Return each (key, value) pair in C{self} that has no pair with matching\n key in C{other}.\n\n >>> x = sc.parallelize([(\"a\", 1), (\"b\", 4), (\"b\", 5), (\"a\", 2)])\n >>> y = sc.parallelize([(\"a\", 3), (\"c\", None)])\n >>> sorted(x.subtractByKey(y).collect())\n [('b', 4), ('b', 5)]\n \"\"\"\n def filter_func(pair):\n key, (val1, val2) = pair\n return val1 and not val2\n return self.cogroup(other, numPartitions).filter(filter_func).flatMapValues(lambda x: x[0])" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn each value in C{self} that is not contained in C{other}.\n\n >>> x = sc.parallelize([(\"a\", 1), (\"b\", 4), (\"b\", 5), (\"a\", 3)])\n >>> y = sc.parallelize([(\"a\", 3), (\"c\", None)])\n >>> sorted(x.subtract(y).collect())\n [('a', 1), ('b', 4), ('b', 5)]", "output": "def subtract(self, other, numPartitions=None):\n \"\"\"\n Return each value in C{self} that is not contained in C{other}.\n\n >>> x = sc.parallelize([(\"a\", 1), (\"b\", 4), (\"b\", 5), (\"a\", 3)])\n >>> y = sc.parallelize([(\"a\", 3), (\"c\", None)])\n >>> sorted(x.subtract(y).collect())\n [('a', 1), ('b', 4), ('b', 5)]\n \"\"\"\n # note: here 'True' is just a placeholder\n rdd = other.map(lambda x: (x, True))\n return self.map(lambda x: (x, True)).subtractByKey(rdd, numPartitions).keys()" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn a new RDD that is reduced into `numPartitions` partitions.\n\n >>> sc.parallelize([1, 2, 3, 4, 5], 3).glom().collect()\n [[1], [2, 3], [4, 5]]\n >>> sc.parallelize([1, 2, 3, 4, 5], 3).coalesce(1).glom().collect()\n [[1, 2, 3, 4, 5]]", "output": "def coalesce(self, numPartitions, shuffle=False):\n \"\"\"\n Return a new RDD that is reduced into `numPartitions` partitions.\n\n >>> sc.parallelize([1, 2, 3, 4, 5], 3).glom().collect()\n [[1], [2, 3], [4, 5]]\n >>> sc.parallelize([1, 2, 3, 4, 5], 3).coalesce(1).glom().collect()\n [[1, 2, 3, 4, 5]]\n \"\"\"\n if shuffle:\n # Decrease the batch size in order to distribute evenly the elements across output\n # partitions. Otherwise, repartition will possibly produce highly skewed partitions.\n batchSize = min(10, self.ctx._batchSize or 1024)\n ser = BatchedSerializer(PickleSerializer(), batchSize)\n selfCopy = self._reserialize(ser)\n jrdd_deserializer = selfCopy._jrdd_deserializer\n jrdd = selfCopy._jrdd.coalesce(numPartitions, shuffle)\n else:\n jrdd_deserializer = self._jrdd_deserializer\n jrdd = self._jrdd.coalesce(numPartitions, shuffle)\n return RDD(jrdd, self.ctx, jrdd_deserializer)" }, { "instruction": "Write or improve a Python function based on this description:\n\nZips this RDD with another one, returning key-value pairs with the\n first element in each RDD second element in each RDD, etc. Assumes\n that the two RDDs have the same number of partitions and the same\n number of elements in each partition (e.g. one was made through\n a map on the other).\n\n >>> x = sc.parallelize(range(0,5))\n >>> y = sc.parallelize(range(1000, 1005))\n >>> x.zip(y).collect()\n [(0, 1000), (1, 1001), (2, 1002), (3, 1003), (4, 1004)]", "output": "def zip(self, other):\n \"\"\"\n Zips this RDD with another one, returning key-value pairs with the\n first element in each RDD second element in each RDD, etc. Assumes\n that the two RDDs have the same number of partitions and the same\n number of elements in each partition (e.g. one was made through\n a map on the other).\n\n >>> x = sc.parallelize(range(0,5))\n >>> y = sc.parallelize(range(1000, 1005))\n >>> x.zip(y).collect()\n [(0, 1000), (1, 1001), (2, 1002), (3, 1003), (4, 1004)]\n \"\"\"\n def get_batch_size(ser):\n if isinstance(ser, BatchedSerializer):\n return ser.batchSize\n return 1 # not batched\n\n def batch_as(rdd, batchSize):\n return rdd._reserialize(BatchedSerializer(PickleSerializer(), batchSize))\n\n my_batch = get_batch_size(self._jrdd_deserializer)\n other_batch = get_batch_size(other._jrdd_deserializer)\n if my_batch != other_batch or not my_batch:\n # use the smallest batchSize for both of them\n batchSize = min(my_batch, other_batch)\n if batchSize <= 0:\n # auto batched or unlimited\n batchSize = 100\n other = batch_as(other, batchSize)\n self = batch_as(self, batchSize)\n\n if self.getNumPartitions() != other.getNumPartitions():\n raise ValueError(\"Can only zip with RDD which has the same number of partitions\")\n\n # There will be an Exception in JVM if there are different number\n # of items in each partitions.\n pairRDD = self._jrdd.zip(other._jrdd)\n deserializer = PairDeserializer(self._jrdd_deserializer,\n other._jrdd_deserializer)\n return RDD(pairRDD, self.ctx, deserializer)" }, { "instruction": "Write or improve a Python function based on this description:\n\nZips this RDD with its element indices.\n\n The ordering is first based on the partition index and then the\n ordering of items within each partition. So the first item in\n the first partition gets index 0, and the last item in the last\n partition receives the largest index.\n\n This method needs to trigger a spark job when this RDD contains\n more than one partitions.\n\n >>> sc.parallelize([\"a\", \"b\", \"c\", \"d\"], 3).zipWithIndex().collect()\n [('a', 0), ('b', 1), ('c', 2), ('d', 3)]", "output": "def zipWithIndex(self):\n \"\"\"\n Zips this RDD with its element indices.\n\n The ordering is first based on the partition index and then the\n ordering of items within each partition. So the first item in\n the first partition gets index 0, and the last item in the last\n partition receives the largest index.\n\n This method needs to trigger a spark job when this RDD contains\n more than one partitions.\n\n >>> sc.parallelize([\"a\", \"b\", \"c\", \"d\"], 3).zipWithIndex().collect()\n [('a', 0), ('b', 1), ('c', 2), ('d', 3)]\n \"\"\"\n starts = [0]\n if self.getNumPartitions() > 1:\n nums = self.mapPartitions(lambda it: [sum(1 for i in it)]).collect()\n for i in range(len(nums) - 1):\n starts.append(starts[-1] + nums[i])\n\n def func(k, it):\n for i, v in enumerate(it, starts[k]):\n yield v, i\n\n return self.mapPartitionsWithIndex(func)" }, { "instruction": "Write or improve a Python function based on this description:\n\nZips this RDD with generated unique Long ids.\n\n Items in the kth partition will get ids k, n+k, 2*n+k, ..., where\n n is the number of partitions. So there may exist gaps, but this\n method won't trigger a spark job, which is different from\n L{zipWithIndex}\n\n >>> sc.parallelize([\"a\", \"b\", \"c\", \"d\", \"e\"], 3).zipWithUniqueId().collect()\n [('a', 0), ('b', 1), ('c', 4), ('d', 2), ('e', 5)]", "output": "def zipWithUniqueId(self):\n \"\"\"\n Zips this RDD with generated unique Long ids.\n\n Items in the kth partition will get ids k, n+k, 2*n+k, ..., where\n n is the number of partitions. So there may exist gaps, but this\n method won't trigger a spark job, which is different from\n L{zipWithIndex}\n\n >>> sc.parallelize([\"a\", \"b\", \"c\", \"d\", \"e\"], 3).zipWithUniqueId().collect()\n [('a', 0), ('b', 1), ('c', 4), ('d', 2), ('e', 5)]\n \"\"\"\n n = self.getNumPartitions()\n\n def func(k, it):\n for i, v in enumerate(it):\n yield v, i * n + k\n\n return self.mapPartitionsWithIndex(func)" }, { "instruction": "Write or improve a Python function based on this description:\n\nGet the RDD's current storage level.\n\n >>> rdd1 = sc.parallelize([1,2])\n >>> rdd1.getStorageLevel()\n StorageLevel(False, False, False, False, 1)\n >>> print(rdd1.getStorageLevel())\n Serialized 1x Replicated", "output": "def getStorageLevel(self):\n \"\"\"\n Get the RDD's current storage level.\n\n >>> rdd1 = sc.parallelize([1,2])\n >>> rdd1.getStorageLevel()\n StorageLevel(False, False, False, False, 1)\n >>> print(rdd1.getStorageLevel())\n Serialized 1x Replicated\n \"\"\"\n java_storage_level = self._jrdd.getStorageLevel()\n storage_level = StorageLevel(java_storage_level.useDisk(),\n java_storage_level.useMemory(),\n java_storage_level.useOffHeap(),\n java_storage_level.deserialized(),\n java_storage_level.replication())\n return storage_level" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns the default number of partitions to use during reduce tasks (e.g., groupBy).\n If spark.default.parallelism is set, then we'll use the value from SparkContext\n defaultParallelism, otherwise we'll use the number of partitions in this RDD.\n\n This mirrors the behavior of the Scala Partitioner#defaultPartitioner, intended to reduce\n the likelihood of OOMs. Once PySpark adopts Partitioner-based APIs, this behavior will\n be inherent.", "output": "def _defaultReducePartitions(self):\n \"\"\"\n Returns the default number of partitions to use during reduce tasks (e.g., groupBy).\n If spark.default.parallelism is set, then we'll use the value from SparkContext\n defaultParallelism, otherwise we'll use the number of partitions in this RDD.\n\n This mirrors the behavior of the Scala Partitioner#defaultPartitioner, intended to reduce\n the likelihood of OOMs. Once PySpark adopts Partitioner-based APIs, this behavior will\n be inherent.\n \"\"\"\n if self.ctx._conf.contains(\"spark.default.parallelism\"):\n return self.ctx.defaultParallelism\n else:\n return self.getNumPartitions()" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn the list of values in the RDD for key `key`. This operation\n is done efficiently if the RDD has a known partitioner by only\n searching the partition that the key maps to.\n\n >>> l = range(1000)\n >>> rdd = sc.parallelize(zip(l, l), 10)\n >>> rdd.lookup(42) # slow\n [42]\n >>> sorted = rdd.sortByKey()\n >>> sorted.lookup(42) # fast\n [42]\n >>> sorted.lookup(1024)\n []\n >>> rdd2 = sc.parallelize([(('a', 'b'), 'c')]).groupByKey()\n >>> list(rdd2.lookup(('a', 'b'))[0])\n ['c']", "output": "def lookup(self, key):\n \"\"\"\n Return the list of values in the RDD for key `key`. This operation\n is done efficiently if the RDD has a known partitioner by only\n searching the partition that the key maps to.\n\n >>> l = range(1000)\n >>> rdd = sc.parallelize(zip(l, l), 10)\n >>> rdd.lookup(42) # slow\n [42]\n >>> sorted = rdd.sortByKey()\n >>> sorted.lookup(42) # fast\n [42]\n >>> sorted.lookup(1024)\n []\n >>> rdd2 = sc.parallelize([(('a', 'b'), 'c')]).groupByKey()\n >>> list(rdd2.lookup(('a', 'b'))[0])\n ['c']\n \"\"\"\n values = self.filter(lambda kv: kv[0] == key).values()\n\n if self.partitioner is not None:\n return self.ctx.runJob(values, lambda x: x, [self.partitioner(key)])\n\n return values.collect()" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn a JavaRDD of Object by unpickling\n\n It will convert each Python object into Java object by Pyrolite, whenever the\n RDD is serialized in batch or not.", "output": "def _to_java_object_rdd(self):\n \"\"\" Return a JavaRDD of Object by unpickling\n\n It will convert each Python object into Java object by Pyrolite, whenever the\n RDD is serialized in batch or not.\n \"\"\"\n rdd = self._pickled()\n return self.ctx._jvm.SerDeUtil.pythonToJava(rdd._jrdd, True)" }, { "instruction": "Write or improve a Python function based on this description:\n\n.. note:: Experimental\n\n Approximate version of count() that returns a potentially incomplete\n result within a timeout, even if not all tasks have finished.\n\n >>> rdd = sc.parallelize(range(1000), 10)\n >>> rdd.countApprox(1000, 1.0)\n 1000", "output": "def countApprox(self, timeout, confidence=0.95):\n \"\"\"\n .. note:: Experimental\n\n Approximate version of count() that returns a potentially incomplete\n result within a timeout, even if not all tasks have finished.\n\n >>> rdd = sc.parallelize(range(1000), 10)\n >>> rdd.countApprox(1000, 1.0)\n 1000\n \"\"\"\n drdd = self.mapPartitions(lambda it: [float(sum(1 for i in it))])\n return int(drdd.sumApprox(timeout, confidence))" }, { "instruction": "Write or improve a Python function based on this description:\n\n.. note:: Experimental\n\n Approximate operation to return the sum within a timeout\n or meet the confidence.\n\n >>> rdd = sc.parallelize(range(1000), 10)\n >>> r = sum(range(1000))\n >>> abs(rdd.sumApprox(1000) - r) / r < 0.05\n True", "output": "def sumApprox(self, timeout, confidence=0.95):\n \"\"\"\n .. note:: Experimental\n\n Approximate operation to return the sum within a timeout\n or meet the confidence.\n\n >>> rdd = sc.parallelize(range(1000), 10)\n >>> r = sum(range(1000))\n >>> abs(rdd.sumApprox(1000) - r) / r < 0.05\n True\n \"\"\"\n jrdd = self.mapPartitions(lambda it: [float(sum(it))])._to_java_object_rdd()\n jdrdd = self.ctx._jvm.JavaDoubleRDD.fromRDD(jrdd.rdd())\n r = jdrdd.sumApprox(timeout, confidence).getFinalValue()\n return BoundedFloat(r.mean(), r.confidence(), r.low(), r.high())" }, { "instruction": "Write or improve a Python function based on this description:\n\n.. note:: Experimental\n\n Approximate operation to return the mean within a timeout\n or meet the confidence.\n\n >>> rdd = sc.parallelize(range(1000), 10)\n >>> r = sum(range(1000)) / 1000.0\n >>> abs(rdd.meanApprox(1000) - r) / r < 0.05\n True", "output": "def meanApprox(self, timeout, confidence=0.95):\n \"\"\"\n .. note:: Experimental\n\n Approximate operation to return the mean within a timeout\n or meet the confidence.\n\n >>> rdd = sc.parallelize(range(1000), 10)\n >>> r = sum(range(1000)) / 1000.0\n >>> abs(rdd.meanApprox(1000) - r) / r < 0.05\n True\n \"\"\"\n jrdd = self.map(float)._to_java_object_rdd()\n jdrdd = self.ctx._jvm.JavaDoubleRDD.fromRDD(jrdd.rdd())\n r = jdrdd.meanApprox(timeout, confidence).getFinalValue()\n return BoundedFloat(r.mean(), r.confidence(), r.low(), r.high())" }, { "instruction": "Write or improve a Python function based on this description:\n\n.. note:: Experimental\n\n Return approximate number of distinct elements in the RDD.\n\n The algorithm used is based on streamlib's implementation of\n `\"HyperLogLog in Practice: Algorithmic Engineering of a State\n of The Art Cardinality Estimation Algorithm\", available here\n `_.\n\n :param relativeSD: Relative accuracy. Smaller values create\n counters that require more space.\n It must be greater than 0.000017.\n\n >>> n = sc.parallelize(range(1000)).map(str).countApproxDistinct()\n >>> 900 < n < 1100\n True\n >>> n = sc.parallelize([i % 20 for i in range(1000)]).countApproxDistinct()\n >>> 16 < n < 24\n True", "output": "def countApproxDistinct(self, relativeSD=0.05):\n \"\"\"\n .. note:: Experimental\n\n Return approximate number of distinct elements in the RDD.\n\n The algorithm used is based on streamlib's implementation of\n `\"HyperLogLog in Practice: Algorithmic Engineering of a State\n of The Art Cardinality Estimation Algorithm\", available here\n `_.\n\n :param relativeSD: Relative accuracy. Smaller values create\n counters that require more space.\n It must be greater than 0.000017.\n\n >>> n = sc.parallelize(range(1000)).map(str).countApproxDistinct()\n >>> 900 < n < 1100\n True\n >>> n = sc.parallelize([i % 20 for i in range(1000)]).countApproxDistinct()\n >>> 16 < n < 24\n True\n \"\"\"\n if relativeSD < 0.000017:\n raise ValueError(\"relativeSD should be greater than 0.000017\")\n # the hash space in Java is 2^32\n hashRDD = self.map(lambda x: portable_hash(x) & 0xFFFFFFFF)\n return hashRDD._to_java_object_rdd().countApproxDistinct(relativeSD)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn an iterator that contains all of the elements in this RDD.\n The iterator will consume as much memory as the largest partition in this RDD.\n\n >>> rdd = sc.parallelize(range(10))\n >>> [x for x in rdd.toLocalIterator()]\n [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]", "output": "def toLocalIterator(self):\n \"\"\"\n Return an iterator that contains all of the elements in this RDD.\n The iterator will consume as much memory as the largest partition in this RDD.\n\n >>> rdd = sc.parallelize(range(10))\n >>> [x for x in rdd.toLocalIterator()]\n [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n \"\"\"\n with SCCallSiteSync(self.context) as css:\n sock_info = self.ctx._jvm.PythonRDD.toLocalIteratorAndServe(self._jrdd.rdd())\n return _load_from_socket(sock_info, self._jrdd_deserializer)" }, { "instruction": "Write or improve a Python function based on this description:\n\n.. note:: Experimental\n\n Returns a new RDD by applying a function to each partition of the wrapped RDD,\n where tasks are launched together in a barrier stage.\n The interface is the same as :func:`RDD.mapPartitions`.\n Please see the API doc there.\n\n .. versionadded:: 2.4.0", "output": "def mapPartitions(self, f, preservesPartitioning=False):\n \"\"\"\n .. note:: Experimental\n\n Returns a new RDD by applying a function to each partition of the wrapped RDD,\n where tasks are launched together in a barrier stage.\n The interface is the same as :func:`RDD.mapPartitions`.\n Please see the API doc there.\n\n .. versionadded:: 2.4.0\n \"\"\"\n def func(s, iterator):\n return f(iterator)\n return PipelinedRDD(self.rdd, func, preservesPartitioning, isFromBarrier=True)" }, { "instruction": "Write or improve a Python function based on this description:\n\nConvert a list of Column (or names) into a JVM Seq of Column.\n\n An optional `converter` could be used to convert items in `cols`\n into JVM Column objects.", "output": "def _to_seq(sc, cols, converter=None):\n \"\"\"\n Convert a list of Column (or names) into a JVM Seq of Column.\n\n An optional `converter` could be used to convert items in `cols`\n into JVM Column objects.\n \"\"\"\n if converter:\n cols = [converter(c) for c in cols]\n return sc._jvm.PythonUtils.toSeq(cols)" }, { "instruction": "Write or improve a Python function based on this description:\n\nConvert a list of Column (or names) into a JVM (Scala) List of Column.\n\n An optional `converter` could be used to convert items in `cols`\n into JVM Column objects.", "output": "def _to_list(sc, cols, converter=None):\n \"\"\"\n Convert a list of Column (or names) into a JVM (Scala) List of Column.\n\n An optional `converter` could be used to convert items in `cols`\n into JVM Column objects.\n \"\"\"\n if converter:\n cols = [converter(c) for c in cols]\n return sc._jvm.PythonUtils.toList(cols)" }, { "instruction": "Write or improve a Python function based on this description:\n\nCreate a method for given unary operator", "output": "def _unary_op(name, doc=\"unary operator\"):\n \"\"\" Create a method for given unary operator \"\"\"\n def _(self):\n jc = getattr(self._jc, name)()\n return Column(jc)\n _.__doc__ = doc\n return _" }, { "instruction": "Write or improve a Python function based on this description:\n\nCreate a method for given binary operator", "output": "def _bin_op(name, doc=\"binary operator\"):\n \"\"\" Create a method for given binary operator\n \"\"\"\n def _(self, other):\n jc = other._jc if isinstance(other, Column) else other\n njc = getattr(self._jc, name)(jc)\n return Column(njc)\n _.__doc__ = doc\n return _" }, { "instruction": "Write or improve a Python function based on this description:\n\nCreate a method for binary operator (this object is on right side)", "output": "def _reverse_op(name, doc=\"binary operator\"):\n \"\"\" Create a method for binary operator (this object is on right side)\n \"\"\"\n def _(self, other):\n jother = _create_column_from_literal(other)\n jc = getattr(jother, name)(self._jc)\n return Column(jc)\n _.__doc__ = doc\n return _" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn a :class:`Column` which is a substring of the column.\n\n :param startPos: start position (int or Column)\n :param length: length of the substring (int or Column)\n\n >>> df.select(df.name.substr(1, 3).alias(\"col\")).collect()\n [Row(col=u'Ali'), Row(col=u'Bob')]", "output": "def substr(self, startPos, length):\n \"\"\"\n Return a :class:`Column` which is a substring of the column.\n\n :param startPos: start position (int or Column)\n :param length: length of the substring (int or Column)\n\n >>> df.select(df.name.substr(1, 3).alias(\"col\")).collect()\n [Row(col=u'Ali'), Row(col=u'Bob')]\n \"\"\"\n if type(startPos) != type(length):\n raise TypeError(\n \"startPos and length must be the same type. \"\n \"Got {startPos_t} and {length_t}, respectively.\"\n .format(\n startPos_t=type(startPos),\n length_t=type(length),\n ))\n if isinstance(startPos, int):\n jc = self._jc.substr(startPos, length)\n elif isinstance(startPos, Column):\n jc = self._jc.substr(startPos._jc, length._jc)\n else:\n raise TypeError(\"Unexpected type: %s\" % type(startPos))\n return Column(jc)" }, { "instruction": "Write or improve a Python function based on this description:\n\nA boolean expression that is evaluated to true if the value of this\n expression is contained by the evaluated values of the arguments.\n\n >>> df[df.name.isin(\"Bob\", \"Mike\")].collect()\n [Row(age=5, name=u'Bob')]\n >>> df[df.age.isin([1, 2, 3])].collect()\n [Row(age=2, name=u'Alice')]", "output": "def isin(self, *cols):\n \"\"\"\n A boolean expression that is evaluated to true if the value of this\n expression is contained by the evaluated values of the arguments.\n\n >>> df[df.name.isin(\"Bob\", \"Mike\")].collect()\n [Row(age=5, name=u'Bob')]\n >>> df[df.age.isin([1, 2, 3])].collect()\n [Row(age=2, name=u'Alice')]\n \"\"\"\n if len(cols) == 1 and isinstance(cols[0], (list, set)):\n cols = cols[0]\n cols = [c._jc if isinstance(c, Column) else _create_column_from_literal(c) for c in cols]\n sc = SparkContext._active_spark_context\n jc = getattr(self._jc, \"isin\")(_to_seq(sc, cols))\n return Column(jc)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns this column aliased with a new name or names (in the case of expressions that\n return more than one column, such as explode).\n\n :param alias: strings of desired column names (collects all positional arguments passed)\n :param metadata: a dict of information to be stored in ``metadata`` attribute of the\n corresponding :class: `StructField` (optional, keyword only argument)\n\n .. versionchanged:: 2.2\n Added optional ``metadata`` argument.\n\n >>> df.select(df.age.alias(\"age2\")).collect()\n [Row(age2=2), Row(age2=5)]\n >>> df.select(df.age.alias(\"age3\", metadata={'max': 99})).schema['age3'].metadata['max']\n 99", "output": "def alias(self, *alias, **kwargs):\n \"\"\"\n Returns this column aliased with a new name or names (in the case of expressions that\n return more than one column, such as explode).\n\n :param alias: strings of desired column names (collects all positional arguments passed)\n :param metadata: a dict of information to be stored in ``metadata`` attribute of the\n corresponding :class: `StructField` (optional, keyword only argument)\n\n .. versionchanged:: 2.2\n Added optional ``metadata`` argument.\n\n >>> df.select(df.age.alias(\"age2\")).collect()\n [Row(age2=2), Row(age2=5)]\n >>> df.select(df.age.alias(\"age3\", metadata={'max': 99})).schema['age3'].metadata['max']\n 99\n \"\"\"\n\n metadata = kwargs.pop('metadata', None)\n assert not kwargs, 'Unexpected kwargs where passed: %s' % kwargs\n\n sc = SparkContext._active_spark_context\n if len(alias) == 1:\n if metadata:\n jmeta = sc._jvm.org.apache.spark.sql.types.Metadata.fromJson(\n json.dumps(metadata))\n return Column(getattr(self._jc, \"as\")(alias[0], jmeta))\n else:\n return Column(getattr(self._jc, \"as\")(alias[0]))\n else:\n if metadata:\n raise ValueError('metadata can only be provided for a single column')\n return Column(getattr(self._jc, \"as\")(_to_seq(sc, list(alias))))" }, { "instruction": "Write or improve a Python function based on this description:\n\nConvert the column into type ``dataType``.\n\n >>> df.select(df.age.cast(\"string\").alias('ages')).collect()\n [Row(ages=u'2'), Row(ages=u'5')]\n >>> df.select(df.age.cast(StringType()).alias('ages')).collect()\n [Row(ages=u'2'), Row(ages=u'5')]", "output": "def cast(self, dataType):\n \"\"\" Convert the column into type ``dataType``.\n\n >>> df.select(df.age.cast(\"string\").alias('ages')).collect()\n [Row(ages=u'2'), Row(ages=u'5')]\n >>> df.select(df.age.cast(StringType()).alias('ages')).collect()\n [Row(ages=u'2'), Row(ages=u'5')]\n \"\"\"\n if isinstance(dataType, basestring):\n jc = self._jc.cast(dataType)\n elif isinstance(dataType, DataType):\n from pyspark.sql import SparkSession\n spark = SparkSession.builder.getOrCreate()\n jdt = spark._jsparkSession.parseDataType(dataType.json())\n jc = self._jc.cast(jdt)\n else:\n raise TypeError(\"unexpected type: %s\" % type(dataType))\n return Column(jc)" }, { "instruction": "Write or improve a Python function based on this description:\n\nEvaluates a list of conditions and returns one of multiple possible result expressions.\n If :func:`Column.otherwise` is not invoked, None is returned for unmatched conditions.\n\n See :func:`pyspark.sql.functions.when` for example usage.\n\n :param condition: a boolean :class:`Column` expression.\n :param value: a literal value, or a :class:`Column` expression.\n\n >>> from pyspark.sql import functions as F\n >>> df.select(df.name, F.when(df.age > 4, 1).when(df.age < 3, -1).otherwise(0)).show()\n +-----+------------------------------------------------------------+\n | name|CASE WHEN (age > 4) THEN 1 WHEN (age < 3) THEN -1 ELSE 0 END|\n +-----+------------------------------------------------------------+\n |Alice| -1|\n | Bob| 1|\n +-----+------------------------------------------------------------+", "output": "def when(self, condition, value):\n \"\"\"\n Evaluates a list of conditions and returns one of multiple possible result expressions.\n If :func:`Column.otherwise` is not invoked, None is returned for unmatched conditions.\n\n See :func:`pyspark.sql.functions.when` for example usage.\n\n :param condition: a boolean :class:`Column` expression.\n :param value: a literal value, or a :class:`Column` expression.\n\n >>> from pyspark.sql import functions as F\n >>> df.select(df.name, F.when(df.age > 4, 1).when(df.age < 3, -1).otherwise(0)).show()\n +-----+------------------------------------------------------------+\n | name|CASE WHEN (age > 4) THEN 1 WHEN (age < 3) THEN -1 ELSE 0 END|\n +-----+------------------------------------------------------------+\n |Alice| -1|\n | Bob| 1|\n +-----+------------------------------------------------------------+\n \"\"\"\n if not isinstance(condition, Column):\n raise TypeError(\"condition should be a Column\")\n v = value._jc if isinstance(value, Column) else value\n jc = self._jc.when(condition._jc, v)\n return Column(jc)" }, { "instruction": "Write or improve a Python function based on this description:\n\nEvaluates a list of conditions and returns one of multiple possible result expressions.\n If :func:`Column.otherwise` is not invoked, None is returned for unmatched conditions.\n\n See :func:`pyspark.sql.functions.when` for example usage.\n\n :param value: a literal value, or a :class:`Column` expression.\n\n >>> from pyspark.sql import functions as F\n >>> df.select(df.name, F.when(df.age > 3, 1).otherwise(0)).show()\n +-----+-------------------------------------+\n | name|CASE WHEN (age > 3) THEN 1 ELSE 0 END|\n +-----+-------------------------------------+\n |Alice| 0|\n | Bob| 1|\n +-----+-------------------------------------+", "output": "def otherwise(self, value):\n \"\"\"\n Evaluates a list of conditions and returns one of multiple possible result expressions.\n If :func:`Column.otherwise` is not invoked, None is returned for unmatched conditions.\n\n See :func:`pyspark.sql.functions.when` for example usage.\n\n :param value: a literal value, or a :class:`Column` expression.\n\n >>> from pyspark.sql import functions as F\n >>> df.select(df.name, F.when(df.age > 3, 1).otherwise(0)).show()\n +-----+-------------------------------------+\n | name|CASE WHEN (age > 3) THEN 1 ELSE 0 END|\n +-----+-------------------------------------+\n |Alice| 0|\n | Bob| 1|\n +-----+-------------------------------------+\n \"\"\"\n v = value._jc if isinstance(value, Column) else value\n jc = self._jc.otherwise(v)\n return Column(jc)" }, { "instruction": "Write or improve a Python function based on this description:\n\nDefine a windowing column.\n\n :param window: a :class:`WindowSpec`\n :return: a Column\n\n >>> from pyspark.sql import Window\n >>> window = Window.partitionBy(\"name\").orderBy(\"age\").rowsBetween(-1, 1)\n >>> from pyspark.sql.functions import rank, min\n >>> # df.select(rank().over(window), min('age').over(window))", "output": "def over(self, window):\n \"\"\"\n Define a windowing column.\n\n :param window: a :class:`WindowSpec`\n :return: a Column\n\n >>> from pyspark.sql import Window\n >>> window = Window.partitionBy(\"name\").orderBy(\"age\").rowsBetween(-1, 1)\n >>> from pyspark.sql.functions import rank, min\n >>> # df.select(rank().over(window), min('age').over(window))\n \"\"\"\n from pyspark.sql.window import WindowSpec\n if not isinstance(window, WindowSpec):\n raise TypeError(\"window should be WindowSpec\")\n jc = self._jc.over(window._jspec)\n return Column(jc)" }, { "instruction": "Write or improve a Python function based on this description:\n\nApplies transformation on a vector or an RDD[Vector].\n\n .. note:: In Python, transform cannot currently be used within\n an RDD transformation or action.\n Call transform directly on the RDD instead.\n\n :param vector: Vector or RDD of Vector to be transformed.", "output": "def transform(self, vector):\n \"\"\"\n Applies transformation on a vector or an RDD[Vector].\n\n .. note:: In Python, transform cannot currently be used within\n an RDD transformation or action.\n Call transform directly on the RDD instead.\n\n :param vector: Vector or RDD of Vector to be transformed.\n \"\"\"\n if isinstance(vector, RDD):\n vector = vector.map(_convert_to_vector)\n else:\n vector = _convert_to_vector(vector)\n return self.call(\"transform\", vector)" }, { "instruction": "Write or improve a Python function based on this description:\n\nComputes the mean and variance and stores as a model to be used\n for later scaling.\n\n :param dataset: The data used to compute the mean and variance\n to build the transformation model.\n :return: a StandardScalarModel", "output": "def fit(self, dataset):\n \"\"\"\n Computes the mean and variance and stores as a model to be used\n for later scaling.\n\n :param dataset: The data used to compute the mean and variance\n to build the transformation model.\n :return: a StandardScalarModel\n \"\"\"\n dataset = dataset.map(_convert_to_vector)\n jmodel = callMLlibFunc(\"fitStandardScaler\", self.withMean, self.withStd, dataset)\n return StandardScalerModel(jmodel)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns a ChiSquared feature selector.\n\n :param data: an `RDD[LabeledPoint]` containing the labeled dataset\n with categorical features. Real-valued features will be\n treated as categorical for each distinct value.\n Apply feature discretizer before using this function.", "output": "def fit(self, data):\n \"\"\"\n Returns a ChiSquared feature selector.\n\n :param data: an `RDD[LabeledPoint]` containing the labeled dataset\n with categorical features. Real-valued features will be\n treated as categorical for each distinct value.\n Apply feature discretizer before using this function.\n \"\"\"\n jmodel = callMLlibFunc(\"fitChiSqSelector\", self.selectorType, self.numTopFeatures,\n self.percentile, self.fpr, self.fdr, self.fwe, data)\n return ChiSqSelectorModel(jmodel)" }, { "instruction": "Write or improve a Python function based on this description:\n\nComputes a [[PCAModel]] that contains the principal components of the input vectors.\n :param data: source vectors", "output": "def fit(self, data):\n \"\"\"\n Computes a [[PCAModel]] that contains the principal components of the input vectors.\n :param data: source vectors\n \"\"\"\n jmodel = callMLlibFunc(\"fitPCA\", self.k, data)\n return PCAModel(jmodel)" }, { "instruction": "Write or improve a Python function based on this description:\n\nTransforms the input document (list of terms) to term frequency\n vectors, or transform the RDD of document to RDD of term\n frequency vectors.", "output": "def transform(self, document):\n \"\"\"\n Transforms the input document (list of terms) to term frequency\n vectors, or transform the RDD of document to RDD of term\n frequency vectors.\n \"\"\"\n if isinstance(document, RDD):\n return document.map(self.transform)\n\n freq = {}\n for term in document:\n i = self.indexOf(term)\n freq[i] = 1.0 if self.binary else freq.get(i, 0) + 1.0\n return Vectors.sparse(self.numFeatures, freq.items())" }, { "instruction": "Write or improve a Python function based on this description:\n\nComputes the inverse document frequency.\n\n :param dataset: an RDD of term frequency vectors", "output": "def fit(self, dataset):\n \"\"\"\n Computes the inverse document frequency.\n\n :param dataset: an RDD of term frequency vectors\n \"\"\"\n if not isinstance(dataset, RDD):\n raise TypeError(\"dataset should be an RDD of term frequency vectors\")\n jmodel = callMLlibFunc(\"fitIDF\", self.minDocFreq, dataset.map(_convert_to_vector))\n return IDFModel(jmodel)" }, { "instruction": "Write or improve a Python function based on this description:\n\nFind synonyms of a word\n\n :param word: a word or a vector representation of word\n :param num: number of synonyms to find\n :return: array of (word, cosineSimilarity)\n\n .. note:: Local use only", "output": "def findSynonyms(self, word, num):\n \"\"\"\n Find synonyms of a word\n\n :param word: a word or a vector representation of word\n :param num: number of synonyms to find\n :return: array of (word, cosineSimilarity)\n\n .. note:: Local use only\n \"\"\"\n if not isinstance(word, basestring):\n word = _convert_to_vector(word)\n words, similarity = self.call(\"findSynonyms\", word, num)\n return zip(words, similarity)" }, { "instruction": "Write or improve a Python function based on this description:\n\nLoad a model from the given path.", "output": "def load(cls, sc, path):\n \"\"\"\n Load a model from the given path.\n \"\"\"\n jmodel = sc._jvm.org.apache.spark.mllib.feature \\\n .Word2VecModel.load(sc._jsc.sc(), path)\n model = sc._jvm.org.apache.spark.mllib.api.python.Word2VecModelWrapper(jmodel)\n return Word2VecModel(model)" }, { "instruction": "Write or improve a Python function based on this description:\n\nComputes the Hadamard product of the vector.", "output": "def transform(self, vector):\n \"\"\"\n Computes the Hadamard product of the vector.\n \"\"\"\n if isinstance(vector, RDD):\n vector = vector.map(_convert_to_vector)\n\n else:\n vector = _convert_to_vector(vector)\n return callMLlibFunc(\"elementwiseProductVector\", self.scalingVector, vector)" }, { "instruction": "Write or improve a Python function based on this description:\n\nPredict values for a single data point or an RDD of points using\n the model trained.\n\n .. note:: In Python, predict cannot currently be used within an RDD\n transformation or action.\n Call predict directly on the RDD instead.", "output": "def predict(self, x):\n \"\"\"\n Predict values for a single data point or an RDD of points using\n the model trained.\n\n .. note:: In Python, predict cannot currently be used within an RDD\n transformation or action.\n Call predict directly on the RDD instead.\n \"\"\"\n if isinstance(x, RDD):\n return self.call(\"predict\", x.map(_convert_to_vector))\n\n else:\n return self.call(\"predict\", _convert_to_vector(x))" }, { "instruction": "Write or improve a Python function based on this description:\n\nTrain a decision tree model for classification.\n\n :param data:\n Training data: RDD of LabeledPoint. Labels should take values\n {0, 1, ..., numClasses-1}.\n :param numClasses:\n Number of classes for classification.\n :param categoricalFeaturesInfo:\n Map storing arity of categorical features. An entry (n -> k)\n indicates that feature n is categorical with k categories\n indexed from 0: {0, 1, ..., k-1}.\n :param impurity:\n Criterion used for information gain calculation.\n Supported values: \"gini\" or \"entropy\".\n (default: \"gini\")\n :param maxDepth:\n Maximum depth of tree (e.g. depth 0 means 1 leaf node, depth 1\n means 1 internal node + 2 leaf nodes).\n (default: 5)\n :param maxBins:\n Number of bins used for finding splits at each node.\n (default: 32)\n :param minInstancesPerNode:\n Minimum number of instances required at child nodes to create\n the parent split.\n (default: 1)\n :param minInfoGain:\n Minimum info gain required to create a split.\n (default: 0.0)\n :return:\n DecisionTreeModel.\n\n Example usage:\n\n >>> from numpy import array\n >>> from pyspark.mllib.regression import LabeledPoint\n >>> from pyspark.mllib.tree import DecisionTree\n >>>\n >>> data = [\n ... LabeledPoint(0.0, [0.0]),\n ... LabeledPoint(1.0, [1.0]),\n ... LabeledPoint(1.0, [2.0]),\n ... LabeledPoint(1.0, [3.0])\n ... ]\n >>> model = DecisionTree.trainClassifier(sc.parallelize(data), 2, {})\n >>> print(model)\n DecisionTreeModel classifier of depth 1 with 3 nodes\n\n >>> print(model.toDebugString())\n DecisionTreeModel classifier of depth 1 with 3 nodes\n If (feature 0 <= 0.5)\n Predict: 0.0\n Else (feature 0 > 0.5)\n Predict: 1.0\n \n >>> model.predict(array([1.0]))\n 1.0\n >>> model.predict(array([0.0]))\n 0.0\n >>> rdd = sc.parallelize([[1.0], [0.0]])\n >>> model.predict(rdd).collect()\n [1.0, 0.0]", "output": "def trainClassifier(cls, data, numClasses, categoricalFeaturesInfo,\n impurity=\"gini\", maxDepth=5, maxBins=32, minInstancesPerNode=1,\n minInfoGain=0.0):\n \"\"\"\n Train a decision tree model for classification.\n\n :param data:\n Training data: RDD of LabeledPoint. Labels should take values\n {0, 1, ..., numClasses-1}.\n :param numClasses:\n Number of classes for classification.\n :param categoricalFeaturesInfo:\n Map storing arity of categorical features. An entry (n -> k)\n indicates that feature n is categorical with k categories\n indexed from 0: {0, 1, ..., k-1}.\n :param impurity:\n Criterion used for information gain calculation.\n Supported values: \"gini\" or \"entropy\".\n (default: \"gini\")\n :param maxDepth:\n Maximum depth of tree (e.g. depth 0 means 1 leaf node, depth 1\n means 1 internal node + 2 leaf nodes).\n (default: 5)\n :param maxBins:\n Number of bins used for finding splits at each node.\n (default: 32)\n :param minInstancesPerNode:\n Minimum number of instances required at child nodes to create\n the parent split.\n (default: 1)\n :param minInfoGain:\n Minimum info gain required to create a split.\n (default: 0.0)\n :return:\n DecisionTreeModel.\n\n Example usage:\n\n >>> from numpy import array\n >>> from pyspark.mllib.regression import LabeledPoint\n >>> from pyspark.mllib.tree import DecisionTree\n >>>\n >>> data = [\n ... LabeledPoint(0.0, [0.0]),\n ... LabeledPoint(1.0, [1.0]),\n ... LabeledPoint(1.0, [2.0]),\n ... LabeledPoint(1.0, [3.0])\n ... ]\n >>> model = DecisionTree.trainClassifier(sc.parallelize(data), 2, {})\n >>> print(model)\n DecisionTreeModel classifier of depth 1 with 3 nodes\n\n >>> print(model.toDebugString())\n DecisionTreeModel classifier of depth 1 with 3 nodes\n If (feature 0 <= 0.5)\n Predict: 0.0\n Else (feature 0 > 0.5)\n Predict: 1.0\n \n >>> model.predict(array([1.0]))\n 1.0\n >>> model.predict(array([0.0]))\n 0.0\n >>> rdd = sc.parallelize([[1.0], [0.0]])\n >>> model.predict(rdd).collect()\n [1.0, 0.0]\n \"\"\"\n return cls._train(data, \"classification\", numClasses, categoricalFeaturesInfo,\n impurity, maxDepth, maxBins, minInstancesPerNode, minInfoGain)" }, { "instruction": "Write or improve a Python function based on this description:\n\nTrain a decision tree model for regression.\n\n :param data:\n Training data: RDD of LabeledPoint. Labels are real numbers.\n :param categoricalFeaturesInfo:\n Map storing arity of categorical features. An entry (n -> k)\n indicates that feature n is categorical with k categories\n indexed from 0: {0, 1, ..., k-1}.\n :param impurity:\n Criterion used for information gain calculation.\n The only supported value for regression is \"variance\".\n (default: \"variance\")\n :param maxDepth:\n Maximum depth of tree (e.g. depth 0 means 1 leaf node, depth 1\n means 1 internal node + 2 leaf nodes).\n (default: 5)\n :param maxBins:\n Number of bins used for finding splits at each node.\n (default: 32)\n :param minInstancesPerNode:\n Minimum number of instances required at child nodes to create\n the parent split.\n (default: 1)\n :param minInfoGain:\n Minimum info gain required to create a split.\n (default: 0.0)\n :return:\n DecisionTreeModel.\n\n Example usage:\n\n >>> from pyspark.mllib.regression import LabeledPoint\n >>> from pyspark.mllib.tree import DecisionTree\n >>> from pyspark.mllib.linalg import SparseVector\n >>>\n >>> sparse_data = [\n ... LabeledPoint(0.0, SparseVector(2, {0: 0.0})),\n ... LabeledPoint(1.0, SparseVector(2, {1: 1.0})),\n ... LabeledPoint(0.0, SparseVector(2, {0: 0.0})),\n ... LabeledPoint(1.0, SparseVector(2, {1: 2.0}))\n ... ]\n >>>\n >>> model = DecisionTree.trainRegressor(sc.parallelize(sparse_data), {})\n >>> model.predict(SparseVector(2, {1: 1.0}))\n 1.0\n >>> model.predict(SparseVector(2, {1: 0.0}))\n 0.0\n >>> rdd = sc.parallelize([[0.0, 1.0], [0.0, 0.0]])\n >>> model.predict(rdd).collect()\n [1.0, 0.0]", "output": "def trainRegressor(cls, data, categoricalFeaturesInfo,\n impurity=\"variance\", maxDepth=5, maxBins=32, minInstancesPerNode=1,\n minInfoGain=0.0):\n \"\"\"\n Train a decision tree model for regression.\n\n :param data:\n Training data: RDD of LabeledPoint. Labels are real numbers.\n :param categoricalFeaturesInfo:\n Map storing arity of categorical features. An entry (n -> k)\n indicates that feature n is categorical with k categories\n indexed from 0: {0, 1, ..., k-1}.\n :param impurity:\n Criterion used for information gain calculation.\n The only supported value for regression is \"variance\".\n (default: \"variance\")\n :param maxDepth:\n Maximum depth of tree (e.g. depth 0 means 1 leaf node, depth 1\n means 1 internal node + 2 leaf nodes).\n (default: 5)\n :param maxBins:\n Number of bins used for finding splits at each node.\n (default: 32)\n :param minInstancesPerNode:\n Minimum number of instances required at child nodes to create\n the parent split.\n (default: 1)\n :param minInfoGain:\n Minimum info gain required to create a split.\n (default: 0.0)\n :return:\n DecisionTreeModel.\n\n Example usage:\n\n >>> from pyspark.mllib.regression import LabeledPoint\n >>> from pyspark.mllib.tree import DecisionTree\n >>> from pyspark.mllib.linalg import SparseVector\n >>>\n >>> sparse_data = [\n ... LabeledPoint(0.0, SparseVector(2, {0: 0.0})),\n ... LabeledPoint(1.0, SparseVector(2, {1: 1.0})),\n ... LabeledPoint(0.0, SparseVector(2, {0: 0.0})),\n ... LabeledPoint(1.0, SparseVector(2, {1: 2.0}))\n ... ]\n >>>\n >>> model = DecisionTree.trainRegressor(sc.parallelize(sparse_data), {})\n >>> model.predict(SparseVector(2, {1: 1.0}))\n 1.0\n >>> model.predict(SparseVector(2, {1: 0.0}))\n 0.0\n >>> rdd = sc.parallelize([[0.0, 1.0], [0.0, 0.0]])\n >>> model.predict(rdd).collect()\n [1.0, 0.0]\n \"\"\"\n return cls._train(data, \"regression\", 0, categoricalFeaturesInfo,\n impurity, maxDepth, maxBins, minInstancesPerNode, minInfoGain)" }, { "instruction": "Write or improve a Python function based on this description:\n\nTrain a random forest model for binary or multiclass\n classification.\n\n :param data:\n Training dataset: RDD of LabeledPoint. Labels should take values\n {0, 1, ..., numClasses-1}.\n :param numClasses:\n Number of classes for classification.\n :param categoricalFeaturesInfo:\n Map storing arity of categorical features. An entry (n -> k)\n indicates that feature n is categorical with k categories\n indexed from 0: {0, 1, ..., k-1}.\n :param numTrees:\n Number of trees in the random forest.\n :param featureSubsetStrategy:\n Number of features to consider for splits at each node.\n Supported values: \"auto\", \"all\", \"sqrt\", \"log2\", \"onethird\".\n If \"auto\" is set, this parameter is set based on numTrees:\n if numTrees == 1, set to \"all\";\n if numTrees > 1 (forest) set to \"sqrt\".\n (default: \"auto\")\n :param impurity:\n Criterion used for information gain calculation.\n Supported values: \"gini\" or \"entropy\".\n (default: \"gini\")\n :param maxDepth:\n Maximum depth of tree (e.g. depth 0 means 1 leaf node, depth 1\n means 1 internal node + 2 leaf nodes).\n (default: 4)\n :param maxBins:\n Maximum number of bins used for splitting features.\n (default: 32)\n :param seed:\n Random seed for bootstrapping and choosing feature subsets.\n Set as None to generate seed based on system time.\n (default: None)\n :return:\n RandomForestModel that can be used for prediction.\n\n Example usage:\n\n >>> from pyspark.mllib.regression import LabeledPoint\n >>> from pyspark.mllib.tree import RandomForest\n >>>\n >>> data = [\n ... LabeledPoint(0.0, [0.0]),\n ... LabeledPoint(0.0, [1.0]),\n ... LabeledPoint(1.0, [2.0]),\n ... LabeledPoint(1.0, [3.0])\n ... ]\n >>> model = RandomForest.trainClassifier(sc.parallelize(data), 2, {}, 3, seed=42)\n >>> model.numTrees()\n 3\n >>> model.totalNumNodes()\n 7\n >>> print(model)\n TreeEnsembleModel classifier with 3 trees\n \n >>> print(model.toDebugString())\n TreeEnsembleModel classifier with 3 trees\n \n Tree 0:\n Predict: 1.0\n Tree 1:\n If (feature 0 <= 1.5)\n Predict: 0.0\n Else (feature 0 > 1.5)\n Predict: 1.0\n Tree 2:\n If (feature 0 <= 1.5)\n Predict: 0.0\n Else (feature 0 > 1.5)\n Predict: 1.0\n \n >>> model.predict([2.0])\n 1.0\n >>> model.predict([0.0])\n 0.0\n >>> rdd = sc.parallelize([[3.0], [1.0]])\n >>> model.predict(rdd).collect()\n [1.0, 0.0]", "output": "def trainClassifier(cls, data, numClasses, categoricalFeaturesInfo, numTrees,\n featureSubsetStrategy=\"auto\", impurity=\"gini\", maxDepth=4, maxBins=32,\n seed=None):\n \"\"\"\n Train a random forest model for binary or multiclass\n classification.\n\n :param data:\n Training dataset: RDD of LabeledPoint. Labels should take values\n {0, 1, ..., numClasses-1}.\n :param numClasses:\n Number of classes for classification.\n :param categoricalFeaturesInfo:\n Map storing arity of categorical features. An entry (n -> k)\n indicates that feature n is categorical with k categories\n indexed from 0: {0, 1, ..., k-1}.\n :param numTrees:\n Number of trees in the random forest.\n :param featureSubsetStrategy:\n Number of features to consider for splits at each node.\n Supported values: \"auto\", \"all\", \"sqrt\", \"log2\", \"onethird\".\n If \"auto\" is set, this parameter is set based on numTrees:\n if numTrees == 1, set to \"all\";\n if numTrees > 1 (forest) set to \"sqrt\".\n (default: \"auto\")\n :param impurity:\n Criterion used for information gain calculation.\n Supported values: \"gini\" or \"entropy\".\n (default: \"gini\")\n :param maxDepth:\n Maximum depth of tree (e.g. depth 0 means 1 leaf node, depth 1\n means 1 internal node + 2 leaf nodes).\n (default: 4)\n :param maxBins:\n Maximum number of bins used for splitting features.\n (default: 32)\n :param seed:\n Random seed for bootstrapping and choosing feature subsets.\n Set as None to generate seed based on system time.\n (default: None)\n :return:\n RandomForestModel that can be used for prediction.\n\n Example usage:\n\n >>> from pyspark.mllib.regression import LabeledPoint\n >>> from pyspark.mllib.tree import RandomForest\n >>>\n >>> data = [\n ... LabeledPoint(0.0, [0.0]),\n ... LabeledPoint(0.0, [1.0]),\n ... LabeledPoint(1.0, [2.0]),\n ... LabeledPoint(1.0, [3.0])\n ... ]\n >>> model = RandomForest.trainClassifier(sc.parallelize(data), 2, {}, 3, seed=42)\n >>> model.numTrees()\n 3\n >>> model.totalNumNodes()\n 7\n >>> print(model)\n TreeEnsembleModel classifier with 3 trees\n \n >>> print(model.toDebugString())\n TreeEnsembleModel classifier with 3 trees\n \n Tree 0:\n Predict: 1.0\n Tree 1:\n If (feature 0 <= 1.5)\n Predict: 0.0\n Else (feature 0 > 1.5)\n Predict: 1.0\n Tree 2:\n If (feature 0 <= 1.5)\n Predict: 0.0\n Else (feature 0 > 1.5)\n Predict: 1.0\n \n >>> model.predict([2.0])\n 1.0\n >>> model.predict([0.0])\n 0.0\n >>> rdd = sc.parallelize([[3.0], [1.0]])\n >>> model.predict(rdd).collect()\n [1.0, 0.0]\n \"\"\"\n return cls._train(data, \"classification\", numClasses,\n categoricalFeaturesInfo, numTrees, featureSubsetStrategy, impurity,\n maxDepth, maxBins, seed)" }, { "instruction": "Write or improve a Python function based on this description:\n\nTrain a random forest model for regression.\n\n :param data:\n Training dataset: RDD of LabeledPoint. Labels are real numbers.\n :param categoricalFeaturesInfo:\n Map storing arity of categorical features. An entry (n -> k)\n indicates that feature n is categorical with k categories\n indexed from 0: {0, 1, ..., k-1}.\n :param numTrees:\n Number of trees in the random forest.\n :param featureSubsetStrategy:\n Number of features to consider for splits at each node.\n Supported values: \"auto\", \"all\", \"sqrt\", \"log2\", \"onethird\".\n If \"auto\" is set, this parameter is set based on numTrees:\n if numTrees == 1, set to \"all\";\n if numTrees > 1 (forest) set to \"onethird\" for regression.\n (default: \"auto\")\n :param impurity:\n Criterion used for information gain calculation.\n The only supported value for regression is \"variance\".\n (default: \"variance\")\n :param maxDepth:\n Maximum depth of tree (e.g. depth 0 means 1 leaf node, depth 1\n means 1 internal node + 2 leaf nodes).\n (default: 4)\n :param maxBins:\n Maximum number of bins used for splitting features.\n (default: 32)\n :param seed:\n Random seed for bootstrapping and choosing feature subsets.\n Set as None to generate seed based on system time.\n (default: None)\n :return:\n RandomForestModel that can be used for prediction.\n\n Example usage:\n\n >>> from pyspark.mllib.regression import LabeledPoint\n >>> from pyspark.mllib.tree import RandomForest\n >>> from pyspark.mllib.linalg import SparseVector\n >>>\n >>> sparse_data = [\n ... LabeledPoint(0.0, SparseVector(2, {0: 1.0})),\n ... LabeledPoint(1.0, SparseVector(2, {1: 1.0})),\n ... LabeledPoint(0.0, SparseVector(2, {0: 1.0})),\n ... LabeledPoint(1.0, SparseVector(2, {1: 2.0}))\n ... ]\n >>>\n >>> model = RandomForest.trainRegressor(sc.parallelize(sparse_data), {}, 2, seed=42)\n >>> model.numTrees()\n 2\n >>> model.totalNumNodes()\n 4\n >>> model.predict(SparseVector(2, {1: 1.0}))\n 1.0\n >>> model.predict(SparseVector(2, {0: 1.0}))\n 0.5\n >>> rdd = sc.parallelize([[0.0, 1.0], [1.0, 0.0]])\n >>> model.predict(rdd).collect()\n [1.0, 0.5]", "output": "def trainRegressor(cls, data, categoricalFeaturesInfo, numTrees, featureSubsetStrategy=\"auto\",\n impurity=\"variance\", maxDepth=4, maxBins=32, seed=None):\n \"\"\"\n Train a random forest model for regression.\n\n :param data:\n Training dataset: RDD of LabeledPoint. Labels are real numbers.\n :param categoricalFeaturesInfo:\n Map storing arity of categorical features. An entry (n -> k)\n indicates that feature n is categorical with k categories\n indexed from 0: {0, 1, ..., k-1}.\n :param numTrees:\n Number of trees in the random forest.\n :param featureSubsetStrategy:\n Number of features to consider for splits at each node.\n Supported values: \"auto\", \"all\", \"sqrt\", \"log2\", \"onethird\".\n If \"auto\" is set, this parameter is set based on numTrees:\n if numTrees == 1, set to \"all\";\n if numTrees > 1 (forest) set to \"onethird\" for regression.\n (default: \"auto\")\n :param impurity:\n Criterion used for information gain calculation.\n The only supported value for regression is \"variance\".\n (default: \"variance\")\n :param maxDepth:\n Maximum depth of tree (e.g. depth 0 means 1 leaf node, depth 1\n means 1 internal node + 2 leaf nodes).\n (default: 4)\n :param maxBins:\n Maximum number of bins used for splitting features.\n (default: 32)\n :param seed:\n Random seed for bootstrapping and choosing feature subsets.\n Set as None to generate seed based on system time.\n (default: None)\n :return:\n RandomForestModel that can be used for prediction.\n\n Example usage:\n\n >>> from pyspark.mllib.regression import LabeledPoint\n >>> from pyspark.mllib.tree import RandomForest\n >>> from pyspark.mllib.linalg import SparseVector\n >>>\n >>> sparse_data = [\n ... LabeledPoint(0.0, SparseVector(2, {0: 1.0})),\n ... LabeledPoint(1.0, SparseVector(2, {1: 1.0})),\n ... LabeledPoint(0.0, SparseVector(2, {0: 1.0})),\n ... LabeledPoint(1.0, SparseVector(2, {1: 2.0}))\n ... ]\n >>>\n >>> model = RandomForest.trainRegressor(sc.parallelize(sparse_data), {}, 2, seed=42)\n >>> model.numTrees()\n 2\n >>> model.totalNumNodes()\n 4\n >>> model.predict(SparseVector(2, {1: 1.0}))\n 1.0\n >>> model.predict(SparseVector(2, {0: 1.0}))\n 0.5\n >>> rdd = sc.parallelize([[0.0, 1.0], [1.0, 0.0]])\n >>> model.predict(rdd).collect()\n [1.0, 0.5]\n \"\"\"\n return cls._train(data, \"regression\", 0, categoricalFeaturesInfo, numTrees,\n featureSubsetStrategy, impurity, maxDepth, maxBins, seed)" }, { "instruction": "Write or improve a Python function based on this description:\n\nTrain a gradient-boosted trees model for classification.\n\n :param data:\n Training dataset: RDD of LabeledPoint. Labels should take values\n {0, 1}.\n :param categoricalFeaturesInfo:\n Map storing arity of categorical features. An entry (n -> k)\n indicates that feature n is categorical with k categories\n indexed from 0: {0, 1, ..., k-1}.\n :param loss:\n Loss function used for minimization during gradient boosting.\n Supported values: \"logLoss\", \"leastSquaresError\",\n \"leastAbsoluteError\".\n (default: \"logLoss\")\n :param numIterations:\n Number of iterations of boosting.\n (default: 100)\n :param learningRate:\n Learning rate for shrinking the contribution of each estimator.\n The learning rate should be between in the interval (0, 1].\n (default: 0.1)\n :param maxDepth:\n Maximum depth of tree (e.g. depth 0 means 1 leaf node, depth 1\n means 1 internal node + 2 leaf nodes).\n (default: 3)\n :param maxBins:\n Maximum number of bins used for splitting features. DecisionTree\n requires maxBins >= max categories.\n (default: 32)\n :return:\n GradientBoostedTreesModel that can be used for prediction.\n\n Example usage:\n\n >>> from pyspark.mllib.regression import LabeledPoint\n >>> from pyspark.mllib.tree import GradientBoostedTrees\n >>>\n >>> data = [\n ... LabeledPoint(0.0, [0.0]),\n ... LabeledPoint(0.0, [1.0]),\n ... LabeledPoint(1.0, [2.0]),\n ... LabeledPoint(1.0, [3.0])\n ... ]\n >>>\n >>> model = GradientBoostedTrees.trainClassifier(sc.parallelize(data), {}, numIterations=10)\n >>> model.numTrees()\n 10\n >>> model.totalNumNodes()\n 30\n >>> print(model) # it already has newline\n TreeEnsembleModel classifier with 10 trees\n \n >>> model.predict([2.0])\n 1.0\n >>> model.predict([0.0])\n 0.0\n >>> rdd = sc.parallelize([[2.0], [0.0]])\n >>> model.predict(rdd).collect()\n [1.0, 0.0]", "output": "def trainClassifier(cls, data, categoricalFeaturesInfo,\n loss=\"logLoss\", numIterations=100, learningRate=0.1, maxDepth=3,\n maxBins=32):\n \"\"\"\n Train a gradient-boosted trees model for classification.\n\n :param data:\n Training dataset: RDD of LabeledPoint. Labels should take values\n {0, 1}.\n :param categoricalFeaturesInfo:\n Map storing arity of categorical features. An entry (n -> k)\n indicates that feature n is categorical with k categories\n indexed from 0: {0, 1, ..., k-1}.\n :param loss:\n Loss function used for minimization during gradient boosting.\n Supported values: \"logLoss\", \"leastSquaresError\",\n \"leastAbsoluteError\".\n (default: \"logLoss\")\n :param numIterations:\n Number of iterations of boosting.\n (default: 100)\n :param learningRate:\n Learning rate for shrinking the contribution of each estimator.\n The learning rate should be between in the interval (0, 1].\n (default: 0.1)\n :param maxDepth:\n Maximum depth of tree (e.g. depth 0 means 1 leaf node, depth 1\n means 1 internal node + 2 leaf nodes).\n (default: 3)\n :param maxBins:\n Maximum number of bins used for splitting features. DecisionTree\n requires maxBins >= max categories.\n (default: 32)\n :return:\n GradientBoostedTreesModel that can be used for prediction.\n\n Example usage:\n\n >>> from pyspark.mllib.regression import LabeledPoint\n >>> from pyspark.mllib.tree import GradientBoostedTrees\n >>>\n >>> data = [\n ... LabeledPoint(0.0, [0.0]),\n ... LabeledPoint(0.0, [1.0]),\n ... LabeledPoint(1.0, [2.0]),\n ... LabeledPoint(1.0, [3.0])\n ... ]\n >>>\n >>> model = GradientBoostedTrees.trainClassifier(sc.parallelize(data), {}, numIterations=10)\n >>> model.numTrees()\n 10\n >>> model.totalNumNodes()\n 30\n >>> print(model) # it already has newline\n TreeEnsembleModel classifier with 10 trees\n \n >>> model.predict([2.0])\n 1.0\n >>> model.predict([0.0])\n 0.0\n >>> rdd = sc.parallelize([[2.0], [0.0]])\n >>> model.predict(rdd).collect()\n [1.0, 0.0]\n \"\"\"\n return cls._train(data, \"classification\", categoricalFeaturesInfo,\n loss, numIterations, learningRate, maxDepth, maxBins)" }, { "instruction": "Write or improve a Python function based on this description:\n\nSet a configuration property.", "output": "def set(self, key, value):\n \"\"\"Set a configuration property.\"\"\"\n # Try to set self._jconf first if JVM is created, set self._conf if JVM is not created yet.\n if self._jconf is not None:\n self._jconf.set(key, unicode(value))\n else:\n self._conf[key] = unicode(value)\n return self" }, { "instruction": "Write or improve a Python function based on this description:\n\nSet a configuration property, if not already set.", "output": "def setIfMissing(self, key, value):\n \"\"\"Set a configuration property, if not already set.\"\"\"\n if self.get(key) is None:\n self.set(key, value)\n return self" }, { "instruction": "Write or improve a Python function based on this description:\n\nSet an environment variable to be passed to executors.", "output": "def setExecutorEnv(self, key=None, value=None, pairs=None):\n \"\"\"Set an environment variable to be passed to executors.\"\"\"\n if (key is not None and pairs is not None) or (key is None and pairs is None):\n raise Exception(\"Either pass one key-value pair or a list of pairs\")\n elif key is not None:\n self.set(\"spark.executorEnv.\" + key, value)\n elif pairs is not None:\n for (k, v) in pairs:\n self.set(\"spark.executorEnv.\" + k, v)\n return self" }, { "instruction": "Write or improve a Python function based on this description:\n\nSet multiple parameters, passed as a list of key-value pairs.\n\n :param pairs: list of key-value pairs to set", "output": "def setAll(self, pairs):\n \"\"\"\n Set multiple parameters, passed as a list of key-value pairs.\n\n :param pairs: list of key-value pairs to set\n \"\"\"\n for (k, v) in pairs:\n self.set(k, v)\n return self" }, { "instruction": "Write or improve a Python function based on this description:\n\nGet the configured value for some key, or return a default otherwise.", "output": "def get(self, key, defaultValue=None):\n \"\"\"Get the configured value for some key, or return a default otherwise.\"\"\"\n if defaultValue is None: # Py4J doesn't call the right get() if we pass None\n if self._jconf is not None:\n if not self._jconf.contains(key):\n return None\n return self._jconf.get(key)\n else:\n if key not in self._conf:\n return None\n return self._conf[key]\n else:\n if self._jconf is not None:\n return self._jconf.get(key, defaultValue)\n else:\n return self._conf.get(key, defaultValue)" }, { "instruction": "Write or improve a Python function based on this description:\n\nGet all values as a list of key-value pairs.", "output": "def getAll(self):\n \"\"\"Get all values as a list of key-value pairs.\"\"\"\n if self._jconf is not None:\n return [(elem._1(), elem._2()) for elem in self._jconf.getAll()]\n else:\n return self._conf.items()" }, { "instruction": "Write or improve a Python function based on this description:\n\nDoes this configuration contain a given key?", "output": "def contains(self, key):\n \"\"\"Does this configuration contain a given key?\"\"\"\n if self._jconf is not None:\n return self._jconf.contains(key)\n else:\n return key in self._conf" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns a printable version of the configuration, as a list of\n key=value pairs, one per line.", "output": "def toDebugString(self):\n \"\"\"\n Returns a printable version of the configuration, as a list of\n key=value pairs, one per line.\n \"\"\"\n if self._jconf is not None:\n return self._jconf.toDebugString()\n else:\n return '\\n'.join('%s=%s' % (k, v) for k, v in self._conf.items())" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns a list of databases available across all sessions.", "output": "def listDatabases(self):\n \"\"\"Returns a list of databases available across all sessions.\"\"\"\n iter = self._jcatalog.listDatabases().toLocalIterator()\n databases = []\n while iter.hasNext():\n jdb = iter.next()\n databases.append(Database(\n name=jdb.name(),\n description=jdb.description(),\n locationUri=jdb.locationUri()))\n return databases" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns a list of tables/views in the specified database.\n\n If no database is specified, the current database is used.\n This includes all temporary views.", "output": "def listTables(self, dbName=None):\n \"\"\"Returns a list of tables/views in the specified database.\n\n If no database is specified, the current database is used.\n This includes all temporary views.\n \"\"\"\n if dbName is None:\n dbName = self.currentDatabase()\n iter = self._jcatalog.listTables(dbName).toLocalIterator()\n tables = []\n while iter.hasNext():\n jtable = iter.next()\n tables.append(Table(\n name=jtable.name(),\n database=jtable.database(),\n description=jtable.description(),\n tableType=jtable.tableType(),\n isTemporary=jtable.isTemporary()))\n return tables" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns a list of functions registered in the specified database.\n\n If no database is specified, the current database is used.\n This includes all temporary functions.", "output": "def listFunctions(self, dbName=None):\n \"\"\"Returns a list of functions registered in the specified database.\n\n If no database is specified, the current database is used.\n This includes all temporary functions.\n \"\"\"\n if dbName is None:\n dbName = self.currentDatabase()\n iter = self._jcatalog.listFunctions(dbName).toLocalIterator()\n functions = []\n while iter.hasNext():\n jfunction = iter.next()\n functions.append(Function(\n name=jfunction.name(),\n description=jfunction.description(),\n className=jfunction.className(),\n isTemporary=jfunction.isTemporary()))\n return functions" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns a list of columns for the given table/view in the specified database.\n\n If no database is specified, the current database is used.\n\n Note: the order of arguments here is different from that of its JVM counterpart\n because Python does not support method overloading.", "output": "def listColumns(self, tableName, dbName=None):\n \"\"\"Returns a list of columns for the given table/view in the specified database.\n\n If no database is specified, the current database is used.\n\n Note: the order of arguments here is different from that of its JVM counterpart\n because Python does not support method overloading.\n \"\"\"\n if dbName is None:\n dbName = self.currentDatabase()\n iter = self._jcatalog.listColumns(dbName, tableName).toLocalIterator()\n columns = []\n while iter.hasNext():\n jcolumn = iter.next()\n columns.append(Column(\n name=jcolumn.name(),\n description=jcolumn.description(),\n dataType=jcolumn.dataType(),\n nullable=jcolumn.nullable(),\n isPartition=jcolumn.isPartition(),\n isBucket=jcolumn.isBucket()))\n return columns" }, { "instruction": "Write or improve a Python function based on this description:\n\nCreates a table based on the dataset in a data source.\n\n It returns the DataFrame associated with the external table.\n\n The data source is specified by the ``source`` and a set of ``options``.\n If ``source`` is not specified, the default data source configured by\n ``spark.sql.sources.default`` will be used.\n\n Optionally, a schema can be provided as the schema of the returned :class:`DataFrame` and\n created external table.\n\n :return: :class:`DataFrame`", "output": "def createExternalTable(self, tableName, path=None, source=None, schema=None, **options):\n \"\"\"Creates a table based on the dataset in a data source.\n\n It returns the DataFrame associated with the external table.\n\n The data source is specified by the ``source`` and a set of ``options``.\n If ``source`` is not specified, the default data source configured by\n ``spark.sql.sources.default`` will be used.\n\n Optionally, a schema can be provided as the schema of the returned :class:`DataFrame` and\n created external table.\n\n :return: :class:`DataFrame`\n \"\"\"\n warnings.warn(\n \"createExternalTable is deprecated since Spark 2.2, please use createTable instead.\",\n DeprecationWarning)\n return self.createTable(tableName, path, source, schema, **options)" }, { "instruction": "Write or improve a Python function based on this description:\n\nCreates a table based on the dataset in a data source.\n\n It returns the DataFrame associated with the table.\n\n The data source is specified by the ``source`` and a set of ``options``.\n If ``source`` is not specified, the default data source configured by\n ``spark.sql.sources.default`` will be used. When ``path`` is specified, an external table is\n created from the data at the given path. Otherwise a managed table is created.\n\n Optionally, a schema can be provided as the schema of the returned :class:`DataFrame` and\n created table.\n\n :return: :class:`DataFrame`", "output": "def createTable(self, tableName, path=None, source=None, schema=None, **options):\n \"\"\"Creates a table based on the dataset in a data source.\n\n It returns the DataFrame associated with the table.\n\n The data source is specified by the ``source`` and a set of ``options``.\n If ``source`` is not specified, the default data source configured by\n ``spark.sql.sources.default`` will be used. When ``path`` is specified, an external table is\n created from the data at the given path. Otherwise a managed table is created.\n\n Optionally, a schema can be provided as the schema of the returned :class:`DataFrame` and\n created table.\n\n :return: :class:`DataFrame`\n \"\"\"\n if path is not None:\n options[\"path\"] = path\n if source is None:\n source = self._sparkSession._wrapped._conf.defaultDataSourceName()\n if schema is None:\n df = self._jcatalog.createTable(tableName, source, options)\n else:\n if not isinstance(schema, StructType):\n raise TypeError(\"schema should be StructType\")\n scala_datatype = self._jsparkSession.parseDataType(schema.json())\n df = self._jcatalog.createTable(tableName, source, scala_datatype, options)\n return DataFrame(df, self._sparkSession._wrapped)" }, { "instruction": "Write or improve a Python function based on this description:\n\nLoad data from a given socket, this is a blocking method thus only return when the socket\n connection has been closed.", "output": "def _load_from_socket(port, auth_secret):\n \"\"\"\n Load data from a given socket, this is a blocking method thus only return when the socket\n connection has been closed.\n \"\"\"\n (sockfile, sock) = local_connect_and_auth(port, auth_secret)\n # The barrier() call may block forever, so no timeout\n sock.settimeout(None)\n # Make a barrier() function call.\n write_int(BARRIER_FUNCTION, sockfile)\n sockfile.flush()\n\n # Collect result.\n res = UTF8Deserializer().loads(sockfile)\n\n # Release resources.\n sockfile.close()\n sock.close()\n\n return res" }, { "instruction": "Write or improve a Python function based on this description:\n\nInternal function to get or create global BarrierTaskContext. We need to make sure\n BarrierTaskContext is returned from here because it is needed in python worker reuse\n scenario, see SPARK-25921 for more details.", "output": "def _getOrCreate(cls):\n \"\"\"\n Internal function to get or create global BarrierTaskContext. We need to make sure\n BarrierTaskContext is returned from here because it is needed in python worker reuse\n scenario, see SPARK-25921 for more details.\n \"\"\"\n if not isinstance(cls._taskContext, BarrierTaskContext):\n cls._taskContext = object.__new__(cls)\n return cls._taskContext" }, { "instruction": "Write or improve a Python function based on this description:\n\nInitialize BarrierTaskContext, other methods within BarrierTaskContext can only be called\n after BarrierTaskContext is initialized.", "output": "def _initialize(cls, port, secret):\n \"\"\"\n Initialize BarrierTaskContext, other methods within BarrierTaskContext can only be called\n after BarrierTaskContext is initialized.\n \"\"\"\n cls._port = port\n cls._secret = secret" }, { "instruction": "Write or improve a Python function based on this description:\n\n.. note:: Experimental\n\n Sets a global barrier and waits until all tasks in this stage hit this barrier.\n Similar to `MPI_Barrier` function in MPI, this function blocks until all tasks\n in the same stage have reached this routine.\n\n .. warning:: In a barrier stage, each task much have the same number of `barrier()`\n calls, in all possible code branches.\n Otherwise, you may get the job hanging or a SparkException after timeout.\n\n .. versionadded:: 2.4.0", "output": "def barrier(self):\n \"\"\"\n .. note:: Experimental\n\n Sets a global barrier and waits until all tasks in this stage hit this barrier.\n Similar to `MPI_Barrier` function in MPI, this function blocks until all tasks\n in the same stage have reached this routine.\n\n .. warning:: In a barrier stage, each task much have the same number of `barrier()`\n calls, in all possible code branches.\n Otherwise, you may get the job hanging or a SparkException after timeout.\n\n .. versionadded:: 2.4.0\n \"\"\"\n if self._port is None or self._secret is None:\n raise Exception(\"Not supported to call barrier() before initialize \" +\n \"BarrierTaskContext.\")\n else:\n _load_from_socket(self._port, self._secret)" }, { "instruction": "Write or improve a Python function based on this description:\n\n.. note:: Experimental\n\n Returns :class:`BarrierTaskInfo` for all tasks in this barrier stage,\n ordered by partition ID.\n\n .. versionadded:: 2.4.0", "output": "def getTaskInfos(self):\n \"\"\"\n .. note:: Experimental\n\n Returns :class:`BarrierTaskInfo` for all tasks in this barrier stage,\n ordered by partition ID.\n\n .. versionadded:: 2.4.0\n \"\"\"\n if self._port is None or self._secret is None:\n raise Exception(\"Not supported to call getTaskInfos() before initialize \" +\n \"BarrierTaskContext.\")\n else:\n addresses = self._localProperties.get(\"addresses\", \"\")\n return [BarrierTaskInfo(h.strip()) for h in addresses.split(\",\")]" }, { "instruction": "Write or improve a Python function based on this description:\n\nA decorator that annotates a function to append the version of Spark the function was added.", "output": "def since(version):\n \"\"\"\n A decorator that annotates a function to append the version of Spark the function was added.\n \"\"\"\n import re\n indent_p = re.compile(r'\\n( +)')\n\n def deco(f):\n indents = indent_p.findall(f.__doc__)\n indent = ' ' * (min(len(m) for m in indents) if indents else 0)\n f.__doc__ = f.__doc__.rstrip() + \"\\n\\n%s.. versionadded:: %s\" % (indent, version)\n return f\n return deco" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns a function with same code, globals, defaults, closure, and\n name (or provide a new name).", "output": "def copy_func(f, name=None, sinceversion=None, doc=None):\n \"\"\"\n Returns a function with same code, globals, defaults, closure, and\n name (or provide a new name).\n \"\"\"\n # See\n # http://stackoverflow.com/questions/6527633/how-can-i-make-a-deepcopy-of-a-function-in-python\n fn = types.FunctionType(f.__code__, f.__globals__, name or f.__name__, f.__defaults__,\n f.__closure__)\n # in case f was given attrs (note this dict is a shallow copy):\n fn.__dict__.update(f.__dict__)\n if doc is not None:\n fn.__doc__ = doc\n if sinceversion is not None:\n fn = since(sinceversion)(fn)\n return fn" }, { "instruction": "Write or improve a Python function based on this description:\n\nA decorator that forces keyword arguments in the wrapped method\n and saves actual input keyword arguments in `_input_kwargs`.\n\n .. note:: Should only be used to wrap a method where first arg is `self`", "output": "def keyword_only(func):\n \"\"\"\n A decorator that forces keyword arguments in the wrapped method\n and saves actual input keyword arguments in `_input_kwargs`.\n\n .. note:: Should only be used to wrap a method where first arg is `self`\n \"\"\"\n @wraps(func)\n def wrapper(self, *args, **kwargs):\n if len(args) > 0:\n raise TypeError(\"Method %s forces keyword arguments.\" % func.__name__)\n self._input_kwargs = kwargs\n return func(self, **kwargs)\n return wrapper" }, { "instruction": "Write or improve a Python function based on this description:\n\nGenerates the header part for shared variables\n\n :param name: param name\n :param doc: param doc", "output": "def _gen_param_header(name, doc, defaultValueStr, typeConverter):\n \"\"\"\n Generates the header part for shared variables\n\n :param name: param name\n :param doc: param doc\n \"\"\"\n template = '''class Has$Name(Params):\n \"\"\"\n Mixin for param $name: $doc\n \"\"\"\n\n $name = Param(Params._dummy(), \"$name\", \"$doc\", typeConverter=$typeConverter)\n\n def __init__(self):\n super(Has$Name, self).__init__()'''\n\n if defaultValueStr is not None:\n template += '''\n self._setDefault($name=$defaultValueStr)'''\n\n Name = name[0].upper() + name[1:]\n if typeConverter is None:\n typeConverter = str(None)\n return template \\\n .replace(\"$name\", name) \\\n .replace(\"$Name\", Name) \\\n .replace(\"$doc\", doc) \\\n .replace(\"$defaultValueStr\", str(defaultValueStr)) \\\n .replace(\"$typeConverter\", typeConverter)" }, { "instruction": "Write or improve a Python function based on this description:\n\nGenerates Python code for a shared param class.\n\n :param name: param name\n :param doc: param doc\n :param defaultValueStr: string representation of the default value\n :return: code string", "output": "def _gen_param_code(name, doc, defaultValueStr):\n \"\"\"\n Generates Python code for a shared param class.\n\n :param name: param name\n :param doc: param doc\n :param defaultValueStr: string representation of the default value\n :return: code string\n \"\"\"\n # TODO: How to correctly inherit instance attributes?\n template = '''\n def set$Name(self, value):\n \"\"\"\n Sets the value of :py:attr:`$name`.\n \"\"\"\n return self._set($name=value)\n\n def get$Name(self):\n \"\"\"\n Gets the value of $name or its default value.\n \"\"\"\n return self.getOrDefault(self.$name)'''\n\n Name = name[0].upper() + name[1:]\n return template \\\n .replace(\"$name\", name) \\\n .replace(\"$Name\", Name) \\\n .replace(\"$doc\", doc) \\\n .replace(\"$defaultValueStr\", str(defaultValueStr))" }, { "instruction": "Write or improve a Python function based on this description:\n\nRuns the bisecting k-means algorithm return the model.\n\n :param rdd:\n Training points as an `RDD` of `Vector` or convertible\n sequence types.\n :param k:\n The desired number of leaf clusters. The actual number could\n be smaller if there are no divisible leaf clusters.\n (default: 4)\n :param maxIterations:\n Maximum number of iterations allowed to split clusters.\n (default: 20)\n :param minDivisibleClusterSize:\n Minimum number of points (if >= 1.0) or the minimum proportion\n of points (if < 1.0) of a divisible cluster.\n (default: 1)\n :param seed:\n Random seed value for cluster initialization.\n (default: -1888008604 from classOf[BisectingKMeans].getName.##)", "output": "def train(self, rdd, k=4, maxIterations=20, minDivisibleClusterSize=1.0, seed=-1888008604):\n \"\"\"\n Runs the bisecting k-means algorithm return the model.\n\n :param rdd:\n Training points as an `RDD` of `Vector` or convertible\n sequence types.\n :param k:\n The desired number of leaf clusters. The actual number could\n be smaller if there are no divisible leaf clusters.\n (default: 4)\n :param maxIterations:\n Maximum number of iterations allowed to split clusters.\n (default: 20)\n :param minDivisibleClusterSize:\n Minimum number of points (if >= 1.0) or the minimum proportion\n of points (if < 1.0) of a divisible cluster.\n (default: 1)\n :param seed:\n Random seed value for cluster initialization.\n (default: -1888008604 from classOf[BisectingKMeans].getName.##)\n \"\"\"\n java_model = callMLlibFunc(\n \"trainBisectingKMeans\", rdd.map(_convert_to_vector),\n k, maxIterations, minDivisibleClusterSize, seed)\n return BisectingKMeansModel(java_model)" }, { "instruction": "Write or improve a Python function based on this description:\n\nTrain a k-means clustering model.\n\n :param rdd:\n Training points as an `RDD` of `Vector` or convertible\n sequence types.\n :param k:\n Number of clusters to create.\n :param maxIterations:\n Maximum number of iterations allowed.\n (default: 100)\n :param runs:\n This param has no effect since Spark 2.0.0.\n :param initializationMode:\n The initialization algorithm. This can be either \"random\" or\n \"k-means||\".\n (default: \"k-means||\")\n :param seed:\n Random seed value for cluster initialization. Set as None to\n generate seed based on system time.\n (default: None)\n :param initializationSteps:\n Number of steps for the k-means|| initialization mode.\n This is an advanced setting -- the default of 2 is almost\n always enough.\n (default: 2)\n :param epsilon:\n Distance threshold within which a center will be considered to\n have converged. If all centers move less than this Euclidean\n distance, iterations are stopped.\n (default: 1e-4)\n :param initialModel:\n Initial cluster centers can be provided as a KMeansModel object\n rather than using the random or k-means|| initializationModel.\n (default: None)", "output": "def train(cls, rdd, k, maxIterations=100, runs=1, initializationMode=\"k-means||\",\n seed=None, initializationSteps=2, epsilon=1e-4, initialModel=None):\n \"\"\"\n Train a k-means clustering model.\n\n :param rdd:\n Training points as an `RDD` of `Vector` or convertible\n sequence types.\n :param k:\n Number of clusters to create.\n :param maxIterations:\n Maximum number of iterations allowed.\n (default: 100)\n :param runs:\n This param has no effect since Spark 2.0.0.\n :param initializationMode:\n The initialization algorithm. This can be either \"random\" or\n \"k-means||\".\n (default: \"k-means||\")\n :param seed:\n Random seed value for cluster initialization. Set as None to\n generate seed based on system time.\n (default: None)\n :param initializationSteps:\n Number of steps for the k-means|| initialization mode.\n This is an advanced setting -- the default of 2 is almost\n always enough.\n (default: 2)\n :param epsilon:\n Distance threshold within which a center will be considered to\n have converged. If all centers move less than this Euclidean\n distance, iterations are stopped.\n (default: 1e-4)\n :param initialModel:\n Initial cluster centers can be provided as a KMeansModel object\n rather than using the random or k-means|| initializationModel.\n (default: None)\n \"\"\"\n if runs != 1:\n warnings.warn(\"The param `runs` has no effect since Spark 2.0.0.\")\n clusterInitialModel = []\n if initialModel is not None:\n if not isinstance(initialModel, KMeansModel):\n raise Exception(\"initialModel is of \"+str(type(initialModel))+\". It needs \"\n \"to be of \")\n clusterInitialModel = [_convert_to_vector(c) for c in initialModel.clusterCenters]\n model = callMLlibFunc(\"trainKMeansModel\", rdd.map(_convert_to_vector), k, maxIterations,\n runs, initializationMode, seed, initializationSteps, epsilon,\n clusterInitialModel)\n centers = callJavaFunc(rdd.context, model.clusterCenters)\n return KMeansModel([c.toArray() for c in centers])" }, { "instruction": "Write or improve a Python function based on this description:\n\nTrain a Gaussian Mixture clustering model.\n\n :param rdd:\n Training points as an `RDD` of `Vector` or convertible\n sequence types.\n :param k:\n Number of independent Gaussians in the mixture model.\n :param convergenceTol:\n Maximum change in log-likelihood at which convergence is\n considered to have occurred.\n (default: 1e-3)\n :param maxIterations:\n Maximum number of iterations allowed.\n (default: 100)\n :param seed:\n Random seed for initial Gaussian distribution. Set as None to\n generate seed based on system time.\n (default: None)\n :param initialModel:\n Initial GMM starting point, bypassing the random\n initialization.\n (default: None)", "output": "def train(cls, rdd, k, convergenceTol=1e-3, maxIterations=100, seed=None, initialModel=None):\n \"\"\"\n Train a Gaussian Mixture clustering model.\n\n :param rdd:\n Training points as an `RDD` of `Vector` or convertible\n sequence types.\n :param k:\n Number of independent Gaussians in the mixture model.\n :param convergenceTol:\n Maximum change in log-likelihood at which convergence is\n considered to have occurred.\n (default: 1e-3)\n :param maxIterations:\n Maximum number of iterations allowed.\n (default: 100)\n :param seed:\n Random seed for initial Gaussian distribution. Set as None to\n generate seed based on system time.\n (default: None)\n :param initialModel:\n Initial GMM starting point, bypassing the random\n initialization.\n (default: None)\n \"\"\"\n initialModelWeights = None\n initialModelMu = None\n initialModelSigma = None\n if initialModel is not None:\n if initialModel.k != k:\n raise Exception(\"Mismatched cluster count, initialModel.k = %s, however k = %s\"\n % (initialModel.k, k))\n initialModelWeights = list(initialModel.weights)\n initialModelMu = [initialModel.gaussians[i].mu for i in range(initialModel.k)]\n initialModelSigma = [initialModel.gaussians[i].sigma for i in range(initialModel.k)]\n java_model = callMLlibFunc(\"trainGaussianMixtureModel\", rdd.map(_convert_to_vector),\n k, convergenceTol, maxIterations, seed,\n initialModelWeights, initialModelMu, initialModelSigma)\n return GaussianMixtureModel(java_model)" }, { "instruction": "Write or improve a Python function based on this description:\n\nLoad a model from the given path.", "output": "def load(cls, sc, path):\n \"\"\"\n Load a model from the given path.\n \"\"\"\n model = cls._load_java(sc, path)\n wrapper =\\\n sc._jvm.org.apache.spark.mllib.api.python.PowerIterationClusteringModelWrapper(model)\n return PowerIterationClusteringModel(wrapper)" }, { "instruction": "Write or improve a Python function based on this description:\n\nr\"\"\"\n :param rdd:\n An RDD of (i, j, s\\ :sub:`ij`\\) tuples representing the\n affinity matrix, which is the matrix A in the PIC paper. The\n similarity s\\ :sub:`ij`\\ must be nonnegative. This is a symmetric\n matrix and hence s\\ :sub:`ij`\\ = s\\ :sub:`ji`\\ For any (i, j) with\n nonzero similarity, there should be either (i, j, s\\ :sub:`ij`\\) or\n (j, i, s\\ :sub:`ji`\\) in the input. Tuples with i = j are ignored,\n because it is assumed s\\ :sub:`ij`\\ = 0.0.\n :param k:\n Number of clusters.\n :param maxIterations:\n Maximum number of iterations of the PIC algorithm.\n (default: 100)\n :param initMode:\n Initialization mode. This can be either \"random\" to use\n a random vector as vertex properties, or \"degree\" to use\n normalized sum similarities.\n (default: \"random\")", "output": "def train(cls, rdd, k, maxIterations=100, initMode=\"random\"):\n r\"\"\"\n :param rdd:\n An RDD of (i, j, s\\ :sub:`ij`\\) tuples representing the\n affinity matrix, which is the matrix A in the PIC paper. The\n similarity s\\ :sub:`ij`\\ must be nonnegative. This is a symmetric\n matrix and hence s\\ :sub:`ij`\\ = s\\ :sub:`ji`\\ For any (i, j) with\n nonzero similarity, there should be either (i, j, s\\ :sub:`ij`\\) or\n (j, i, s\\ :sub:`ji`\\) in the input. Tuples with i = j are ignored,\n because it is assumed s\\ :sub:`ij`\\ = 0.0.\n :param k:\n Number of clusters.\n :param maxIterations:\n Maximum number of iterations of the PIC algorithm.\n (default: 100)\n :param initMode:\n Initialization mode. This can be either \"random\" to use\n a random vector as vertex properties, or \"degree\" to use\n normalized sum similarities.\n (default: \"random\")\n \"\"\"\n model = callMLlibFunc(\"trainPowerIterationClusteringModel\",\n rdd.map(_convert_to_vector), int(k), int(maxIterations), initMode)\n return PowerIterationClusteringModel(model)" }, { "instruction": "Write or improve a Python function based on this description:\n\nUpdate the centroids, according to data\n\n :param data:\n RDD with new data for the model update.\n :param decayFactor:\n Forgetfulness of the previous centroids.\n :param timeUnit:\n Can be \"batches\" or \"points\". If points, then the decay factor\n is raised to the power of number of new points and if batches,\n then decay factor will be used as is.", "output": "def update(self, data, decayFactor, timeUnit):\n \"\"\"Update the centroids, according to data\n\n :param data:\n RDD with new data for the model update.\n :param decayFactor:\n Forgetfulness of the previous centroids.\n :param timeUnit:\n Can be \"batches\" or \"points\". If points, then the decay factor\n is raised to the power of number of new points and if batches,\n then decay factor will be used as is.\n \"\"\"\n if not isinstance(data, RDD):\n raise TypeError(\"Data should be of an RDD, got %s.\" % type(data))\n data = data.map(_convert_to_vector)\n decayFactor = float(decayFactor)\n if timeUnit not in [\"batches\", \"points\"]:\n raise ValueError(\n \"timeUnit should be 'batches' or 'points', got %s.\" % timeUnit)\n vectorCenters = [_convert_to_vector(center) for center in self.centers]\n updatedModel = callMLlibFunc(\n \"updateStreamingKMeansModel\", vectorCenters, self._clusterWeights,\n data, decayFactor, timeUnit)\n self.centers = array(updatedModel[0])\n self._clusterWeights = list(updatedModel[1])\n return self" }, { "instruction": "Write or improve a Python function based on this description:\n\nSet number of batches after which the centroids of that\n particular batch has half the weightage.", "output": "def setHalfLife(self, halfLife, timeUnit):\n \"\"\"\n Set number of batches after which the centroids of that\n particular batch has half the weightage.\n \"\"\"\n self._timeUnit = timeUnit\n self._decayFactor = exp(log(0.5) / halfLife)\n return self" }, { "instruction": "Write or improve a Python function based on this description:\n\nSet initial centers. Should be set before calling trainOn.", "output": "def setInitialCenters(self, centers, weights):\n \"\"\"\n Set initial centers. Should be set before calling trainOn.\n \"\"\"\n self._model = StreamingKMeansModel(centers, weights)\n return self" }, { "instruction": "Write or improve a Python function based on this description:\n\nSet the initial centres to be random samples from\n a gaussian population with constant weights.", "output": "def setRandomCenters(self, dim, weight, seed):\n \"\"\"\n Set the initial centres to be random samples from\n a gaussian population with constant weights.\n \"\"\"\n rng = random.RandomState(seed)\n clusterCenters = rng.randn(self._k, dim)\n clusterWeights = tile(weight, self._k)\n self._model = StreamingKMeansModel(clusterCenters, clusterWeights)\n return self" }, { "instruction": "Write or improve a Python function based on this description:\n\nTrain the model on the incoming dstream.", "output": "def trainOn(self, dstream):\n \"\"\"Train the model on the incoming dstream.\"\"\"\n self._validate(dstream)\n\n def update(rdd):\n self._model.update(rdd, self._decayFactor, self._timeUnit)\n\n dstream.foreachRDD(update)" }, { "instruction": "Write or improve a Python function based on this description:\n\nMake predictions on a dstream.\n Returns a transformed dstream object", "output": "def predictOn(self, dstream):\n \"\"\"\n Make predictions on a dstream.\n Returns a transformed dstream object\n \"\"\"\n self._validate(dstream)\n return dstream.map(lambda x: self._model.predict(x))" }, { "instruction": "Write or improve a Python function based on this description:\n\nMake predictions on a keyed dstream.\n Returns a transformed dstream object.", "output": "def predictOnValues(self, dstream):\n \"\"\"\n Make predictions on a keyed dstream.\n Returns a transformed dstream object.\n \"\"\"\n self._validate(dstream)\n return dstream.mapValues(lambda x: self._model.predict(x))" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn the topics described by weighted terms.\n\n WARNING: If vocabSize and k are large, this can return a large object!\n\n :param maxTermsPerTopic:\n Maximum number of terms to collect for each topic.\n (default: vocabulary size)\n :return:\n Array over topics. Each topic is represented as a pair of\n matching arrays: (term indices, term weights in topic).\n Each topic's terms are sorted in order of decreasing weight.", "output": "def describeTopics(self, maxTermsPerTopic=None):\n \"\"\"Return the topics described by weighted terms.\n\n WARNING: If vocabSize and k are large, this can return a large object!\n\n :param maxTermsPerTopic:\n Maximum number of terms to collect for each topic.\n (default: vocabulary size)\n :return:\n Array over topics. Each topic is represented as a pair of\n matching arrays: (term indices, term weights in topic).\n Each topic's terms are sorted in order of decreasing weight.\n \"\"\"\n if maxTermsPerTopic is None:\n topics = self.call(\"describeTopics\")\n else:\n topics = self.call(\"describeTopics\", maxTermsPerTopic)\n return topics" }, { "instruction": "Write or improve a Python function based on this description:\n\nLoad the LDAModel from disk.\n\n :param sc:\n SparkContext.\n :param path:\n Path to where the model is stored.", "output": "def load(cls, sc, path):\n \"\"\"Load the LDAModel from disk.\n\n :param sc:\n SparkContext.\n :param path:\n Path to where the model is stored.\n \"\"\"\n if not isinstance(sc, SparkContext):\n raise TypeError(\"sc should be a SparkContext, got type %s\" % type(sc))\n if not isinstance(path, basestring):\n raise TypeError(\"path should be a basestring, got type %s\" % type(path))\n model = callMLlibFunc(\"loadLDAModel\", sc, path)\n return LDAModel(model)" }, { "instruction": "Write or improve a Python function based on this description:\n\nTrain a LDA model.\n\n :param rdd:\n RDD of documents, which are tuples of document IDs and term\n (word) count vectors. The term count vectors are \"bags of\n words\" with a fixed-size vocabulary (where the vocabulary size\n is the length of the vector). Document IDs must be unique\n and >= 0.\n :param k:\n Number of topics to infer, i.e., the number of soft cluster\n centers.\n (default: 10)\n :param maxIterations:\n Maximum number of iterations allowed.\n (default: 20)\n :param docConcentration:\n Concentration parameter (commonly named \"alpha\") for the prior\n placed on documents' distributions over topics (\"theta\").\n (default: -1.0)\n :param topicConcentration:\n Concentration parameter (commonly named \"beta\" or \"eta\") for\n the prior placed on topics' distributions over terms.\n (default: -1.0)\n :param seed:\n Random seed for cluster initialization. Set as None to generate\n seed based on system time.\n (default: None)\n :param checkpointInterval:\n Period (in iterations) between checkpoints.\n (default: 10)\n :param optimizer:\n LDAOptimizer used to perform the actual calculation. Currently\n \"em\", \"online\" are supported.\n (default: \"em\")", "output": "def train(cls, rdd, k=10, maxIterations=20, docConcentration=-1.0,\n topicConcentration=-1.0, seed=None, checkpointInterval=10, optimizer=\"em\"):\n \"\"\"Train a LDA model.\n\n :param rdd:\n RDD of documents, which are tuples of document IDs and term\n (word) count vectors. The term count vectors are \"bags of\n words\" with a fixed-size vocabulary (where the vocabulary size\n is the length of the vector). Document IDs must be unique\n and >= 0.\n :param k:\n Number of topics to infer, i.e., the number of soft cluster\n centers.\n (default: 10)\n :param maxIterations:\n Maximum number of iterations allowed.\n (default: 20)\n :param docConcentration:\n Concentration parameter (commonly named \"alpha\") for the prior\n placed on documents' distributions over topics (\"theta\").\n (default: -1.0)\n :param topicConcentration:\n Concentration parameter (commonly named \"beta\" or \"eta\") for\n the prior placed on topics' distributions over terms.\n (default: -1.0)\n :param seed:\n Random seed for cluster initialization. Set as None to generate\n seed based on system time.\n (default: None)\n :param checkpointInterval:\n Period (in iterations) between checkpoints.\n (default: 10)\n :param optimizer:\n LDAOptimizer used to perform the actual calculation. Currently\n \"em\", \"online\" are supported.\n (default: \"em\")\n \"\"\"\n model = callMLlibFunc(\"trainLDAModel\", rdd, k, maxIterations,\n docConcentration, topicConcentration, seed,\n checkpointInterval, optimizer)\n return LDAModel(model)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn a JavaRDD of Object by unpickling\n\n It will convert each Python object into Java object by Pyrolite, whenever the\n RDD is serialized in batch or not.", "output": "def _to_java_object_rdd(rdd):\n \"\"\" Return a JavaRDD of Object by unpickling\n\n It will convert each Python object into Java object by Pyrolite, whenever the\n RDD is serialized in batch or not.\n \"\"\"\n rdd = rdd._reserialize(AutoBatchedSerializer(PickleSerializer()))\n return rdd.ctx._jvm.org.apache.spark.mllib.api.python.SerDe.pythonToJava(rdd._jrdd, True)" }, { "instruction": "Write or improve a Python function based on this description:\n\nConvert Python object into Java", "output": "def _py2java(sc, obj):\n \"\"\" Convert Python object into Java \"\"\"\n if isinstance(obj, RDD):\n obj = _to_java_object_rdd(obj)\n elif isinstance(obj, DataFrame):\n obj = obj._jdf\n elif isinstance(obj, SparkContext):\n obj = obj._jsc\n elif isinstance(obj, list):\n obj = [_py2java(sc, x) for x in obj]\n elif isinstance(obj, JavaObject):\n pass\n elif isinstance(obj, (int, long, float, bool, bytes, unicode)):\n pass\n else:\n data = bytearray(PickleSerializer().dumps(obj))\n obj = sc._jvm.org.apache.spark.mllib.api.python.SerDe.loads(data)\n return obj" }, { "instruction": "Write or improve a Python function based on this description:\n\nCall Java Function", "output": "def callJavaFunc(sc, func, *args):\n \"\"\" Call Java Function \"\"\"\n args = [_py2java(sc, a) for a in args]\n return _java2py(sc, func(*args))" }, { "instruction": "Write or improve a Python function based on this description:\n\nCall API in PythonMLLibAPI", "output": "def callMLlibFunc(name, *args):\n \"\"\" Call API in PythonMLLibAPI \"\"\"\n sc = SparkContext.getOrCreate()\n api = getattr(sc._jvm.PythonMLLibAPI(), name)\n return callJavaFunc(sc, api, *args)" }, { "instruction": "Write or improve a Python function based on this description:\n\nA decorator that makes a class inherit documentation from its parents.", "output": "def inherit_doc(cls):\n \"\"\"\n A decorator that makes a class inherit documentation from its parents.\n \"\"\"\n for name, func in vars(cls).items():\n # only inherit docstring for public functions\n if name.startswith(\"_\"):\n continue\n if not func.__doc__:\n for parent in cls.__bases__:\n parent_func = getattr(parent, name, None)\n if parent_func and getattr(parent_func, \"__doc__\", None):\n func.__doc__ = parent_func.__doc__\n break\n return cls" }, { "instruction": "Write or improve a Python function based on this description:\n\nCall method of java_model", "output": "def call(self, name, *a):\n \"\"\"Call method of java_model\"\"\"\n return callJavaFunc(self._sc, getattr(self._java_model, name), *a)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn a new DStream in which each RDD has a single element\n generated by counting each RDD of this DStream.", "output": "def count(self):\n \"\"\"\n Return a new DStream in which each RDD has a single element\n generated by counting each RDD of this DStream.\n \"\"\"\n return self.mapPartitions(lambda i: [sum(1 for _ in i)]).reduce(operator.add)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn a new DStream containing only the elements that satisfy predicate.", "output": "def filter(self, f):\n \"\"\"\n Return a new DStream containing only the elements that satisfy predicate.\n \"\"\"\n def func(iterator):\n return filter(f, iterator)\n return self.mapPartitions(func, True)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn a new DStream by applying a function to each element of DStream.", "output": "def map(self, f, preservesPartitioning=False):\n \"\"\"\n Return a new DStream by applying a function to each element of DStream.\n \"\"\"\n def func(iterator):\n return map(f, iterator)\n return self.mapPartitions(func, preservesPartitioning)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn a new DStream in which each RDD is generated by applying\n mapPartitionsWithIndex() to each RDDs of this DStream.", "output": "def mapPartitionsWithIndex(self, f, preservesPartitioning=False):\n \"\"\"\n Return a new DStream in which each RDD is generated by applying\n mapPartitionsWithIndex() to each RDDs of this DStream.\n \"\"\"\n return self.transform(lambda rdd: rdd.mapPartitionsWithIndex(f, preservesPartitioning))" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn a new DStream in which each RDD has a single element\n generated by reducing each RDD of this DStream.", "output": "def reduce(self, func):\n \"\"\"\n Return a new DStream in which each RDD has a single element\n generated by reducing each RDD of this DStream.\n \"\"\"\n return self.map(lambda x: (None, x)).reduceByKey(func, 1).map(lambda x: x[1])" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn a new DStream by applying reduceByKey to each RDD.", "output": "def reduceByKey(self, func, numPartitions=None):\n \"\"\"\n Return a new DStream by applying reduceByKey to each RDD.\n \"\"\"\n if numPartitions is None:\n numPartitions = self._sc.defaultParallelism\n return self.combineByKey(lambda x: x, func, func, numPartitions)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn a new DStream by applying combineByKey to each RDD.", "output": "def combineByKey(self, createCombiner, mergeValue, mergeCombiners,\n numPartitions=None):\n \"\"\"\n Return a new DStream by applying combineByKey to each RDD.\n \"\"\"\n if numPartitions is None:\n numPartitions = self._sc.defaultParallelism\n\n def func(rdd):\n return rdd.combineByKey(createCombiner, mergeValue, mergeCombiners, numPartitions)\n return self.transform(func)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn a copy of the DStream in which each RDD are partitioned\n using the specified partitioner.", "output": "def partitionBy(self, numPartitions, partitionFunc=portable_hash):\n \"\"\"\n Return a copy of the DStream in which each RDD are partitioned\n using the specified partitioner.\n \"\"\"\n return self.transform(lambda rdd: rdd.partitionBy(numPartitions, partitionFunc))" }, { "instruction": "Write or improve a Python function based on this description:\n\nApply a function to each RDD in this DStream.", "output": "def foreachRDD(self, func):\n \"\"\"\n Apply a function to each RDD in this DStream.\n \"\"\"\n if func.__code__.co_argcount == 1:\n old_func = func\n func = lambda t, rdd: old_func(rdd)\n jfunc = TransformFunction(self._sc, func, self._jrdd_deserializer)\n api = self._ssc._jvm.PythonDStream\n api.callForeachRDD(self._jdstream, jfunc)" }, { "instruction": "Write or improve a Python function based on this description:\n\nPrint the first num elements of each RDD generated in this DStream.\n\n @param num: the number of elements from the first will be printed.", "output": "def pprint(self, num=10):\n \"\"\"\n Print the first num elements of each RDD generated in this DStream.\n\n @param num: the number of elements from the first will be printed.\n \"\"\"\n def takeAndPrint(time, rdd):\n taken = rdd.take(num + 1)\n print(\"-------------------------------------------\")\n print(\"Time: %s\" % time)\n print(\"-------------------------------------------\")\n for record in taken[:num]:\n print(record)\n if len(taken) > num:\n print(\"...\")\n print(\"\")\n\n self.foreachRDD(takeAndPrint)" }, { "instruction": "Write or improve a Python function based on this description:\n\nPersist the RDDs of this DStream with the given storage level", "output": "def persist(self, storageLevel):\n \"\"\"\n Persist the RDDs of this DStream with the given storage level\n \"\"\"\n self.is_cached = True\n javaStorageLevel = self._sc._getJavaStorageLevel(storageLevel)\n self._jdstream.persist(javaStorageLevel)\n return self" }, { "instruction": "Write or improve a Python function based on this description:\n\nEnable periodic checkpointing of RDDs of this DStream\n\n @param interval: time in seconds, after each period of that, generated\n RDD will be checkpointed", "output": "def checkpoint(self, interval):\n \"\"\"\n Enable periodic checkpointing of RDDs of this DStream\n\n @param interval: time in seconds, after each period of that, generated\n RDD will be checkpointed\n \"\"\"\n self.is_checkpointed = True\n self._jdstream.checkpoint(self._ssc._jduration(interval))\n return self" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn a new DStream by applying groupByKey on each RDD.", "output": "def groupByKey(self, numPartitions=None):\n \"\"\"\n Return a new DStream by applying groupByKey on each RDD.\n \"\"\"\n if numPartitions is None:\n numPartitions = self._sc.defaultParallelism\n return self.transform(lambda rdd: rdd.groupByKey(numPartitions))" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn a new DStream in which each RDD contains the counts of each\n distinct value in each RDD of this DStream.", "output": "def countByValue(self):\n \"\"\"\n Return a new DStream in which each RDD contains the counts of each\n distinct value in each RDD of this DStream.\n \"\"\"\n return self.map(lambda x: (x, 1)).reduceByKey(lambda x, y: x+y)" }, { "instruction": "Write or improve a Python function based on this description:\n\nSave each RDD in this DStream as at text file, using string\n representation of elements.", "output": "def saveAsTextFiles(self, prefix, suffix=None):\n \"\"\"\n Save each RDD in this DStream as at text file, using string\n representation of elements.\n \"\"\"\n def saveAsTextFile(t, rdd):\n path = rddToFileName(prefix, suffix, t)\n try:\n rdd.saveAsTextFile(path)\n except Py4JJavaError as e:\n # after recovered from checkpointing, the foreachRDD may\n # be called twice\n if 'FileAlreadyExistsException' not in str(e):\n raise\n return self.foreachRDD(saveAsTextFile)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn a new DStream in which each RDD is generated by applying a function\n on each RDD of this DStream.\n\n `func` can have one argument of `rdd`, or have two arguments of\n (`time`, `rdd`)", "output": "def transform(self, func):\n \"\"\"\n Return a new DStream in which each RDD is generated by applying a function\n on each RDD of this DStream.\n\n `func` can have one argument of `rdd`, or have two arguments of\n (`time`, `rdd`)\n \"\"\"\n if func.__code__.co_argcount == 1:\n oldfunc = func\n func = lambda t, rdd: oldfunc(rdd)\n assert func.__code__.co_argcount == 2, \"func should take one or two arguments\"\n return TransformedDStream(self, func)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn a new DStream in which each RDD is generated by applying a function\n on each RDD of this DStream and 'other' DStream.\n\n `func` can have two arguments of (`rdd_a`, `rdd_b`) or have three\n arguments of (`time`, `rdd_a`, `rdd_b`)", "output": "def transformWith(self, func, other, keepSerializer=False):\n \"\"\"\n Return a new DStream in which each RDD is generated by applying a function\n on each RDD of this DStream and 'other' DStream.\n\n `func` can have two arguments of (`rdd_a`, `rdd_b`) or have three\n arguments of (`time`, `rdd_a`, `rdd_b`)\n \"\"\"\n if func.__code__.co_argcount == 2:\n oldfunc = func\n func = lambda t, a, b: oldfunc(a, b)\n assert func.__code__.co_argcount == 3, \"func should take two or three arguments\"\n jfunc = TransformFunction(self._sc, func, self._jrdd_deserializer, other._jrdd_deserializer)\n dstream = self._sc._jvm.PythonTransformed2DStream(self._jdstream.dstream(),\n other._jdstream.dstream(), jfunc)\n jrdd_serializer = self._jrdd_deserializer if keepSerializer else self._sc.serializer\n return DStream(dstream.asJavaDStream(), self._ssc, jrdd_serializer)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn a new DStream by unifying data of another DStream with this DStream.\n\n @param other: Another DStream having the same interval (i.e., slideDuration)\n as this DStream.", "output": "def union(self, other):\n \"\"\"\n Return a new DStream by unifying data of another DStream with this DStream.\n\n @param other: Another DStream having the same interval (i.e., slideDuration)\n as this DStream.\n \"\"\"\n if self._slideDuration != other._slideDuration:\n raise ValueError(\"the two DStream should have same slide duration\")\n return self.transformWith(lambda a, b: a.union(b), other, True)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn a new DStream by applying 'cogroup' between RDDs of this\n DStream and `other` DStream.\n\n Hash partitioning is used to generate the RDDs with `numPartitions` partitions.", "output": "def cogroup(self, other, numPartitions=None):\n \"\"\"\n Return a new DStream by applying 'cogroup' between RDDs of this\n DStream and `other` DStream.\n\n Hash partitioning is used to generate the RDDs with `numPartitions` partitions.\n \"\"\"\n if numPartitions is None:\n numPartitions = self._sc.defaultParallelism\n return self.transformWith(lambda a, b: a.cogroup(b, numPartitions), other)" }, { "instruction": "Write or improve a Python function based on this description:\n\nConvert datetime or unix_timestamp into Time", "output": "def _jtime(self, timestamp):\n \"\"\" Convert datetime or unix_timestamp into Time\n \"\"\"\n if isinstance(timestamp, datetime):\n timestamp = time.mktime(timestamp.timetuple())\n return self._sc._jvm.Time(long(timestamp * 1000))" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn all the RDDs between 'begin' to 'end' (both included)\n\n `begin`, `end` could be datetime.datetime() or unix_timestamp", "output": "def slice(self, begin, end):\n \"\"\"\n Return all the RDDs between 'begin' to 'end' (both included)\n\n `begin`, `end` could be datetime.datetime() or unix_timestamp\n \"\"\"\n jrdds = self._jdstream.slice(self._jtime(begin), self._jtime(end))\n return [RDD(jrdd, self._sc, self._jrdd_deserializer) for jrdd in jrdds]" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn a new DStream in which each RDD contains all the elements in seen in a\n sliding window of time over this DStream.\n\n @param windowDuration: width of the window; must be a multiple of this DStream's\n batching interval\n @param slideDuration: sliding interval of the window (i.e., the interval after which\n the new DStream will generate RDDs); must be a multiple of this\n DStream's batching interval", "output": "def window(self, windowDuration, slideDuration=None):\n \"\"\"\n Return a new DStream in which each RDD contains all the elements in seen in a\n sliding window of time over this DStream.\n\n @param windowDuration: width of the window; must be a multiple of this DStream's\n batching interval\n @param slideDuration: sliding interval of the window (i.e., the interval after which\n the new DStream will generate RDDs); must be a multiple of this\n DStream's batching interval\n \"\"\"\n self._validate_window_param(windowDuration, slideDuration)\n d = self._ssc._jduration(windowDuration)\n if slideDuration is None:\n return DStream(self._jdstream.window(d), self._ssc, self._jrdd_deserializer)\n s = self._ssc._jduration(slideDuration)\n return DStream(self._jdstream.window(d, s), self._ssc, self._jrdd_deserializer)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn a new DStream in which each RDD has a single element generated by reducing all\n elements in a sliding window over this DStream.\n\n if `invReduceFunc` is not None, the reduction is done incrementally\n using the old window's reduced value :\n\n 1. reduce the new values that entered the window (e.g., adding new counts)\n\n 2. \"inverse reduce\" the old values that left the window (e.g., subtracting old counts)\n This is more efficient than `invReduceFunc` is None.\n\n @param reduceFunc: associative and commutative reduce function\n @param invReduceFunc: inverse reduce function of `reduceFunc`; such that for all y,\n and invertible x:\n `invReduceFunc(reduceFunc(x, y), x) = y`\n @param windowDuration: width of the window; must be a multiple of this DStream's\n batching interval\n @param slideDuration: sliding interval of the window (i.e., the interval after which\n the new DStream will generate RDDs); must be a multiple of this\n DStream's batching interval", "output": "def reduceByWindow(self, reduceFunc, invReduceFunc, windowDuration, slideDuration):\n \"\"\"\n Return a new DStream in which each RDD has a single element generated by reducing all\n elements in a sliding window over this DStream.\n\n if `invReduceFunc` is not None, the reduction is done incrementally\n using the old window's reduced value :\n\n 1. reduce the new values that entered the window (e.g., adding new counts)\n\n 2. \"inverse reduce\" the old values that left the window (e.g., subtracting old counts)\n This is more efficient than `invReduceFunc` is None.\n\n @param reduceFunc: associative and commutative reduce function\n @param invReduceFunc: inverse reduce function of `reduceFunc`; such that for all y,\n and invertible x:\n `invReduceFunc(reduceFunc(x, y), x) = y`\n @param windowDuration: width of the window; must be a multiple of this DStream's\n batching interval\n @param slideDuration: sliding interval of the window (i.e., the interval after which\n the new DStream will generate RDDs); must be a multiple of this\n DStream's batching interval\n \"\"\"\n keyed = self.map(lambda x: (1, x))\n reduced = keyed.reduceByKeyAndWindow(reduceFunc, invReduceFunc,\n windowDuration, slideDuration, 1)\n return reduced.map(lambda kv: kv[1])" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn a new DStream in which each RDD has a single element generated\n by counting the number of elements in a window over this DStream.\n windowDuration and slideDuration are as defined in the window() operation.\n\n This is equivalent to window(windowDuration, slideDuration).count(),\n but will be more efficient if window is large.", "output": "def countByWindow(self, windowDuration, slideDuration):\n \"\"\"\n Return a new DStream in which each RDD has a single element generated\n by counting the number of elements in a window over this DStream.\n windowDuration and slideDuration are as defined in the window() operation.\n\n This is equivalent to window(windowDuration, slideDuration).count(),\n but will be more efficient if window is large.\n \"\"\"\n return self.map(lambda x: 1).reduceByWindow(operator.add, operator.sub,\n windowDuration, slideDuration)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn a new DStream in which each RDD contains the count of distinct elements in\n RDDs in a sliding window over this DStream.\n\n @param windowDuration: width of the window; must be a multiple of this DStream's\n batching interval\n @param slideDuration: sliding interval of the window (i.e., the interval after which\n the new DStream will generate RDDs); must be a multiple of this\n DStream's batching interval\n @param numPartitions: number of partitions of each RDD in the new DStream.", "output": "def countByValueAndWindow(self, windowDuration, slideDuration, numPartitions=None):\n \"\"\"\n Return a new DStream in which each RDD contains the count of distinct elements in\n RDDs in a sliding window over this DStream.\n\n @param windowDuration: width of the window; must be a multiple of this DStream's\n batching interval\n @param slideDuration: sliding interval of the window (i.e., the interval after which\n the new DStream will generate RDDs); must be a multiple of this\n DStream's batching interval\n @param numPartitions: number of partitions of each RDD in the new DStream.\n \"\"\"\n keyed = self.map(lambda x: (x, 1))\n counted = keyed.reduceByKeyAndWindow(operator.add, operator.sub,\n windowDuration, slideDuration, numPartitions)\n return counted.filter(lambda kv: kv[1] > 0)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn a new DStream by applying `groupByKey` over a sliding window.\n Similar to `DStream.groupByKey()`, but applies it over a sliding window.\n\n @param windowDuration: width of the window; must be a multiple of this DStream's\n batching interval\n @param slideDuration: sliding interval of the window (i.e., the interval after which\n the new DStream will generate RDDs); must be a multiple of this\n DStream's batching interval\n @param numPartitions: Number of partitions of each RDD in the new DStream.", "output": "def groupByKeyAndWindow(self, windowDuration, slideDuration, numPartitions=None):\n \"\"\"\n Return a new DStream by applying `groupByKey` over a sliding window.\n Similar to `DStream.groupByKey()`, but applies it over a sliding window.\n\n @param windowDuration: width of the window; must be a multiple of this DStream's\n batching interval\n @param slideDuration: sliding interval of the window (i.e., the interval after which\n the new DStream will generate RDDs); must be a multiple of this\n DStream's batching interval\n @param numPartitions: Number of partitions of each RDD in the new DStream.\n \"\"\"\n ls = self.mapValues(lambda x: [x])\n grouped = ls.reduceByKeyAndWindow(lambda a, b: a.extend(b) or a, lambda a, b: a[len(b):],\n windowDuration, slideDuration, numPartitions)\n return grouped.mapValues(ResultIterable)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn a new DStream by applying incremental `reduceByKey` over a sliding window.\n\n The reduced value of over a new window is calculated using the old window's reduce value :\n 1. reduce the new values that entered the window (e.g., adding new counts)\n 2. \"inverse reduce\" the old values that left the window (e.g., subtracting old counts)\n\n `invFunc` can be None, then it will reduce all the RDDs in window, could be slower\n than having `invFunc`.\n\n @param func: associative and commutative reduce function\n @param invFunc: inverse function of `reduceFunc`\n @param windowDuration: width of the window; must be a multiple of this DStream's\n batching interval\n @param slideDuration: sliding interval of the window (i.e., the interval after which\n the new DStream will generate RDDs); must be a multiple of this\n DStream's batching interval\n @param numPartitions: number of partitions of each RDD in the new DStream.\n @param filterFunc: function to filter expired key-value pairs;\n only pairs that satisfy the function are retained\n set this to null if you do not want to filter", "output": "def reduceByKeyAndWindow(self, func, invFunc, windowDuration, slideDuration=None,\n numPartitions=None, filterFunc=None):\n \"\"\"\n Return a new DStream by applying incremental `reduceByKey` over a sliding window.\n\n The reduced value of over a new window is calculated using the old window's reduce value :\n 1. reduce the new values that entered the window (e.g., adding new counts)\n 2. \"inverse reduce\" the old values that left the window (e.g., subtracting old counts)\n\n `invFunc` can be None, then it will reduce all the RDDs in window, could be slower\n than having `invFunc`.\n\n @param func: associative and commutative reduce function\n @param invFunc: inverse function of `reduceFunc`\n @param windowDuration: width of the window; must be a multiple of this DStream's\n batching interval\n @param slideDuration: sliding interval of the window (i.e., the interval after which\n the new DStream will generate RDDs); must be a multiple of this\n DStream's batching interval\n @param numPartitions: number of partitions of each RDD in the new DStream.\n @param filterFunc: function to filter expired key-value pairs;\n only pairs that satisfy the function are retained\n set this to null if you do not want to filter\n \"\"\"\n self._validate_window_param(windowDuration, slideDuration)\n if numPartitions is None:\n numPartitions = self._sc.defaultParallelism\n\n reduced = self.reduceByKey(func, numPartitions)\n\n if invFunc:\n def reduceFunc(t, a, b):\n b = b.reduceByKey(func, numPartitions)\n r = a.union(b).reduceByKey(func, numPartitions) if a else b\n if filterFunc:\n r = r.filter(filterFunc)\n return r\n\n def invReduceFunc(t, a, b):\n b = b.reduceByKey(func, numPartitions)\n joined = a.leftOuterJoin(b, numPartitions)\n return joined.mapValues(lambda kv: invFunc(kv[0], kv[1])\n if kv[1] is not None else kv[0])\n\n jreduceFunc = TransformFunction(self._sc, reduceFunc, reduced._jrdd_deserializer)\n jinvReduceFunc = TransformFunction(self._sc, invReduceFunc, reduced._jrdd_deserializer)\n if slideDuration is None:\n slideDuration = self._slideDuration\n dstream = self._sc._jvm.PythonReducedWindowedDStream(\n reduced._jdstream.dstream(),\n jreduceFunc, jinvReduceFunc,\n self._ssc._jduration(windowDuration),\n self._ssc._jduration(slideDuration))\n return DStream(dstream.asJavaDStream(), self._ssc, self._sc.serializer)\n else:\n return reduced.window(windowDuration, slideDuration).reduceByKey(func, numPartitions)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn a new \"state\" DStream where the state for each key is updated by applying\n the given function on the previous state of the key and the new values of the key.\n\n @param updateFunc: State update function. If this function returns None, then\n corresponding state key-value pair will be eliminated.", "output": "def updateStateByKey(self, updateFunc, numPartitions=None, initialRDD=None):\n \"\"\"\n Return a new \"state\" DStream where the state for each key is updated by applying\n the given function on the previous state of the key and the new values of the key.\n\n @param updateFunc: State update function. If this function returns None, then\n corresponding state key-value pair will be eliminated.\n \"\"\"\n if numPartitions is None:\n numPartitions = self._sc.defaultParallelism\n\n if initialRDD and not isinstance(initialRDD, RDD):\n initialRDD = self._sc.parallelize(initialRDD)\n\n def reduceFunc(t, a, b):\n if a is None:\n g = b.groupByKey(numPartitions).mapValues(lambda vs: (list(vs), None))\n else:\n g = a.cogroup(b.partitionBy(numPartitions), numPartitions)\n g = g.mapValues(lambda ab: (list(ab[1]), list(ab[0])[0] if len(ab[0]) else None))\n state = g.mapValues(lambda vs_s: updateFunc(vs_s[0], vs_s[1]))\n return state.filter(lambda k_v: k_v[1] is not None)\n\n jreduceFunc = TransformFunction(self._sc, reduceFunc,\n self._sc.serializer, self._jrdd_deserializer)\n if initialRDD:\n initialRDD = initialRDD._reserialize(self._jrdd_deserializer)\n dstream = self._sc._jvm.PythonStateDStream(self._jdstream.dstream(), jreduceFunc,\n initialRDD._jrdd)\n else:\n dstream = self._sc._jvm.PythonStateDStream(self._jdstream.dstream(), jreduceFunc)\n\n return DStream(dstream.asJavaDStream(), self._ssc, self._sc.serializer)" }, { "instruction": "Write or improve a Python function based on this description:\n\nsetParams(self, minSupport=0.3, minConfidence=0.8, itemsCol=\"items\", \\\n predictionCol=\"prediction\", numPartitions=None)", "output": "def setParams(self, minSupport=0.3, minConfidence=0.8, itemsCol=\"items\",\n predictionCol=\"prediction\", numPartitions=None):\n \"\"\"\n setParams(self, minSupport=0.3, minConfidence=0.8, itemsCol=\"items\", \\\n predictionCol=\"prediction\", numPartitions=None)\n \"\"\"\n kwargs = self._input_kwargs\n return self._set(**kwargs)" }, { "instruction": "Write or improve a Python function based on this description:\n\nsetParams(self, minSupport=0.1, maxPatternLength=10, maxLocalProjDBSize=32000000, \\\n sequenceCol=\"sequence\")", "output": "def setParams(self, minSupport=0.1, maxPatternLength=10, maxLocalProjDBSize=32000000,\n sequenceCol=\"sequence\"):\n \"\"\"\n setParams(self, minSupport=0.1, maxPatternLength=10, maxLocalProjDBSize=32000000, \\\n sequenceCol=\"sequence\")\n \"\"\"\n kwargs = self._input_kwargs\n return self._set(**kwargs)" }, { "instruction": "Write or improve a Python function based on this description:\n\n.. note:: Experimental\n\n Finds the complete set of frequent sequential patterns in the input sequences of itemsets.\n\n :param dataset: A dataframe containing a sequence column which is\n `ArrayType(ArrayType(T))` type, T is the item type for the input dataset.\n :return: A `DataFrame` that contains columns of sequence and corresponding frequency.\n The schema of it will be:\n - `sequence: ArrayType(ArrayType(T))` (T is the item type)\n - `freq: Long`\n\n >>> from pyspark.ml.fpm import PrefixSpan\n >>> from pyspark.sql import Row\n >>> df = sc.parallelize([Row(sequence=[[1, 2], [3]]),\n ... Row(sequence=[[1], [3, 2], [1, 2]]),\n ... Row(sequence=[[1, 2], [5]]),\n ... Row(sequence=[[6]])]).toDF()\n >>> prefixSpan = PrefixSpan(minSupport=0.5, maxPatternLength=5)\n >>> prefixSpan.findFrequentSequentialPatterns(df).sort(\"sequence\").show(truncate=False)\n +----------+----+\n |sequence |freq|\n +----------+----+\n |[[1]] |3 |\n |[[1], [3]]|2 |\n |[[1, 2]] |3 |\n |[[2]] |3 |\n |[[3]] |2 |\n +----------+----+\n\n .. versionadded:: 2.4.0", "output": "def findFrequentSequentialPatterns(self, dataset):\n \"\"\"\n .. note:: Experimental\n\n Finds the complete set of frequent sequential patterns in the input sequences of itemsets.\n\n :param dataset: A dataframe containing a sequence column which is\n `ArrayType(ArrayType(T))` type, T is the item type for the input dataset.\n :return: A `DataFrame` that contains columns of sequence and corresponding frequency.\n The schema of it will be:\n - `sequence: ArrayType(ArrayType(T))` (T is the item type)\n - `freq: Long`\n\n >>> from pyspark.ml.fpm import PrefixSpan\n >>> from pyspark.sql import Row\n >>> df = sc.parallelize([Row(sequence=[[1, 2], [3]]),\n ... Row(sequence=[[1], [3, 2], [1, 2]]),\n ... Row(sequence=[[1, 2], [5]]),\n ... Row(sequence=[[6]])]).toDF()\n >>> prefixSpan = PrefixSpan(minSupport=0.5, maxPatternLength=5)\n >>> prefixSpan.findFrequentSequentialPatterns(df).sort(\"sequence\").show(truncate=False)\n +----------+----+\n |sequence |freq|\n +----------+----+\n |[[1]] |3 |\n |[[1], [3]]|2 |\n |[[1, 2]] |3 |\n |[[2]] |3 |\n |[[3]] |2 |\n +----------+----+\n\n .. versionadded:: 2.4.0\n \"\"\"\n self._transfer_params_to_java()\n jdf = self._java_obj.findFrequentSequentialPatterns(dataset._jdf)\n return DataFrame(jdf, dataset.sql_ctx)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn a CallSite representing the first Spark call in the current call stack.", "output": "def first_spark_call():\n \"\"\"\n Return a CallSite representing the first Spark call in the current call stack.\n \"\"\"\n tb = traceback.extract_stack()\n if len(tb) == 0:\n return None\n file, line, module, what = tb[len(tb) - 1]\n sparkpath = os.path.dirname(file)\n first_spark_frame = len(tb) - 1\n for i in range(0, len(tb)):\n file, line, fun, what = tb[i]\n if file.startswith(sparkpath):\n first_spark_frame = i\n break\n if first_spark_frame == 0:\n file, line, fun, what = tb[0]\n return CallSite(function=fun, file=file, linenum=line)\n sfile, sline, sfun, swhat = tb[first_spark_frame]\n ufile, uline, ufun, uwhat = tb[first_spark_frame - 1]\n return CallSite(function=sfun, file=ufile, linenum=uline)" }, { "instruction": "Write or improve a Python function based on this description:\n\nParse a line of text into an MLlib LabeledPoint object.", "output": "def parsePoint(line):\n \"\"\"\n Parse a line of text into an MLlib LabeledPoint object.\n \"\"\"\n values = [float(s) for s in line.split(' ')]\n if values[0] == -1: # Convert -1 labels to 0 for MLlib\n values[0] = 0\n return LabeledPoint(values[0], values[1:])" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns f-measure.", "output": "def fMeasure(self, label, beta=None):\n \"\"\"\n Returns f-measure.\n \"\"\"\n if beta is None:\n return self.call(\"fMeasure\", label)\n else:\n return self.call(\"fMeasure\", label, beta)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns precision or precision for a given label (category) if specified.", "output": "def precision(self, label=None):\n \"\"\"\n Returns precision or precision for a given label (category) if specified.\n \"\"\"\n if label is None:\n return self.call(\"precision\")\n else:\n return self.call(\"precision\", float(label))" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns recall or recall for a given label (category) if specified.", "output": "def recall(self, label=None):\n \"\"\"\n Returns recall or recall for a given label (category) if specified.\n \"\"\"\n if label is None:\n return self.call(\"recall\")\n else:\n return self.call(\"recall\", float(label))" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns f1Measure or f1Measure for a given label (category) if specified.", "output": "def f1Measure(self, label=None):\n \"\"\"\n Returns f1Measure or f1Measure for a given label (category) if specified.\n \"\"\"\n if label is None:\n return self.call(\"f1Measure\")\n else:\n return self.call(\"f1Measure\", float(label))" }, { "instruction": "Write or improve a Python function based on this description:\n\nWhen converting Spark SQL records to Pandas DataFrame, the inferred data type may be wrong.\n This method gets the corrected data type for Pandas if that type may be inferred uncorrectly.", "output": "def _to_corrected_pandas_type(dt):\n \"\"\"\n When converting Spark SQL records to Pandas DataFrame, the inferred data type may be wrong.\n This method gets the corrected data type for Pandas if that type may be inferred uncorrectly.\n \"\"\"\n import numpy as np\n if type(dt) == ByteType:\n return np.int8\n elif type(dt) == ShortType:\n return np.int16\n elif type(dt) == IntegerType:\n return np.int32\n elif type(dt) == FloatType:\n return np.float32\n else:\n return None" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns the content as an :class:`pyspark.RDD` of :class:`Row`.", "output": "def rdd(self):\n \"\"\"Returns the content as an :class:`pyspark.RDD` of :class:`Row`.\n \"\"\"\n if self._lazy_rdd is None:\n jrdd = self._jdf.javaToPython()\n self._lazy_rdd = RDD(jrdd, self.sql_ctx._sc, BatchedSerializer(PickleSerializer()))\n return self._lazy_rdd" }, { "instruction": "Write or improve a Python function based on this description:\n\nConverts a :class:`DataFrame` into a :class:`RDD` of string.\n\n Each row is turned into a JSON document as one element in the returned RDD.\n\n >>> df.toJSON().first()\n u'{\"age\":2,\"name\":\"Alice\"}'", "output": "def toJSON(self, use_unicode=True):\n \"\"\"Converts a :class:`DataFrame` into a :class:`RDD` of string.\n\n Each row is turned into a JSON document as one element in the returned RDD.\n\n >>> df.toJSON().first()\n u'{\"age\":2,\"name\":\"Alice\"}'\n \"\"\"\n rdd = self._jdf.toJSON()\n return RDD(rdd.toJavaRDD(), self._sc, UTF8Deserializer(use_unicode))" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns the schema of this :class:`DataFrame` as a :class:`pyspark.sql.types.StructType`.\n\n >>> df.schema\n StructType(List(StructField(age,IntegerType,true),StructField(name,StringType,true)))", "output": "def schema(self):\n \"\"\"Returns the schema of this :class:`DataFrame` as a :class:`pyspark.sql.types.StructType`.\n\n >>> df.schema\n StructType(List(StructField(age,IntegerType,true),StructField(name,StringType,true)))\n \"\"\"\n if self._schema is None:\n try:\n self._schema = _parse_datatype_json_string(self._jdf.schema().json())\n except AttributeError as e:\n raise Exception(\n \"Unable to parse datatype from schema. %s\" % e)\n return self._schema" }, { "instruction": "Write or improve a Python function based on this description:\n\nPrints the (logical and physical) plans to the console for debugging purpose.\n\n :param extended: boolean, default ``False``. If ``False``, prints only the physical plan.\n\n >>> df.explain()\n == Physical Plan ==\n *(1) Scan ExistingRDD[age#0,name#1]\n\n >>> df.explain(True)\n == Parsed Logical Plan ==\n ...\n == Analyzed Logical Plan ==\n ...\n == Optimized Logical Plan ==\n ...\n == Physical Plan ==\n ...", "output": "def explain(self, extended=False):\n \"\"\"Prints the (logical and physical) plans to the console for debugging purpose.\n\n :param extended: boolean, default ``False``. If ``False``, prints only the physical plan.\n\n >>> df.explain()\n == Physical Plan ==\n *(1) Scan ExistingRDD[age#0,name#1]\n\n >>> df.explain(True)\n == Parsed Logical Plan ==\n ...\n == Analyzed Logical Plan ==\n ...\n == Optimized Logical Plan ==\n ...\n == Physical Plan ==\n ...\n \"\"\"\n if extended:\n print(self._jdf.queryExecution().toString())\n else:\n print(self._jdf.queryExecution().simpleString())" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn a new :class:`DataFrame` containing rows in this :class:`DataFrame` but\n not in another :class:`DataFrame` while preserving duplicates.\n\n This is equivalent to `EXCEPT ALL` in SQL.\n\n >>> df1 = spark.createDataFrame(\n ... [(\"a\", 1), (\"a\", 1), (\"a\", 1), (\"a\", 2), (\"b\", 3), (\"c\", 4)], [\"C1\", \"C2\"])\n >>> df2 = spark.createDataFrame([(\"a\", 1), (\"b\", 3)], [\"C1\", \"C2\"])\n\n >>> df1.exceptAll(df2).show()\n +---+---+\n | C1| C2|\n +---+---+\n | a| 1|\n | a| 1|\n | a| 2|\n | c| 4|\n +---+---+\n\n Also as standard in SQL, this function resolves columns by position (not by name).", "output": "def exceptAll(self, other):\n \"\"\"Return a new :class:`DataFrame` containing rows in this :class:`DataFrame` but\n not in another :class:`DataFrame` while preserving duplicates.\n\n This is equivalent to `EXCEPT ALL` in SQL.\n\n >>> df1 = spark.createDataFrame(\n ... [(\"a\", 1), (\"a\", 1), (\"a\", 1), (\"a\", 2), (\"b\", 3), (\"c\", 4)], [\"C1\", \"C2\"])\n >>> df2 = spark.createDataFrame([(\"a\", 1), (\"b\", 3)], [\"C1\", \"C2\"])\n\n >>> df1.exceptAll(df2).show()\n +---+---+\n | C1| C2|\n +---+---+\n | a| 1|\n | a| 1|\n | a| 2|\n | c| 4|\n +---+---+\n\n Also as standard in SQL, this function resolves columns by position (not by name).\n \"\"\"\n return DataFrame(self._jdf.exceptAll(other._jdf), self.sql_ctx)" }, { "instruction": "Write or improve a Python function based on this description:\n\nPrints the first ``n`` rows to the console.\n\n :param n: Number of rows to show.\n :param truncate: If set to True, truncate strings longer than 20 chars by default.\n If set to a number greater than one, truncates long strings to length ``truncate``\n and align cells right.\n :param vertical: If set to True, print output rows vertically (one line\n per column value).\n\n >>> df\n DataFrame[age: int, name: string]\n >>> df.show()\n +---+-----+\n |age| name|\n +---+-----+\n | 2|Alice|\n | 5| Bob|\n +---+-----+\n >>> df.show(truncate=3)\n +---+----+\n |age|name|\n +---+----+\n | 2| Ali|\n | 5| Bob|\n +---+----+\n >>> df.show(vertical=True)\n -RECORD 0-----\n age | 2\n name | Alice\n -RECORD 1-----\n age | 5\n name | Bob", "output": "def show(self, n=20, truncate=True, vertical=False):\n \"\"\"Prints the first ``n`` rows to the console.\n\n :param n: Number of rows to show.\n :param truncate: If set to True, truncate strings longer than 20 chars by default.\n If set to a number greater than one, truncates long strings to length ``truncate``\n and align cells right.\n :param vertical: If set to True, print output rows vertically (one line\n per column value).\n\n >>> df\n DataFrame[age: int, name: string]\n >>> df.show()\n +---+-----+\n |age| name|\n +---+-----+\n | 2|Alice|\n | 5| Bob|\n +---+-----+\n >>> df.show(truncate=3)\n +---+----+\n |age|name|\n +---+----+\n | 2| Ali|\n | 5| Bob|\n +---+----+\n >>> df.show(vertical=True)\n -RECORD 0-----\n age | 2\n name | Alice\n -RECORD 1-----\n age | 5\n name | Bob\n \"\"\"\n if isinstance(truncate, bool) and truncate:\n print(self._jdf.showString(n, 20, vertical))\n else:\n print(self._jdf.showString(n, int(truncate), vertical))" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns a dataframe with html code when you enabled eager evaluation\n by 'spark.sql.repl.eagerEval.enabled', this only called by REPL you are\n using support eager evaluation with HTML.", "output": "def _repr_html_(self):\n \"\"\"Returns a dataframe with html code when you enabled eager evaluation\n by 'spark.sql.repl.eagerEval.enabled', this only called by REPL you are\n using support eager evaluation with HTML.\n \"\"\"\n import cgi\n if not self._support_repr_html:\n self._support_repr_html = True\n if self.sql_ctx._conf.isReplEagerEvalEnabled():\n max_num_rows = max(self.sql_ctx._conf.replEagerEvalMaxNumRows(), 0)\n sock_info = self._jdf.getRowsToPython(\n max_num_rows, self.sql_ctx._conf.replEagerEvalTruncate())\n rows = list(_load_from_socket(sock_info, BatchedSerializer(PickleSerializer())))\n head = rows[0]\n row_data = rows[1:]\n has_more_data = len(row_data) > max_num_rows\n row_data = row_data[:max_num_rows]\n\n html = \"\\n\"\n # generate table head\n html += \"\\n\" % \"\\n\" % \"
%s
\".join(map(lambda x: cgi.escape(x), head))\n # generate table rows\n for row in row_data:\n html += \"
%s
\".join(\n map(lambda x: cgi.escape(x), row))\n html += \"
\\n\"\n if has_more_data:\n html += \"only showing top %d %s\\n\" % (\n max_num_rows, \"row\" if max_num_rows == 1 else \"rows\")\n return html\n else:\n return None" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns a checkpointed version of this Dataset. Checkpointing can be used to truncate the\n logical plan of this DataFrame, which is especially useful in iterative algorithms where the\n plan may grow exponentially. It will be saved to files inside the checkpoint\n directory set with L{SparkContext.setCheckpointDir()}.\n\n :param eager: Whether to checkpoint this DataFrame immediately\n\n .. note:: Experimental", "output": "def checkpoint(self, eager=True):\n \"\"\"Returns a checkpointed version of this Dataset. Checkpointing can be used to truncate the\n logical plan of this DataFrame, which is especially useful in iterative algorithms where the\n plan may grow exponentially. It will be saved to files inside the checkpoint\n directory set with L{SparkContext.setCheckpointDir()}.\n\n :param eager: Whether to checkpoint this DataFrame immediately\n\n .. note:: Experimental\n \"\"\"\n jdf = self._jdf.checkpoint(eager)\n return DataFrame(jdf, self.sql_ctx)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns a locally checkpointed version of this Dataset. Checkpointing can be used to\n truncate the logical plan of this DataFrame, which is especially useful in iterative\n algorithms where the plan may grow exponentially. Local checkpoints are stored in the\n executors using the caching subsystem and therefore they are not reliable.\n\n :param eager: Whether to checkpoint this DataFrame immediately\n\n .. note:: Experimental", "output": "def localCheckpoint(self, eager=True):\n \"\"\"Returns a locally checkpointed version of this Dataset. Checkpointing can be used to\n truncate the logical plan of this DataFrame, which is especially useful in iterative\n algorithms where the plan may grow exponentially. Local checkpoints are stored in the\n executors using the caching subsystem and therefore they are not reliable.\n\n :param eager: Whether to checkpoint this DataFrame immediately\n\n .. note:: Experimental\n \"\"\"\n jdf = self._jdf.localCheckpoint(eager)\n return DataFrame(jdf, self.sql_ctx)" }, { "instruction": "Write or improve a Python function based on this description:\n\nDefines an event time watermark for this :class:`DataFrame`. A watermark tracks a point\n in time before which we assume no more late data is going to arrive.\n\n Spark will use this watermark for several purposes:\n - To know when a given time window aggregation can be finalized and thus can be emitted\n when using output modes that do not allow updates.\n\n - To minimize the amount of state that we need to keep for on-going aggregations.\n\n The current watermark is computed by looking at the `MAX(eventTime)` seen across\n all of the partitions in the query minus a user specified `delayThreshold`. Due to the cost\n of coordinating this value across partitions, the actual watermark used is only guaranteed\n to be at least `delayThreshold` behind the actual event time. In some cases we may still\n process records that arrive more than `delayThreshold` late.\n\n :param eventTime: the name of the column that contains the event time of the row.\n :param delayThreshold: the minimum delay to wait to data to arrive late, relative to the\n latest record that has been processed in the form of an interval\n (e.g. \"1 minute\" or \"5 hours\").\n\n .. note:: Evolving\n\n >>> sdf.select('name', sdf.time.cast('timestamp')).withWatermark('time', '10 minutes')\n DataFrame[name: string, time: timestamp]", "output": "def withWatermark(self, eventTime, delayThreshold):\n \"\"\"Defines an event time watermark for this :class:`DataFrame`. A watermark tracks a point\n in time before which we assume no more late data is going to arrive.\n\n Spark will use this watermark for several purposes:\n - To know when a given time window aggregation can be finalized and thus can be emitted\n when using output modes that do not allow updates.\n\n - To minimize the amount of state that we need to keep for on-going aggregations.\n\n The current watermark is computed by looking at the `MAX(eventTime)` seen across\n all of the partitions in the query minus a user specified `delayThreshold`. Due to the cost\n of coordinating this value across partitions, the actual watermark used is only guaranteed\n to be at least `delayThreshold` behind the actual event time. In some cases we may still\n process records that arrive more than `delayThreshold` late.\n\n :param eventTime: the name of the column that contains the event time of the row.\n :param delayThreshold: the minimum delay to wait to data to arrive late, relative to the\n latest record that has been processed in the form of an interval\n (e.g. \"1 minute\" or \"5 hours\").\n\n .. note:: Evolving\n\n >>> sdf.select('name', sdf.time.cast('timestamp')).withWatermark('time', '10 minutes')\n DataFrame[name: string, time: timestamp]\n \"\"\"\n if not eventTime or type(eventTime) is not str:\n raise TypeError(\"eventTime should be provided as a string\")\n if not delayThreshold or type(delayThreshold) is not str:\n raise TypeError(\"delayThreshold should be provided as a string interval\")\n jdf = self._jdf.withWatermark(eventTime, delayThreshold)\n return DataFrame(jdf, self.sql_ctx)" }, { "instruction": "Write or improve a Python function based on this description:\n\nSpecifies some hint on the current DataFrame.\n\n :param name: A name of the hint.\n :param parameters: Optional parameters.\n :return: :class:`DataFrame`\n\n >>> df.join(df2.hint(\"broadcast\"), \"name\").show()\n +----+---+------+\n |name|age|height|\n +----+---+------+\n | Bob| 5| 85|\n +----+---+------+", "output": "def hint(self, name, *parameters):\n \"\"\"Specifies some hint on the current DataFrame.\n\n :param name: A name of the hint.\n :param parameters: Optional parameters.\n :return: :class:`DataFrame`\n\n >>> df.join(df2.hint(\"broadcast\"), \"name\").show()\n +----+---+------+\n |name|age|height|\n +----+---+------+\n | Bob| 5| 85|\n +----+---+------+\n \"\"\"\n if len(parameters) == 1 and isinstance(parameters[0], list):\n parameters = parameters[0]\n\n if not isinstance(name, str):\n raise TypeError(\"name should be provided as str, got {0}\".format(type(name)))\n\n allowed_types = (basestring, list, float, int)\n for p in parameters:\n if not isinstance(p, allowed_types):\n raise TypeError(\n \"all parameters should be in {0}, got {1} of type {2}\".format(\n allowed_types, p, type(p)))\n\n jdf = self._jdf.hint(name, self._jseq(parameters))\n return DataFrame(jdf, self.sql_ctx)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns all the records as a list of :class:`Row`.\n\n >>> df.collect()\n [Row(age=2, name=u'Alice'), Row(age=5, name=u'Bob')]", "output": "def collect(self):\n \"\"\"Returns all the records as a list of :class:`Row`.\n\n >>> df.collect()\n [Row(age=2, name=u'Alice'), Row(age=5, name=u'Bob')]\n \"\"\"\n with SCCallSiteSync(self._sc) as css:\n sock_info = self._jdf.collectToPython()\n return list(_load_from_socket(sock_info, BatchedSerializer(PickleSerializer())))" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns an iterator that contains all of the rows in this :class:`DataFrame`.\n The iterator will consume as much memory as the largest partition in this DataFrame.\n\n >>> list(df.toLocalIterator())\n [Row(age=2, name=u'Alice'), Row(age=5, name=u'Bob')]", "output": "def toLocalIterator(self):\n \"\"\"\n Returns an iterator that contains all of the rows in this :class:`DataFrame`.\n The iterator will consume as much memory as the largest partition in this DataFrame.\n\n >>> list(df.toLocalIterator())\n [Row(age=2, name=u'Alice'), Row(age=5, name=u'Bob')]\n \"\"\"\n with SCCallSiteSync(self._sc) as css:\n sock_info = self._jdf.toPythonIterator()\n return _load_from_socket(sock_info, BatchedSerializer(PickleSerializer()))" }, { "instruction": "Write or improve a Python function based on this description:\n\nLimits the result count to the number specified.\n\n >>> df.limit(1).collect()\n [Row(age=2, name=u'Alice')]\n >>> df.limit(0).collect()\n []", "output": "def limit(self, num):\n \"\"\"Limits the result count to the number specified.\n\n >>> df.limit(1).collect()\n [Row(age=2, name=u'Alice')]\n >>> df.limit(0).collect()\n []\n \"\"\"\n jdf = self._jdf.limit(num)\n return DataFrame(jdf, self.sql_ctx)" }, { "instruction": "Write or improve a Python function based on this description:\n\nSets the storage level to persist the contents of the :class:`DataFrame` across\n operations after the first time it is computed. This can only be used to assign\n a new storage level if the :class:`DataFrame` does not have a storage level set yet.\n If no storage level is specified defaults to (C{MEMORY_AND_DISK}).\n\n .. note:: The default storage level has changed to C{MEMORY_AND_DISK} to match Scala in 2.0.", "output": "def persist(self, storageLevel=StorageLevel.MEMORY_AND_DISK):\n \"\"\"Sets the storage level to persist the contents of the :class:`DataFrame` across\n operations after the first time it is computed. This can only be used to assign\n a new storage level if the :class:`DataFrame` does not have a storage level set yet.\n If no storage level is specified defaults to (C{MEMORY_AND_DISK}).\n\n .. note:: The default storage level has changed to C{MEMORY_AND_DISK} to match Scala in 2.0.\n \"\"\"\n self.is_cached = True\n javaStorageLevel = self._sc._getJavaStorageLevel(storageLevel)\n self._jdf.persist(javaStorageLevel)\n return self" }, { "instruction": "Write or improve a Python function based on this description:\n\nGet the :class:`DataFrame`'s current storage level.\n\n >>> df.storageLevel\n StorageLevel(False, False, False, False, 1)\n >>> df.cache().storageLevel\n StorageLevel(True, True, False, True, 1)\n >>> df2.persist(StorageLevel.DISK_ONLY_2).storageLevel\n StorageLevel(True, False, False, False, 2)", "output": "def storageLevel(self):\n \"\"\"Get the :class:`DataFrame`'s current storage level.\n\n >>> df.storageLevel\n StorageLevel(False, False, False, False, 1)\n >>> df.cache().storageLevel\n StorageLevel(True, True, False, True, 1)\n >>> df2.persist(StorageLevel.DISK_ONLY_2).storageLevel\n StorageLevel(True, False, False, False, 2)\n \"\"\"\n java_storage_level = self._jdf.storageLevel()\n storage_level = StorageLevel(java_storage_level.useDisk(),\n java_storage_level.useMemory(),\n java_storage_level.useOffHeap(),\n java_storage_level.deserialized(),\n java_storage_level.replication())\n return storage_level" }, { "instruction": "Write or improve a Python function based on this description:\n\nMarks the :class:`DataFrame` as non-persistent, and remove all blocks for it from\n memory and disk.\n\n .. note:: `blocking` default has changed to False to match Scala in 2.0.", "output": "def unpersist(self, blocking=False):\n \"\"\"Marks the :class:`DataFrame` as non-persistent, and remove all blocks for it from\n memory and disk.\n\n .. note:: `blocking` default has changed to False to match Scala in 2.0.\n \"\"\"\n self.is_cached = False\n self._jdf.unpersist(blocking)\n return self" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns a new :class:`DataFrame` that has exactly `numPartitions` partitions.\n\n :param numPartitions: int, to specify the target number of partitions\n\n Similar to coalesce defined on an :class:`RDD`, this operation results in a\n narrow dependency, e.g. if you go from 1000 partitions to 100 partitions,\n there will not be a shuffle, instead each of the 100 new partitions will\n claim 10 of the current partitions. If a larger number of partitions is requested,\n it will stay at the current number of partitions.\n\n However, if you're doing a drastic coalesce, e.g. to numPartitions = 1,\n this may result in your computation taking place on fewer nodes than\n you like (e.g. one node in the case of numPartitions = 1). To avoid this,\n you can call repartition(). This will add a shuffle step, but means the\n current upstream partitions will be executed in parallel (per whatever\n the current partitioning is).\n\n >>> df.coalesce(1).rdd.getNumPartitions()\n 1", "output": "def coalesce(self, numPartitions):\n \"\"\"\n Returns a new :class:`DataFrame` that has exactly `numPartitions` partitions.\n\n :param numPartitions: int, to specify the target number of partitions\n\n Similar to coalesce defined on an :class:`RDD`, this operation results in a\n narrow dependency, e.g. if you go from 1000 partitions to 100 partitions,\n there will not be a shuffle, instead each of the 100 new partitions will\n claim 10 of the current partitions. If a larger number of partitions is requested,\n it will stay at the current number of partitions.\n\n However, if you're doing a drastic coalesce, e.g. to numPartitions = 1,\n this may result in your computation taking place on fewer nodes than\n you like (e.g. one node in the case of numPartitions = 1). To avoid this,\n you can call repartition(). This will add a shuffle step, but means the\n current upstream partitions will be executed in parallel (per whatever\n the current partitioning is).\n\n >>> df.coalesce(1).rdd.getNumPartitions()\n 1\n \"\"\"\n return DataFrame(self._jdf.coalesce(numPartitions), self.sql_ctx)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns a new :class:`DataFrame` partitioned by the given partitioning expressions. The\n resulting DataFrame is hash partitioned.\n\n :param numPartitions:\n can be an int to specify the target number of partitions or a Column.\n If it is a Column, it will be used as the first partitioning column. If not specified,\n the default number of partitions is used.\n\n .. versionchanged:: 1.6\n Added optional arguments to specify the partitioning columns. Also made numPartitions\n optional if partitioning columns are specified.\n\n >>> df.repartition(10).rdd.getNumPartitions()\n 10\n >>> data = df.union(df).repartition(\"age\")\n >>> data.show()\n +---+-----+\n |age| name|\n +---+-----+\n | 5| Bob|\n | 5| Bob|\n | 2|Alice|\n | 2|Alice|\n +---+-----+\n >>> data = data.repartition(7, \"age\")\n >>> data.show()\n +---+-----+\n |age| name|\n +---+-----+\n | 2|Alice|\n | 5| Bob|\n | 2|Alice|\n | 5| Bob|\n +---+-----+\n >>> data.rdd.getNumPartitions()\n 7\n >>> data = data.repartition(\"name\", \"age\")\n >>> data.show()\n +---+-----+\n |age| name|\n +---+-----+\n | 5| Bob|\n | 5| Bob|\n | 2|Alice|\n | 2|Alice|\n +---+-----+", "output": "def repartition(self, numPartitions, *cols):\n \"\"\"\n Returns a new :class:`DataFrame` partitioned by the given partitioning expressions. The\n resulting DataFrame is hash partitioned.\n\n :param numPartitions:\n can be an int to specify the target number of partitions or a Column.\n If it is a Column, it will be used as the first partitioning column. If not specified,\n the default number of partitions is used.\n\n .. versionchanged:: 1.6\n Added optional arguments to specify the partitioning columns. Also made numPartitions\n optional if partitioning columns are specified.\n\n >>> df.repartition(10).rdd.getNumPartitions()\n 10\n >>> data = df.union(df).repartition(\"age\")\n >>> data.show()\n +---+-----+\n |age| name|\n +---+-----+\n | 5| Bob|\n | 5| Bob|\n | 2|Alice|\n | 2|Alice|\n +---+-----+\n >>> data = data.repartition(7, \"age\")\n >>> data.show()\n +---+-----+\n |age| name|\n +---+-----+\n | 2|Alice|\n | 5| Bob|\n | 2|Alice|\n | 5| Bob|\n +---+-----+\n >>> data.rdd.getNumPartitions()\n 7\n >>> data = data.repartition(\"name\", \"age\")\n >>> data.show()\n +---+-----+\n |age| name|\n +---+-----+\n | 5| Bob|\n | 5| Bob|\n | 2|Alice|\n | 2|Alice|\n +---+-----+\n \"\"\"\n if isinstance(numPartitions, int):\n if len(cols) == 0:\n return DataFrame(self._jdf.repartition(numPartitions), self.sql_ctx)\n else:\n return DataFrame(\n self._jdf.repartition(numPartitions, self._jcols(*cols)), self.sql_ctx)\n elif isinstance(numPartitions, (basestring, Column)):\n cols = (numPartitions, ) + cols\n return DataFrame(self._jdf.repartition(self._jcols(*cols)), self.sql_ctx)\n else:\n raise TypeError(\"numPartitions should be an int or Column\")" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns a sampled subset of this :class:`DataFrame`.\n\n :param withReplacement: Sample with replacement or not (default False).\n :param fraction: Fraction of rows to generate, range [0.0, 1.0].\n :param seed: Seed for sampling (default a random seed).\n\n .. note:: This is not guaranteed to provide exactly the fraction specified of the total\n count of the given :class:`DataFrame`.\n\n .. note:: `fraction` is required and, `withReplacement` and `seed` are optional.\n\n >>> df = spark.range(10)\n >>> df.sample(0.5, 3).count()\n 7\n >>> df.sample(fraction=0.5, seed=3).count()\n 7\n >>> df.sample(withReplacement=True, fraction=0.5, seed=3).count()\n 1\n >>> df.sample(1.0).count()\n 10\n >>> df.sample(fraction=1.0).count()\n 10\n >>> df.sample(False, fraction=1.0).count()\n 10", "output": "def sample(self, withReplacement=None, fraction=None, seed=None):\n \"\"\"Returns a sampled subset of this :class:`DataFrame`.\n\n :param withReplacement: Sample with replacement or not (default False).\n :param fraction: Fraction of rows to generate, range [0.0, 1.0].\n :param seed: Seed for sampling (default a random seed).\n\n .. note:: This is not guaranteed to provide exactly the fraction specified of the total\n count of the given :class:`DataFrame`.\n\n .. note:: `fraction` is required and, `withReplacement` and `seed` are optional.\n\n >>> df = spark.range(10)\n >>> df.sample(0.5, 3).count()\n 7\n >>> df.sample(fraction=0.5, seed=3).count()\n 7\n >>> df.sample(withReplacement=True, fraction=0.5, seed=3).count()\n 1\n >>> df.sample(1.0).count()\n 10\n >>> df.sample(fraction=1.0).count()\n 10\n >>> df.sample(False, fraction=1.0).count()\n 10\n \"\"\"\n\n # For the cases below:\n # sample(True, 0.5 [, seed])\n # sample(True, fraction=0.5 [, seed])\n # sample(withReplacement=False, fraction=0.5 [, seed])\n is_withReplacement_set = \\\n type(withReplacement) == bool and isinstance(fraction, float)\n\n # For the case below:\n # sample(faction=0.5 [, seed])\n is_withReplacement_omitted_kwargs = \\\n withReplacement is None and isinstance(fraction, float)\n\n # For the case below:\n # sample(0.5 [, seed])\n is_withReplacement_omitted_args = isinstance(withReplacement, float)\n\n if not (is_withReplacement_set\n or is_withReplacement_omitted_kwargs\n or is_withReplacement_omitted_args):\n argtypes = [\n str(type(arg)) for arg in [withReplacement, fraction, seed] if arg is not None]\n raise TypeError(\n \"withReplacement (optional), fraction (required) and seed (optional)\"\n \" should be a bool, float and number; however, \"\n \"got [%s].\" % \", \".join(argtypes))\n\n if is_withReplacement_omitted_args:\n if fraction is not None:\n seed = fraction\n fraction = withReplacement\n withReplacement = None\n\n seed = long(seed) if seed is not None else None\n args = [arg for arg in [withReplacement, fraction, seed] if arg is not None]\n jdf = self._jdf.sample(*args)\n return DataFrame(jdf, self.sql_ctx)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns a stratified sample without replacement based on the\n fraction given on each stratum.\n\n :param col: column that defines strata\n :param fractions:\n sampling fraction for each stratum. If a stratum is not\n specified, we treat its fraction as zero.\n :param seed: random seed\n :return: a new DataFrame that represents the stratified sample\n\n >>> from pyspark.sql.functions import col\n >>> dataset = sqlContext.range(0, 100).select((col(\"id\") % 3).alias(\"key\"))\n >>> sampled = dataset.sampleBy(\"key\", fractions={0: 0.1, 1: 0.2}, seed=0)\n >>> sampled.groupBy(\"key\").count().orderBy(\"key\").show()\n +---+-----+\n |key|count|\n +---+-----+\n | 0| 3|\n | 1| 6|\n +---+-----+\n >>> dataset.sampleBy(col(\"key\"), fractions={2: 1.0}, seed=0).count()\n 33\n\n .. versionchanged:: 3.0\n Added sampling by a column of :class:`Column`", "output": "def sampleBy(self, col, fractions, seed=None):\n \"\"\"\n Returns a stratified sample without replacement based on the\n fraction given on each stratum.\n\n :param col: column that defines strata\n :param fractions:\n sampling fraction for each stratum. If a stratum is not\n specified, we treat its fraction as zero.\n :param seed: random seed\n :return: a new DataFrame that represents the stratified sample\n\n >>> from pyspark.sql.functions import col\n >>> dataset = sqlContext.range(0, 100).select((col(\"id\") % 3).alias(\"key\"))\n >>> sampled = dataset.sampleBy(\"key\", fractions={0: 0.1, 1: 0.2}, seed=0)\n >>> sampled.groupBy(\"key\").count().orderBy(\"key\").show()\n +---+-----+\n |key|count|\n +---+-----+\n | 0| 3|\n | 1| 6|\n +---+-----+\n >>> dataset.sampleBy(col(\"key\"), fractions={2: 1.0}, seed=0).count()\n 33\n\n .. versionchanged:: 3.0\n Added sampling by a column of :class:`Column`\n \"\"\"\n if isinstance(col, basestring):\n col = Column(col)\n elif not isinstance(col, Column):\n raise ValueError(\"col must be a string or a column, but got %r\" % type(col))\n if not isinstance(fractions, dict):\n raise ValueError(\"fractions must be a dict but got %r\" % type(fractions))\n for k, v in fractions.items():\n if not isinstance(k, (float, int, long, basestring)):\n raise ValueError(\"key must be float, int, long, or string, but got %r\" % type(k))\n fractions[k] = float(v)\n col = col._jc\n seed = seed if seed is not None else random.randint(0, sys.maxsize)\n return DataFrame(self._jdf.stat().sampleBy(col, self._jmap(fractions), seed), self.sql_ctx)" }, { "instruction": "Write or improve a Python function based on this description:\n\nRandomly splits this :class:`DataFrame` with the provided weights.\n\n :param weights: list of doubles as weights with which to split the DataFrame. Weights will\n be normalized if they don't sum up to 1.0.\n :param seed: The seed for sampling.\n\n >>> splits = df4.randomSplit([1.0, 2.0], 24)\n >>> splits[0].count()\n 2\n\n >>> splits[1].count()\n 2", "output": "def randomSplit(self, weights, seed=None):\n \"\"\"Randomly splits this :class:`DataFrame` with the provided weights.\n\n :param weights: list of doubles as weights with which to split the DataFrame. Weights will\n be normalized if they don't sum up to 1.0.\n :param seed: The seed for sampling.\n\n >>> splits = df4.randomSplit([1.0, 2.0], 24)\n >>> splits[0].count()\n 2\n\n >>> splits[1].count()\n 2\n \"\"\"\n for w in weights:\n if w < 0.0:\n raise ValueError(\"Weights must be positive. Found weight value: %s\" % w)\n seed = seed if seed is not None else random.randint(0, sys.maxsize)\n rdd_array = self._jdf.randomSplit(_to_list(self.sql_ctx._sc, weights), long(seed))\n return [DataFrame(rdd, self.sql_ctx) for rdd in rdd_array]" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns all column names and their data types as a list.\n\n >>> df.dtypes\n [('age', 'int'), ('name', 'string')]", "output": "def dtypes(self):\n \"\"\"Returns all column names and their data types as a list.\n\n >>> df.dtypes\n [('age', 'int'), ('name', 'string')]\n \"\"\"\n return [(str(f.name), f.dataType.simpleString()) for f in self.schema.fields]" }, { "instruction": "Write or improve a Python function based on this description:\n\nSelects column based on the column name specified as a regex and returns it\n as :class:`Column`.\n\n :param colName: string, column name specified as a regex.\n\n >>> df = spark.createDataFrame([(\"a\", 1), (\"b\", 2), (\"c\", 3)], [\"Col1\", \"Col2\"])\n >>> df.select(df.colRegex(\"`(Col1)?+.+`\")).show()\n +----+\n |Col2|\n +----+\n | 1|\n | 2|\n | 3|\n +----+", "output": "def colRegex(self, colName):\n \"\"\"\n Selects column based on the column name specified as a regex and returns it\n as :class:`Column`.\n\n :param colName: string, column name specified as a regex.\n\n >>> df = spark.createDataFrame([(\"a\", 1), (\"b\", 2), (\"c\", 3)], [\"Col1\", \"Col2\"])\n >>> df.select(df.colRegex(\"`(Col1)?+.+`\")).show()\n +----+\n |Col2|\n +----+\n | 1|\n | 2|\n | 3|\n +----+\n \"\"\"\n if not isinstance(colName, basestring):\n raise ValueError(\"colName should be provided as string\")\n jc = self._jdf.colRegex(colName)\n return Column(jc)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns a new :class:`DataFrame` with an alias set.\n\n :param alias: string, an alias name to be set for the DataFrame.\n\n >>> from pyspark.sql.functions import *\n >>> df_as1 = df.alias(\"df_as1\")\n >>> df_as2 = df.alias(\"df_as2\")\n >>> joined_df = df_as1.join(df_as2, col(\"df_as1.name\") == col(\"df_as2.name\"), 'inner')\n >>> joined_df.select(\"df_as1.name\", \"df_as2.name\", \"df_as2.age\").collect()\n [Row(name=u'Bob', name=u'Bob', age=5), Row(name=u'Alice', name=u'Alice', age=2)]", "output": "def alias(self, alias):\n \"\"\"Returns a new :class:`DataFrame` with an alias set.\n\n :param alias: string, an alias name to be set for the DataFrame.\n\n >>> from pyspark.sql.functions import *\n >>> df_as1 = df.alias(\"df_as1\")\n >>> df_as2 = df.alias(\"df_as2\")\n >>> joined_df = df_as1.join(df_as2, col(\"df_as1.name\") == col(\"df_as2.name\"), 'inner')\n >>> joined_df.select(\"df_as1.name\", \"df_as2.name\", \"df_as2.age\").collect()\n [Row(name=u'Bob', name=u'Bob', age=5), Row(name=u'Alice', name=u'Alice', age=2)]\n \"\"\"\n assert isinstance(alias, basestring), \"alias should be a string\"\n return DataFrame(getattr(self._jdf, \"as\")(alias), self.sql_ctx)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns the cartesian product with another :class:`DataFrame`.\n\n :param other: Right side of the cartesian product.\n\n >>> df.select(\"age\", \"name\").collect()\n [Row(age=2, name=u'Alice'), Row(age=5, name=u'Bob')]\n >>> df2.select(\"name\", \"height\").collect()\n [Row(name=u'Tom', height=80), Row(name=u'Bob', height=85)]\n >>> df.crossJoin(df2.select(\"height\")).select(\"age\", \"name\", \"height\").collect()\n [Row(age=2, name=u'Alice', height=80), Row(age=2, name=u'Alice', height=85),\n Row(age=5, name=u'Bob', height=80), Row(age=5, name=u'Bob', height=85)]", "output": "def crossJoin(self, other):\n \"\"\"Returns the cartesian product with another :class:`DataFrame`.\n\n :param other: Right side of the cartesian product.\n\n >>> df.select(\"age\", \"name\").collect()\n [Row(age=2, name=u'Alice'), Row(age=5, name=u'Bob')]\n >>> df2.select(\"name\", \"height\").collect()\n [Row(name=u'Tom', height=80), Row(name=u'Bob', height=85)]\n >>> df.crossJoin(df2.select(\"height\")).select(\"age\", \"name\", \"height\").collect()\n [Row(age=2, name=u'Alice', height=80), Row(age=2, name=u'Alice', height=85),\n Row(age=5, name=u'Bob', height=80), Row(age=5, name=u'Bob', height=85)]\n \"\"\"\n\n jdf = self._jdf.crossJoin(other._jdf)\n return DataFrame(jdf, self.sql_ctx)" }, { "instruction": "Write or improve a Python function based on this description:\n\nJoins with another :class:`DataFrame`, using the given join expression.\n\n :param other: Right side of the join\n :param on: a string for the join column name, a list of column names,\n a join expression (Column), or a list of Columns.\n If `on` is a string or a list of strings indicating the name of the join column(s),\n the column(s) must exist on both sides, and this performs an equi-join.\n :param how: str, default ``inner``. Must be one of: ``inner``, ``cross``, ``outer``,\n ``full``, ``fullouter``, ``full_outer``, ``left``, ``leftouter``, ``left_outer``,\n ``right``, ``rightouter``, ``right_outer``, ``semi``, ``leftsemi``, ``left_semi``,\n ``anti``, ``leftanti`` and ``left_anti``.\n\n The following performs a full outer join between ``df1`` and ``df2``.\n\n >>> df.join(df2, df.name == df2.name, 'outer').select(df.name, df2.height).collect()\n [Row(name=None, height=80), Row(name=u'Bob', height=85), Row(name=u'Alice', height=None)]\n\n >>> df.join(df2, 'name', 'outer').select('name', 'height').collect()\n [Row(name=u'Tom', height=80), Row(name=u'Bob', height=85), Row(name=u'Alice', height=None)]\n\n >>> cond = [df.name == df3.name, df.age == df3.age]\n >>> df.join(df3, cond, 'outer').select(df.name, df3.age).collect()\n [Row(name=u'Alice', age=2), Row(name=u'Bob', age=5)]\n\n >>> df.join(df2, 'name').select(df.name, df2.height).collect()\n [Row(name=u'Bob', height=85)]\n\n >>> df.join(df4, ['name', 'age']).select(df.name, df.age).collect()\n [Row(name=u'Bob', age=5)]", "output": "def join(self, other, on=None, how=None):\n \"\"\"Joins with another :class:`DataFrame`, using the given join expression.\n\n :param other: Right side of the join\n :param on: a string for the join column name, a list of column names,\n a join expression (Column), or a list of Columns.\n If `on` is a string or a list of strings indicating the name of the join column(s),\n the column(s) must exist on both sides, and this performs an equi-join.\n :param how: str, default ``inner``. Must be one of: ``inner``, ``cross``, ``outer``,\n ``full``, ``fullouter``, ``full_outer``, ``left``, ``leftouter``, ``left_outer``,\n ``right``, ``rightouter``, ``right_outer``, ``semi``, ``leftsemi``, ``left_semi``,\n ``anti``, ``leftanti`` and ``left_anti``.\n\n The following performs a full outer join between ``df1`` and ``df2``.\n\n >>> df.join(df2, df.name == df2.name, 'outer').select(df.name, df2.height).collect()\n [Row(name=None, height=80), Row(name=u'Bob', height=85), Row(name=u'Alice', height=None)]\n\n >>> df.join(df2, 'name', 'outer').select('name', 'height').collect()\n [Row(name=u'Tom', height=80), Row(name=u'Bob', height=85), Row(name=u'Alice', height=None)]\n\n >>> cond = [df.name == df3.name, df.age == df3.age]\n >>> df.join(df3, cond, 'outer').select(df.name, df3.age).collect()\n [Row(name=u'Alice', age=2), Row(name=u'Bob', age=5)]\n\n >>> df.join(df2, 'name').select(df.name, df2.height).collect()\n [Row(name=u'Bob', height=85)]\n\n >>> df.join(df4, ['name', 'age']).select(df.name, df.age).collect()\n [Row(name=u'Bob', age=5)]\n \"\"\"\n\n if on is not None and not isinstance(on, list):\n on = [on]\n\n if on is not None:\n if isinstance(on[0], basestring):\n on = self._jseq(on)\n else:\n assert isinstance(on[0], Column), \"on should be Column or list of Column\"\n on = reduce(lambda x, y: x.__and__(y), on)\n on = on._jc\n\n if on is None and how is None:\n jdf = self._jdf.join(other._jdf)\n else:\n if how is None:\n how = \"inner\"\n if on is None:\n on = self._jseq([])\n assert isinstance(how, basestring), \"how should be basestring\"\n jdf = self._jdf.join(other._jdf, on, how)\n return DataFrame(jdf, self.sql_ctx)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns a new :class:`DataFrame` with each partition sorted by the specified column(s).\n\n :param cols: list of :class:`Column` or column names to sort by.\n :param ascending: boolean or list of boolean (default True).\n Sort ascending vs. descending. Specify list for multiple sort orders.\n If a list is specified, length of the list must equal length of the `cols`.\n\n >>> df.sortWithinPartitions(\"age\", ascending=False).show()\n +---+-----+\n |age| name|\n +---+-----+\n | 2|Alice|\n | 5| Bob|\n +---+-----+", "output": "def sortWithinPartitions(self, *cols, **kwargs):\n \"\"\"Returns a new :class:`DataFrame` with each partition sorted by the specified column(s).\n\n :param cols: list of :class:`Column` or column names to sort by.\n :param ascending: boolean or list of boolean (default True).\n Sort ascending vs. descending. Specify list for multiple sort orders.\n If a list is specified, length of the list must equal length of the `cols`.\n\n >>> df.sortWithinPartitions(\"age\", ascending=False).show()\n +---+-----+\n |age| name|\n +---+-----+\n | 2|Alice|\n | 5| Bob|\n +---+-----+\n \"\"\"\n jdf = self._jdf.sortWithinPartitions(self._sort_cols(cols, kwargs))\n return DataFrame(jdf, self.sql_ctx)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn a JVM Seq of Columns from a list of Column or names", "output": "def _jseq(self, cols, converter=None):\n \"\"\"Return a JVM Seq of Columns from a list of Column or names\"\"\"\n return _to_seq(self.sql_ctx._sc, cols, converter)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn a JVM Seq of Columns from a list of Column or column names\n\n If `cols` has only one list in it, cols[0] will be used as the list.", "output": "def _jcols(self, *cols):\n \"\"\"Return a JVM Seq of Columns from a list of Column or column names\n\n If `cols` has only one list in it, cols[0] will be used as the list.\n \"\"\"\n if len(cols) == 1 and isinstance(cols[0], list):\n cols = cols[0]\n return self._jseq(cols, _to_java_column)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn a JVM Seq of Columns that describes the sort order", "output": "def _sort_cols(self, cols, kwargs):\n \"\"\" Return a JVM Seq of Columns that describes the sort order\n \"\"\"\n if not cols:\n raise ValueError(\"should sort by at least one column\")\n if len(cols) == 1 and isinstance(cols[0], list):\n cols = cols[0]\n jcols = [_to_java_column(c) for c in cols]\n ascending = kwargs.get('ascending', True)\n if isinstance(ascending, (bool, int)):\n if not ascending:\n jcols = [jc.desc() for jc in jcols]\n elif isinstance(ascending, list):\n jcols = [jc if asc else jc.desc()\n for asc, jc in zip(ascending, jcols)]\n else:\n raise TypeError(\"ascending can only be boolean or list, but got %s\" % type(ascending))\n return self._jseq(jcols)" }, { "instruction": "Write or improve a Python function based on this description:\n\nComputes basic statistics for numeric and string columns.\n\n This include count, mean, stddev, min, and max. If no columns are\n given, this function computes statistics for all numerical or string columns.\n\n .. note:: This function is meant for exploratory data analysis, as we make no\n guarantee about the backward compatibility of the schema of the resulting DataFrame.\n\n >>> df.describe(['age']).show()\n +-------+------------------+\n |summary| age|\n +-------+------------------+\n | count| 2|\n | mean| 3.5|\n | stddev|2.1213203435596424|\n | min| 2|\n | max| 5|\n +-------+------------------+\n >>> df.describe().show()\n +-------+------------------+-----+\n |summary| age| name|\n +-------+------------------+-----+\n | count| 2| 2|\n | mean| 3.5| null|\n | stddev|2.1213203435596424| null|\n | min| 2|Alice|\n | max| 5| Bob|\n +-------+------------------+-----+\n\n Use summary for expanded statistics and control over which statistics to compute.", "output": "def describe(self, *cols):\n \"\"\"Computes basic statistics for numeric and string columns.\n\n This include count, mean, stddev, min, and max. If no columns are\n given, this function computes statistics for all numerical or string columns.\n\n .. note:: This function is meant for exploratory data analysis, as we make no\n guarantee about the backward compatibility of the schema of the resulting DataFrame.\n\n >>> df.describe(['age']).show()\n +-------+------------------+\n |summary| age|\n +-------+------------------+\n | count| 2|\n | mean| 3.5|\n | stddev|2.1213203435596424|\n | min| 2|\n | max| 5|\n +-------+------------------+\n >>> df.describe().show()\n +-------+------------------+-----+\n |summary| age| name|\n +-------+------------------+-----+\n | count| 2| 2|\n | mean| 3.5| null|\n | stddev|2.1213203435596424| null|\n | min| 2|Alice|\n | max| 5| Bob|\n +-------+------------------+-----+\n\n Use summary for expanded statistics and control over which statistics to compute.\n \"\"\"\n if len(cols) == 1 and isinstance(cols[0], list):\n cols = cols[0]\n jdf = self._jdf.describe(self._jseq(cols))\n return DataFrame(jdf, self.sql_ctx)" }, { "instruction": "Write or improve a Python function based on this description:\n\nComputes specified statistics for numeric and string columns. Available statistics are:\n - count\n - mean\n - stddev\n - min\n - max\n - arbitrary approximate percentiles specified as a percentage (eg, 75%)\n\n If no statistics are given, this function computes count, mean, stddev, min,\n approximate quartiles (percentiles at 25%, 50%, and 75%), and max.\n\n .. note:: This function is meant for exploratory data analysis, as we make no\n guarantee about the backward compatibility of the schema of the resulting DataFrame.\n\n >>> df.summary().show()\n +-------+------------------+-----+\n |summary| age| name|\n +-------+------------------+-----+\n | count| 2| 2|\n | mean| 3.5| null|\n | stddev|2.1213203435596424| null|\n | min| 2|Alice|\n | 25%| 2| null|\n | 50%| 2| null|\n | 75%| 5| null|\n | max| 5| Bob|\n +-------+------------------+-----+\n\n >>> df.summary(\"count\", \"min\", \"25%\", \"75%\", \"max\").show()\n +-------+---+-----+\n |summary|age| name|\n +-------+---+-----+\n | count| 2| 2|\n | min| 2|Alice|\n | 25%| 2| null|\n | 75%| 5| null|\n | max| 5| Bob|\n +-------+---+-----+\n\n To do a summary for specific columns first select them:\n\n >>> df.select(\"age\", \"name\").summary(\"count\").show()\n +-------+---+----+\n |summary|age|name|\n +-------+---+----+\n | count| 2| 2|\n +-------+---+----+\n\n See also describe for basic statistics.", "output": "def summary(self, *statistics):\n \"\"\"Computes specified statistics for numeric and string columns. Available statistics are:\n - count\n - mean\n - stddev\n - min\n - max\n - arbitrary approximate percentiles specified as a percentage (eg, 75%)\n\n If no statistics are given, this function computes count, mean, stddev, min,\n approximate quartiles (percentiles at 25%, 50%, and 75%), and max.\n\n .. note:: This function is meant for exploratory data analysis, as we make no\n guarantee about the backward compatibility of the schema of the resulting DataFrame.\n\n >>> df.summary().show()\n +-------+------------------+-----+\n |summary| age| name|\n +-------+------------------+-----+\n | count| 2| 2|\n | mean| 3.5| null|\n | stddev|2.1213203435596424| null|\n | min| 2|Alice|\n | 25%| 2| null|\n | 50%| 2| null|\n | 75%| 5| null|\n | max| 5| Bob|\n +-------+------------------+-----+\n\n >>> df.summary(\"count\", \"min\", \"25%\", \"75%\", \"max\").show()\n +-------+---+-----+\n |summary|age| name|\n +-------+---+-----+\n | count| 2| 2|\n | min| 2|Alice|\n | 25%| 2| null|\n | 75%| 5| null|\n | max| 5| Bob|\n +-------+---+-----+\n\n To do a summary for specific columns first select them:\n\n >>> df.select(\"age\", \"name\").summary(\"count\").show()\n +-------+---+----+\n |summary|age|name|\n +-------+---+----+\n | count| 2| 2|\n +-------+---+----+\n\n See also describe for basic statistics.\n \"\"\"\n if len(statistics) == 1 and isinstance(statistics[0], list):\n statistics = statistics[0]\n jdf = self._jdf.summary(self._jseq(statistics))\n return DataFrame(jdf, self.sql_ctx)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns the first ``n`` rows.\n\n .. note:: This method should only be used if the resulting array is expected\n to be small, as all the data is loaded into the driver's memory.\n\n :param n: int, default 1. Number of rows to return.\n :return: If n is greater than 1, return a list of :class:`Row`.\n If n is 1, return a single Row.\n\n >>> df.head()\n Row(age=2, name=u'Alice')\n >>> df.head(1)\n [Row(age=2, name=u'Alice')]", "output": "def head(self, n=None):\n \"\"\"Returns the first ``n`` rows.\n\n .. note:: This method should only be used if the resulting array is expected\n to be small, as all the data is loaded into the driver's memory.\n\n :param n: int, default 1. Number of rows to return.\n :return: If n is greater than 1, return a list of :class:`Row`.\n If n is 1, return a single Row.\n\n >>> df.head()\n Row(age=2, name=u'Alice')\n >>> df.head(1)\n [Row(age=2, name=u'Alice')]\n \"\"\"\n if n is None:\n rs = self.head(1)\n return rs[0] if rs else None\n return self.take(n)" }, { "instruction": "Write or improve a Python function based on this description:\n\nProjects a set of expressions and returns a new :class:`DataFrame`.\n\n :param cols: list of column names (string) or expressions (:class:`Column`).\n If one of the column names is '*', that column is expanded to include all columns\n in the current DataFrame.\n\n >>> df.select('*').collect()\n [Row(age=2, name=u'Alice'), Row(age=5, name=u'Bob')]\n >>> df.select('name', 'age').collect()\n [Row(name=u'Alice', age=2), Row(name=u'Bob', age=5)]\n >>> df.select(df.name, (df.age + 10).alias('age')).collect()\n [Row(name=u'Alice', age=12), Row(name=u'Bob', age=15)]", "output": "def select(self, *cols):\n \"\"\"Projects a set of expressions and returns a new :class:`DataFrame`.\n\n :param cols: list of column names (string) or expressions (:class:`Column`).\n If one of the column names is '*', that column is expanded to include all columns\n in the current DataFrame.\n\n >>> df.select('*').collect()\n [Row(age=2, name=u'Alice'), Row(age=5, name=u'Bob')]\n >>> df.select('name', 'age').collect()\n [Row(name=u'Alice', age=2), Row(name=u'Bob', age=5)]\n >>> df.select(df.name, (df.age + 10).alias('age')).collect()\n [Row(name=u'Alice', age=12), Row(name=u'Bob', age=15)]\n \"\"\"\n jdf = self._jdf.select(self._jcols(*cols))\n return DataFrame(jdf, self.sql_ctx)" }, { "instruction": "Write or improve a Python function based on this description:\n\nProjects a set of SQL expressions and returns a new :class:`DataFrame`.\n\n This is a variant of :func:`select` that accepts SQL expressions.\n\n >>> df.selectExpr(\"age * 2\", \"abs(age)\").collect()\n [Row((age * 2)=4, abs(age)=2), Row((age * 2)=10, abs(age)=5)]", "output": "def selectExpr(self, *expr):\n \"\"\"Projects a set of SQL expressions and returns a new :class:`DataFrame`.\n\n This is a variant of :func:`select` that accepts SQL expressions.\n\n >>> df.selectExpr(\"age * 2\", \"abs(age)\").collect()\n [Row((age * 2)=4, abs(age)=2), Row((age * 2)=10, abs(age)=5)]\n \"\"\"\n if len(expr) == 1 and isinstance(expr[0], list):\n expr = expr[0]\n jdf = self._jdf.selectExpr(self._jseq(expr))\n return DataFrame(jdf, self.sql_ctx)" }, { "instruction": "Write or improve a Python function based on this description:\n\nFilters rows using the given condition.\n\n :func:`where` is an alias for :func:`filter`.\n\n :param condition: a :class:`Column` of :class:`types.BooleanType`\n or a string of SQL expression.\n\n >>> df.filter(df.age > 3).collect()\n [Row(age=5, name=u'Bob')]\n >>> df.where(df.age == 2).collect()\n [Row(age=2, name=u'Alice')]\n\n >>> df.filter(\"age > 3\").collect()\n [Row(age=5, name=u'Bob')]\n >>> df.where(\"age = 2\").collect()\n [Row(age=2, name=u'Alice')]", "output": "def filter(self, condition):\n \"\"\"Filters rows using the given condition.\n\n :func:`where` is an alias for :func:`filter`.\n\n :param condition: a :class:`Column` of :class:`types.BooleanType`\n or a string of SQL expression.\n\n >>> df.filter(df.age > 3).collect()\n [Row(age=5, name=u'Bob')]\n >>> df.where(df.age == 2).collect()\n [Row(age=2, name=u'Alice')]\n\n >>> df.filter(\"age > 3\").collect()\n [Row(age=5, name=u'Bob')]\n >>> df.where(\"age = 2\").collect()\n [Row(age=2, name=u'Alice')]\n \"\"\"\n if isinstance(condition, basestring):\n jdf = self._jdf.filter(condition)\n elif isinstance(condition, Column):\n jdf = self._jdf.filter(condition._jc)\n else:\n raise TypeError(\"condition should be string or Column\")\n return DataFrame(jdf, self.sql_ctx)" }, { "instruction": "Write or improve a Python function based on this description:\n\nGroups the :class:`DataFrame` using the specified columns,\n so we can run aggregation on them. See :class:`GroupedData`\n for all the available aggregate functions.\n\n :func:`groupby` is an alias for :func:`groupBy`.\n\n :param cols: list of columns to group by.\n Each element should be a column name (string) or an expression (:class:`Column`).\n\n >>> df.groupBy().avg().collect()\n [Row(avg(age)=3.5)]\n >>> sorted(df.groupBy('name').agg({'age': 'mean'}).collect())\n [Row(name=u'Alice', avg(age)=2.0), Row(name=u'Bob', avg(age)=5.0)]\n >>> sorted(df.groupBy(df.name).avg().collect())\n [Row(name=u'Alice', avg(age)=2.0), Row(name=u'Bob', avg(age)=5.0)]\n >>> sorted(df.groupBy(['name', df.age]).count().collect())\n [Row(name=u'Alice', age=2, count=1), Row(name=u'Bob', age=5, count=1)]", "output": "def groupBy(self, *cols):\n \"\"\"Groups the :class:`DataFrame` using the specified columns,\n so we can run aggregation on them. See :class:`GroupedData`\n for all the available aggregate functions.\n\n :func:`groupby` is an alias for :func:`groupBy`.\n\n :param cols: list of columns to group by.\n Each element should be a column name (string) or an expression (:class:`Column`).\n\n >>> df.groupBy().avg().collect()\n [Row(avg(age)=3.5)]\n >>> sorted(df.groupBy('name').agg({'age': 'mean'}).collect())\n [Row(name=u'Alice', avg(age)=2.0), Row(name=u'Bob', avg(age)=5.0)]\n >>> sorted(df.groupBy(df.name).avg().collect())\n [Row(name=u'Alice', avg(age)=2.0), Row(name=u'Bob', avg(age)=5.0)]\n >>> sorted(df.groupBy(['name', df.age]).count().collect())\n [Row(name=u'Alice', age=2, count=1), Row(name=u'Bob', age=5, count=1)]\n \"\"\"\n jgd = self._jdf.groupBy(self._jcols(*cols))\n from pyspark.sql.group import GroupedData\n return GroupedData(jgd, self)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn a new :class:`DataFrame` containing union of rows in this and another frame.\n\n This is equivalent to `UNION ALL` in SQL. To do a SQL-style set union\n (that does deduplication of elements), use this function followed by :func:`distinct`.\n\n Also as standard in SQL, this function resolves columns by position (not by name).", "output": "def union(self, other):\n \"\"\" Return a new :class:`DataFrame` containing union of rows in this and another frame.\n\n This is equivalent to `UNION ALL` in SQL. To do a SQL-style set union\n (that does deduplication of elements), use this function followed by :func:`distinct`.\n\n Also as standard in SQL, this function resolves columns by position (not by name).\n \"\"\"\n return DataFrame(self._jdf.union(other._jdf), self.sql_ctx)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns a new :class:`DataFrame` containing union of rows in this and another frame.\n\n This is different from both `UNION ALL` and `UNION DISTINCT` in SQL. To do a SQL-style set\n union (that does deduplication of elements), use this function followed by :func:`distinct`.\n\n The difference between this function and :func:`union` is that this function\n resolves columns by name (not by position):\n\n >>> df1 = spark.createDataFrame([[1, 2, 3]], [\"col0\", \"col1\", \"col2\"])\n >>> df2 = spark.createDataFrame([[4, 5, 6]], [\"col1\", \"col2\", \"col0\"])\n >>> df1.unionByName(df2).show()\n +----+----+----+\n |col0|col1|col2|\n +----+----+----+\n | 1| 2| 3|\n | 6| 4| 5|\n +----+----+----+", "output": "def unionByName(self, other):\n \"\"\" Returns a new :class:`DataFrame` containing union of rows in this and another frame.\n\n This is different from both `UNION ALL` and `UNION DISTINCT` in SQL. To do a SQL-style set\n union (that does deduplication of elements), use this function followed by :func:`distinct`.\n\n The difference between this function and :func:`union` is that this function\n resolves columns by name (not by position):\n\n >>> df1 = spark.createDataFrame([[1, 2, 3]], [\"col0\", \"col1\", \"col2\"])\n >>> df2 = spark.createDataFrame([[4, 5, 6]], [\"col1\", \"col2\", \"col0\"])\n >>> df1.unionByName(df2).show()\n +----+----+----+\n |col0|col1|col2|\n +----+----+----+\n | 1| 2| 3|\n | 6| 4| 5|\n +----+----+----+\n \"\"\"\n return DataFrame(self._jdf.unionByName(other._jdf), self.sql_ctx)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn a new :class:`DataFrame` containing rows only in\n both this frame and another frame.\n\n This is equivalent to `INTERSECT` in SQL.", "output": "def intersect(self, other):\n \"\"\" Return a new :class:`DataFrame` containing rows only in\n both this frame and another frame.\n\n This is equivalent to `INTERSECT` in SQL.\n \"\"\"\n return DataFrame(self._jdf.intersect(other._jdf), self.sql_ctx)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn a new :class:`DataFrame` containing rows in both this dataframe and other\n dataframe while preserving duplicates.\n\n This is equivalent to `INTERSECT ALL` in SQL.\n >>> df1 = spark.createDataFrame([(\"a\", 1), (\"a\", 1), (\"b\", 3), (\"c\", 4)], [\"C1\", \"C2\"])\n >>> df2 = spark.createDataFrame([(\"a\", 1), (\"a\", 1), (\"b\", 3)], [\"C1\", \"C2\"])\n\n >>> df1.intersectAll(df2).sort(\"C1\", \"C2\").show()\n +---+---+\n | C1| C2|\n +---+---+\n | a| 1|\n | a| 1|\n | b| 3|\n +---+---+\n\n Also as standard in SQL, this function resolves columns by position (not by name).", "output": "def intersectAll(self, other):\n \"\"\" Return a new :class:`DataFrame` containing rows in both this dataframe and other\n dataframe while preserving duplicates.\n\n This is equivalent to `INTERSECT ALL` in SQL.\n >>> df1 = spark.createDataFrame([(\"a\", 1), (\"a\", 1), (\"b\", 3), (\"c\", 4)], [\"C1\", \"C2\"])\n >>> df2 = spark.createDataFrame([(\"a\", 1), (\"a\", 1), (\"b\", 3)], [\"C1\", \"C2\"])\n\n >>> df1.intersectAll(df2).sort(\"C1\", \"C2\").show()\n +---+---+\n | C1| C2|\n +---+---+\n | a| 1|\n | a| 1|\n | b| 3|\n +---+---+\n\n Also as standard in SQL, this function resolves columns by position (not by name).\n \"\"\"\n return DataFrame(self._jdf.intersectAll(other._jdf), self.sql_ctx)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn a new :class:`DataFrame` containing rows in this frame\n but not in another frame.\n\n This is equivalent to `EXCEPT DISTINCT` in SQL.", "output": "def subtract(self, other):\n \"\"\" Return a new :class:`DataFrame` containing rows in this frame\n but not in another frame.\n\n This is equivalent to `EXCEPT DISTINCT` in SQL.\n\n \"\"\"\n return DataFrame(getattr(self._jdf, \"except\")(other._jdf), self.sql_ctx)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn a new :class:`DataFrame` with duplicate rows removed,\n optionally only considering certain columns.\n\n For a static batch :class:`DataFrame`, it just drops duplicate rows. For a streaming\n :class:`DataFrame`, it will keep all data across triggers as intermediate state to drop\n duplicates rows. You can use :func:`withWatermark` to limit how late the duplicate data can\n be and system will accordingly limit the state. In addition, too late data older than\n watermark will be dropped to avoid any possibility of duplicates.\n\n :func:`drop_duplicates` is an alias for :func:`dropDuplicates`.\n\n >>> from pyspark.sql import Row\n >>> df = sc.parallelize([ \\\\\n ... Row(name='Alice', age=5, height=80), \\\\\n ... Row(name='Alice', age=5, height=80), \\\\\n ... Row(name='Alice', age=10, height=80)]).toDF()\n >>> df.dropDuplicates().show()\n +---+------+-----+\n |age|height| name|\n +---+------+-----+\n | 5| 80|Alice|\n | 10| 80|Alice|\n +---+------+-----+\n\n >>> df.dropDuplicates(['name', 'height']).show()\n +---+------+-----+\n |age|height| name|\n +---+------+-----+\n | 5| 80|Alice|\n +---+------+-----+", "output": "def dropDuplicates(self, subset=None):\n \"\"\"Return a new :class:`DataFrame` with duplicate rows removed,\n optionally only considering certain columns.\n\n For a static batch :class:`DataFrame`, it just drops duplicate rows. For a streaming\n :class:`DataFrame`, it will keep all data across triggers as intermediate state to drop\n duplicates rows. You can use :func:`withWatermark` to limit how late the duplicate data can\n be and system will accordingly limit the state. In addition, too late data older than\n watermark will be dropped to avoid any possibility of duplicates.\n\n :func:`drop_duplicates` is an alias for :func:`dropDuplicates`.\n\n >>> from pyspark.sql import Row\n >>> df = sc.parallelize([ \\\\\n ... Row(name='Alice', age=5, height=80), \\\\\n ... Row(name='Alice', age=5, height=80), \\\\\n ... Row(name='Alice', age=10, height=80)]).toDF()\n >>> df.dropDuplicates().show()\n +---+------+-----+\n |age|height| name|\n +---+------+-----+\n | 5| 80|Alice|\n | 10| 80|Alice|\n +---+------+-----+\n\n >>> df.dropDuplicates(['name', 'height']).show()\n +---+------+-----+\n |age|height| name|\n +---+------+-----+\n | 5| 80|Alice|\n +---+------+-----+\n \"\"\"\n if subset is None:\n jdf = self._jdf.dropDuplicates()\n else:\n jdf = self._jdf.dropDuplicates(self._jseq(subset))\n return DataFrame(jdf, self.sql_ctx)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns a new :class:`DataFrame` omitting rows with null values.\n :func:`DataFrame.dropna` and :func:`DataFrameNaFunctions.drop` are aliases of each other.\n\n :param how: 'any' or 'all'.\n If 'any', drop a row if it contains any nulls.\n If 'all', drop a row only if all its values are null.\n :param thresh: int, default None\n If specified, drop rows that have less than `thresh` non-null values.\n This overwrites the `how` parameter.\n :param subset: optional list of column names to consider.\n\n >>> df4.na.drop().show()\n +---+------+-----+\n |age|height| name|\n +---+------+-----+\n | 10| 80|Alice|\n +---+------+-----+", "output": "def dropna(self, how='any', thresh=None, subset=None):\n \"\"\"Returns a new :class:`DataFrame` omitting rows with null values.\n :func:`DataFrame.dropna` and :func:`DataFrameNaFunctions.drop` are aliases of each other.\n\n :param how: 'any' or 'all'.\n If 'any', drop a row if it contains any nulls.\n If 'all', drop a row only if all its values are null.\n :param thresh: int, default None\n If specified, drop rows that have less than `thresh` non-null values.\n This overwrites the `how` parameter.\n :param subset: optional list of column names to consider.\n\n >>> df4.na.drop().show()\n +---+------+-----+\n |age|height| name|\n +---+------+-----+\n | 10| 80|Alice|\n +---+------+-----+\n \"\"\"\n if how is not None and how not in ['any', 'all']:\n raise ValueError(\"how ('\" + how + \"') should be 'any' or 'all'\")\n\n if subset is None:\n subset = self.columns\n elif isinstance(subset, basestring):\n subset = [subset]\n elif not isinstance(subset, (list, tuple)):\n raise ValueError(\"subset should be a list or tuple of column names\")\n\n if thresh is None:\n thresh = len(subset) if how == 'any' else 1\n\n return DataFrame(self._jdf.na().drop(thresh, self._jseq(subset)), self.sql_ctx)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReplace null values, alias for ``na.fill()``.\n :func:`DataFrame.fillna` and :func:`DataFrameNaFunctions.fill` are aliases of each other.\n\n :param value: int, long, float, string, bool or dict.\n Value to replace null values with.\n If the value is a dict, then `subset` is ignored and `value` must be a mapping\n from column name (string) to replacement value. The replacement value must be\n an int, long, float, boolean, or string.\n :param subset: optional list of column names to consider.\n Columns specified in subset that do not have matching data type are ignored.\n For example, if `value` is a string, and subset contains a non-string column,\n then the non-string column is simply ignored.\n\n >>> df4.na.fill(50).show()\n +---+------+-----+\n |age|height| name|\n +---+------+-----+\n | 10| 80|Alice|\n | 5| 50| Bob|\n | 50| 50| Tom|\n | 50| 50| null|\n +---+------+-----+\n\n >>> df5.na.fill(False).show()\n +----+-------+-----+\n | age| name| spy|\n +----+-------+-----+\n | 10| Alice|false|\n | 5| Bob|false|\n |null|Mallory| true|\n +----+-------+-----+\n\n >>> df4.na.fill({'age': 50, 'name': 'unknown'}).show()\n +---+------+-------+\n |age|height| name|\n +---+------+-------+\n | 10| 80| Alice|\n | 5| null| Bob|\n | 50| null| Tom|\n | 50| null|unknown|\n +---+------+-------+", "output": "def fillna(self, value, subset=None):\n \"\"\"Replace null values, alias for ``na.fill()``.\n :func:`DataFrame.fillna` and :func:`DataFrameNaFunctions.fill` are aliases of each other.\n\n :param value: int, long, float, string, bool or dict.\n Value to replace null values with.\n If the value is a dict, then `subset` is ignored and `value` must be a mapping\n from column name (string) to replacement value. The replacement value must be\n an int, long, float, boolean, or string.\n :param subset: optional list of column names to consider.\n Columns specified in subset that do not have matching data type are ignored.\n For example, if `value` is a string, and subset contains a non-string column,\n then the non-string column is simply ignored.\n\n >>> df4.na.fill(50).show()\n +---+------+-----+\n |age|height| name|\n +---+------+-----+\n | 10| 80|Alice|\n | 5| 50| Bob|\n | 50| 50| Tom|\n | 50| 50| null|\n +---+------+-----+\n\n >>> df5.na.fill(False).show()\n +----+-------+-----+\n | age| name| spy|\n +----+-------+-----+\n | 10| Alice|false|\n | 5| Bob|false|\n |null|Mallory| true|\n +----+-------+-----+\n\n >>> df4.na.fill({'age': 50, 'name': 'unknown'}).show()\n +---+------+-------+\n |age|height| name|\n +---+------+-------+\n | 10| 80| Alice|\n | 5| null| Bob|\n | 50| null| Tom|\n | 50| null|unknown|\n +---+------+-------+\n \"\"\"\n if not isinstance(value, (float, int, long, basestring, bool, dict)):\n raise ValueError(\"value should be a float, int, long, string, bool or dict\")\n\n # Note that bool validates isinstance(int), but we don't want to\n # convert bools to floats\n\n if not isinstance(value, bool) and isinstance(value, (int, long)):\n value = float(value)\n\n if isinstance(value, dict):\n return DataFrame(self._jdf.na().fill(value), self.sql_ctx)\n elif subset is None:\n return DataFrame(self._jdf.na().fill(value), self.sql_ctx)\n else:\n if isinstance(subset, basestring):\n subset = [subset]\n elif not isinstance(subset, (list, tuple)):\n raise ValueError(\"subset should be a list or tuple of column names\")\n\n return DataFrame(self._jdf.na().fill(value, self._jseq(subset)), self.sql_ctx)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns a new :class:`DataFrame` replacing a value with another value.\n :func:`DataFrame.replace` and :func:`DataFrameNaFunctions.replace` are\n aliases of each other.\n Values to_replace and value must have the same type and can only be numerics, booleans,\n or strings. Value can have None. When replacing, the new value will be cast\n to the type of the existing column.\n For numeric replacements all values to be replaced should have unique\n floating point representation. In case of conflicts (for example with `{42: -1, 42.0: 1}`)\n and arbitrary replacement will be used.\n\n :param to_replace: bool, int, long, float, string, list or dict.\n Value to be replaced.\n If the value is a dict, then `value` is ignored or can be omitted, and `to_replace`\n must be a mapping between a value and a replacement.\n :param value: bool, int, long, float, string, list or None.\n The replacement value must be a bool, int, long, float, string or None. If `value` is a\n list, `value` should be of the same length and type as `to_replace`.\n If `value` is a scalar and `to_replace` is a sequence, then `value` is\n used as a replacement for each item in `to_replace`.\n :param subset: optional list of column names to consider.\n Columns specified in subset that do not have matching data type are ignored.\n For example, if `value` is a string, and subset contains a non-string column,\n then the non-string column is simply ignored.\n\n >>> df4.na.replace(10, 20).show()\n +----+------+-----+\n | age|height| name|\n +----+------+-----+\n | 20| 80|Alice|\n | 5| null| Bob|\n |null| null| Tom|\n |null| null| null|\n +----+------+-----+\n\n >>> df4.na.replace('Alice', None).show()\n +----+------+----+\n | age|height|name|\n +----+------+----+\n | 10| 80|null|\n | 5| null| Bob|\n |null| null| Tom|\n |null| null|null|\n +----+------+----+\n\n >>> df4.na.replace({'Alice': None}).show()\n +----+------+----+\n | age|height|name|\n +----+------+----+\n | 10| 80|null|\n | 5| null| Bob|\n |null| null| Tom|\n |null| null|null|\n +----+------+----+\n\n >>> df4.na.replace(['Alice', 'Bob'], ['A', 'B'], 'name').show()\n +----+------+----+\n | age|height|name|\n +----+------+----+\n | 10| 80| A|\n | 5| null| B|\n |null| null| Tom|\n |null| null|null|\n +----+------+----+", "output": "def replace(self, to_replace, value=_NoValue, subset=None):\n \"\"\"Returns a new :class:`DataFrame` replacing a value with another value.\n :func:`DataFrame.replace` and :func:`DataFrameNaFunctions.replace` are\n aliases of each other.\n Values to_replace and value must have the same type and can only be numerics, booleans,\n or strings. Value can have None. When replacing, the new value will be cast\n to the type of the existing column.\n For numeric replacements all values to be replaced should have unique\n floating point representation. In case of conflicts (for example with `{42: -1, 42.0: 1}`)\n and arbitrary replacement will be used.\n\n :param to_replace: bool, int, long, float, string, list or dict.\n Value to be replaced.\n If the value is a dict, then `value` is ignored or can be omitted, and `to_replace`\n must be a mapping between a value and a replacement.\n :param value: bool, int, long, float, string, list or None.\n The replacement value must be a bool, int, long, float, string or None. If `value` is a\n list, `value` should be of the same length and type as `to_replace`.\n If `value` is a scalar and `to_replace` is a sequence, then `value` is\n used as a replacement for each item in `to_replace`.\n :param subset: optional list of column names to consider.\n Columns specified in subset that do not have matching data type are ignored.\n For example, if `value` is a string, and subset contains a non-string column,\n then the non-string column is simply ignored.\n\n >>> df4.na.replace(10, 20).show()\n +----+------+-----+\n | age|height| name|\n +----+------+-----+\n | 20| 80|Alice|\n | 5| null| Bob|\n |null| null| Tom|\n |null| null| null|\n +----+------+-----+\n\n >>> df4.na.replace('Alice', None).show()\n +----+------+----+\n | age|height|name|\n +----+------+----+\n | 10| 80|null|\n | 5| null| Bob|\n |null| null| Tom|\n |null| null|null|\n +----+------+----+\n\n >>> df4.na.replace({'Alice': None}).show()\n +----+------+----+\n | age|height|name|\n +----+------+----+\n | 10| 80|null|\n | 5| null| Bob|\n |null| null| Tom|\n |null| null|null|\n +----+------+----+\n\n >>> df4.na.replace(['Alice', 'Bob'], ['A', 'B'], 'name').show()\n +----+------+----+\n | age|height|name|\n +----+------+----+\n | 10| 80| A|\n | 5| null| B|\n |null| null| Tom|\n |null| null|null|\n +----+------+----+\n \"\"\"\n if value is _NoValue:\n if isinstance(to_replace, dict):\n value = None\n else:\n raise TypeError(\"value argument is required when to_replace is not a dictionary.\")\n\n # Helper functions\n def all_of(types):\n \"\"\"Given a type or tuple of types and a sequence of xs\n check if each x is instance of type(s)\n\n >>> all_of(bool)([True, False])\n True\n >>> all_of(basestring)([\"a\", 1])\n False\n \"\"\"\n def all_of_(xs):\n return all(isinstance(x, types) for x in xs)\n return all_of_\n\n all_of_bool = all_of(bool)\n all_of_str = all_of(basestring)\n all_of_numeric = all_of((float, int, long))\n\n # Validate input types\n valid_types = (bool, float, int, long, basestring, list, tuple)\n if not isinstance(to_replace, valid_types + (dict, )):\n raise ValueError(\n \"to_replace should be a bool, float, int, long, string, list, tuple, or dict. \"\n \"Got {0}\".format(type(to_replace)))\n\n if not isinstance(value, valid_types) and value is not None \\\n and not isinstance(to_replace, dict):\n raise ValueError(\"If to_replace is not a dict, value should be \"\n \"a bool, float, int, long, string, list, tuple or None. \"\n \"Got {0}\".format(type(value)))\n\n if isinstance(to_replace, (list, tuple)) and isinstance(value, (list, tuple)):\n if len(to_replace) != len(value):\n raise ValueError(\"to_replace and value lists should be of the same length. \"\n \"Got {0} and {1}\".format(len(to_replace), len(value)))\n\n if not (subset is None or isinstance(subset, (list, tuple, basestring))):\n raise ValueError(\"subset should be a list or tuple of column names, \"\n \"column name or None. Got {0}\".format(type(subset)))\n\n # Reshape input arguments if necessary\n if isinstance(to_replace, (float, int, long, basestring)):\n to_replace = [to_replace]\n\n if isinstance(to_replace, dict):\n rep_dict = to_replace\n if value is not None:\n warnings.warn(\"to_replace is a dict and value is not None. value will be ignored.\")\n else:\n if isinstance(value, (float, int, long, basestring)) or value is None:\n value = [value for _ in range(len(to_replace))]\n rep_dict = dict(zip(to_replace, value))\n\n if isinstance(subset, basestring):\n subset = [subset]\n\n # Verify we were not passed in mixed type generics.\n if not any(all_of_type(rep_dict.keys())\n and all_of_type(x for x in rep_dict.values() if x is not None)\n for all_of_type in [all_of_bool, all_of_str, all_of_numeric]):\n raise ValueError(\"Mixed type replacements are not supported\")\n\n if subset is None:\n return DataFrame(self._jdf.na().replace('*', rep_dict), self.sql_ctx)\n else:\n return DataFrame(\n self._jdf.na().replace(self._jseq(subset), self._jmap(rep_dict)), self.sql_ctx)" }, { "instruction": "Write or improve a Python function based on this description:\n\nCalculates the approximate quantiles of numerical columns of a\n DataFrame.\n\n The result of this algorithm has the following deterministic bound:\n If the DataFrame has N elements and if we request the quantile at\n probability `p` up to error `err`, then the algorithm will return\n a sample `x` from the DataFrame so that the *exact* rank of `x` is\n close to (p * N). More precisely,\n\n floor((p - err) * N) <= rank(x) <= ceil((p + err) * N).\n\n This method implements a variation of the Greenwald-Khanna\n algorithm (with some speed optimizations). The algorithm was first\n present in [[https://doi.org/10.1145/375663.375670\n Space-efficient Online Computation of Quantile Summaries]]\n by Greenwald and Khanna.\n\n Note that null values will be ignored in numerical columns before calculation.\n For columns only containing null values, an empty list is returned.\n\n :param col: str, list.\n Can be a single column name, or a list of names for multiple columns.\n :param probabilities: a list of quantile probabilities\n Each number must belong to [0, 1].\n For example 0 is the minimum, 0.5 is the median, 1 is the maximum.\n :param relativeError: The relative target precision to achieve\n (>= 0). If set to zero, the exact quantiles are computed, which\n could be very expensive. Note that values greater than 1 are\n accepted but give the same result as 1.\n :return: the approximate quantiles at the given probabilities. If\n the input `col` is a string, the output is a list of floats. If the\n input `col` is a list or tuple of strings, the output is also a\n list, but each element in it is a list of floats, i.e., the output\n is a list of list of floats.\n\n .. versionchanged:: 2.2\n Added support for multiple columns.", "output": "def approxQuantile(self, col, probabilities, relativeError):\n \"\"\"\n Calculates the approximate quantiles of numerical columns of a\n DataFrame.\n\n The result of this algorithm has the following deterministic bound:\n If the DataFrame has N elements and if we request the quantile at\n probability `p` up to error `err`, then the algorithm will return\n a sample `x` from the DataFrame so that the *exact* rank of `x` is\n close to (p * N). More precisely,\n\n floor((p - err) * N) <= rank(x) <= ceil((p + err) * N).\n\n This method implements a variation of the Greenwald-Khanna\n algorithm (with some speed optimizations). The algorithm was first\n present in [[https://doi.org/10.1145/375663.375670\n Space-efficient Online Computation of Quantile Summaries]]\n by Greenwald and Khanna.\n\n Note that null values will be ignored in numerical columns before calculation.\n For columns only containing null values, an empty list is returned.\n\n :param col: str, list.\n Can be a single column name, or a list of names for multiple columns.\n :param probabilities: a list of quantile probabilities\n Each number must belong to [0, 1].\n For example 0 is the minimum, 0.5 is the median, 1 is the maximum.\n :param relativeError: The relative target precision to achieve\n (>= 0). If set to zero, the exact quantiles are computed, which\n could be very expensive. Note that values greater than 1 are\n accepted but give the same result as 1.\n :return: the approximate quantiles at the given probabilities. If\n the input `col` is a string, the output is a list of floats. If the\n input `col` is a list or tuple of strings, the output is also a\n list, but each element in it is a list of floats, i.e., the output\n is a list of list of floats.\n\n .. versionchanged:: 2.2\n Added support for multiple columns.\n \"\"\"\n\n if not isinstance(col, (basestring, list, tuple)):\n raise ValueError(\"col should be a string, list or tuple, but got %r\" % type(col))\n\n isStr = isinstance(col, basestring)\n\n if isinstance(col, tuple):\n col = list(col)\n elif isStr:\n col = [col]\n\n for c in col:\n if not isinstance(c, basestring):\n raise ValueError(\"columns should be strings, but got %r\" % type(c))\n col = _to_list(self._sc, col)\n\n if not isinstance(probabilities, (list, tuple)):\n raise ValueError(\"probabilities should be a list or tuple\")\n if isinstance(probabilities, tuple):\n probabilities = list(probabilities)\n for p in probabilities:\n if not isinstance(p, (float, int, long)) or p < 0 or p > 1:\n raise ValueError(\"probabilities should be numerical (float, int, long) in [0,1].\")\n probabilities = _to_list(self._sc, probabilities)\n\n if not isinstance(relativeError, (float, int, long)) or relativeError < 0:\n raise ValueError(\"relativeError should be numerical (float, int, long) >= 0.\")\n relativeError = float(relativeError)\n\n jaq = self._jdf.stat().approxQuantile(col, probabilities, relativeError)\n jaq_list = [list(j) for j in jaq]\n return jaq_list[0] if isStr else jaq_list" }, { "instruction": "Write or improve a Python function based on this description:\n\nCalculates the correlation of two columns of a DataFrame as a double value.\n Currently only supports the Pearson Correlation Coefficient.\n :func:`DataFrame.corr` and :func:`DataFrameStatFunctions.corr` are aliases of each other.\n\n :param col1: The name of the first column\n :param col2: The name of the second column\n :param method: The correlation method. Currently only supports \"pearson\"", "output": "def corr(self, col1, col2, method=None):\n \"\"\"\n Calculates the correlation of two columns of a DataFrame as a double value.\n Currently only supports the Pearson Correlation Coefficient.\n :func:`DataFrame.corr` and :func:`DataFrameStatFunctions.corr` are aliases of each other.\n\n :param col1: The name of the first column\n :param col2: The name of the second column\n :param method: The correlation method. Currently only supports \"pearson\"\n \"\"\"\n if not isinstance(col1, basestring):\n raise ValueError(\"col1 should be a string.\")\n if not isinstance(col2, basestring):\n raise ValueError(\"col2 should be a string.\")\n if not method:\n method = \"pearson\"\n if not method == \"pearson\":\n raise ValueError(\"Currently only the calculation of the Pearson Correlation \" +\n \"coefficient is supported.\")\n return self._jdf.stat().corr(col1, col2, method)" }, { "instruction": "Write or improve a Python function based on this description:\n\nCalculate the sample covariance for the given columns, specified by their names, as a\n double value. :func:`DataFrame.cov` and :func:`DataFrameStatFunctions.cov` are aliases.\n\n :param col1: The name of the first column\n :param col2: The name of the second column", "output": "def cov(self, col1, col2):\n \"\"\"\n Calculate the sample covariance for the given columns, specified by their names, as a\n double value. :func:`DataFrame.cov` and :func:`DataFrameStatFunctions.cov` are aliases.\n\n :param col1: The name of the first column\n :param col2: The name of the second column\n \"\"\"\n if not isinstance(col1, basestring):\n raise ValueError(\"col1 should be a string.\")\n if not isinstance(col2, basestring):\n raise ValueError(\"col2 should be a string.\")\n return self._jdf.stat().cov(col1, col2)" }, { "instruction": "Write or improve a Python function based on this description:\n\nComputes a pair-wise frequency table of the given columns. Also known as a contingency\n table. The number of distinct values for each column should be less than 1e4. At most 1e6\n non-zero pair frequencies will be returned.\n The first column of each row will be the distinct values of `col1` and the column names\n will be the distinct values of `col2`. The name of the first column will be `$col1_$col2`.\n Pairs that have no occurrences will have zero as their counts.\n :func:`DataFrame.crosstab` and :func:`DataFrameStatFunctions.crosstab` are aliases.\n\n :param col1: The name of the first column. Distinct items will make the first item of\n each row.\n :param col2: The name of the second column. Distinct items will make the column names\n of the DataFrame.", "output": "def crosstab(self, col1, col2):\n \"\"\"\n Computes a pair-wise frequency table of the given columns. Also known as a contingency\n table. The number of distinct values for each column should be less than 1e4. At most 1e6\n non-zero pair frequencies will be returned.\n The first column of each row will be the distinct values of `col1` and the column names\n will be the distinct values of `col2`. The name of the first column will be `$col1_$col2`.\n Pairs that have no occurrences will have zero as their counts.\n :func:`DataFrame.crosstab` and :func:`DataFrameStatFunctions.crosstab` are aliases.\n\n :param col1: The name of the first column. Distinct items will make the first item of\n each row.\n :param col2: The name of the second column. Distinct items will make the column names\n of the DataFrame.\n \"\"\"\n if not isinstance(col1, basestring):\n raise ValueError(\"col1 should be a string.\")\n if not isinstance(col2, basestring):\n raise ValueError(\"col2 should be a string.\")\n return DataFrame(self._jdf.stat().crosstab(col1, col2), self.sql_ctx)" }, { "instruction": "Write or improve a Python function based on this description:\n\nFinding frequent items for columns, possibly with false positives. Using the\n frequent element count algorithm described in\n \"https://doi.org/10.1145/762471.762473, proposed by Karp, Schenker, and Papadimitriou\".\n :func:`DataFrame.freqItems` and :func:`DataFrameStatFunctions.freqItems` are aliases.\n\n .. note:: This function is meant for exploratory data analysis, as we make no\n guarantee about the backward compatibility of the schema of the resulting DataFrame.\n\n :param cols: Names of the columns to calculate frequent items for as a list or tuple of\n strings.\n :param support: The frequency with which to consider an item 'frequent'. Default is 1%.\n The support must be greater than 1e-4.", "output": "def freqItems(self, cols, support=None):\n \"\"\"\n Finding frequent items for columns, possibly with false positives. Using the\n frequent element count algorithm described in\n \"https://doi.org/10.1145/762471.762473, proposed by Karp, Schenker, and Papadimitriou\".\n :func:`DataFrame.freqItems` and :func:`DataFrameStatFunctions.freqItems` are aliases.\n\n .. note:: This function is meant for exploratory data analysis, as we make no\n guarantee about the backward compatibility of the schema of the resulting DataFrame.\n\n :param cols: Names of the columns to calculate frequent items for as a list or tuple of\n strings.\n :param support: The frequency with which to consider an item 'frequent'. Default is 1%.\n The support must be greater than 1e-4.\n \"\"\"\n if isinstance(cols, tuple):\n cols = list(cols)\n if not isinstance(cols, list):\n raise ValueError(\"cols must be a list or tuple of column names as strings.\")\n if not support:\n support = 0.01\n return DataFrame(self._jdf.stat().freqItems(_to_seq(self._sc, cols), support), self.sql_ctx)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns a new :class:`DataFrame` by adding a column or replacing the\n existing column that has the same name.\n\n The column expression must be an expression over this DataFrame; attempting to add\n a column from some other dataframe will raise an error.\n\n :param colName: string, name of the new column.\n :param col: a :class:`Column` expression for the new column.\n\n .. note:: This method introduces a projection internally. Therefore, calling it multiple\n times, for instance, via loops in order to add multiple columns can generate big\n plans which can cause performance issues and even `StackOverflowException`.\n To avoid this, use :func:`select` with the multiple columns at once.\n\n >>> df.withColumn('age2', df.age + 2).collect()\n [Row(age=2, name=u'Alice', age2=4), Row(age=5, name=u'Bob', age2=7)]", "output": "def withColumn(self, colName, col):\n \"\"\"\n Returns a new :class:`DataFrame` by adding a column or replacing the\n existing column that has the same name.\n\n The column expression must be an expression over this DataFrame; attempting to add\n a column from some other dataframe will raise an error.\n\n :param colName: string, name of the new column.\n :param col: a :class:`Column` expression for the new column.\n\n .. note:: This method introduces a projection internally. Therefore, calling it multiple\n times, for instance, via loops in order to add multiple columns can generate big\n plans which can cause performance issues and even `StackOverflowException`.\n To avoid this, use :func:`select` with the multiple columns at once.\n\n >>> df.withColumn('age2', df.age + 2).collect()\n [Row(age=2, name=u'Alice', age2=4), Row(age=5, name=u'Bob', age2=7)]\n\n \"\"\"\n assert isinstance(col, Column), \"col should be Column\"\n return DataFrame(self._jdf.withColumn(colName, col._jc), self.sql_ctx)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns a new :class:`DataFrame` by renaming an existing column.\n This is a no-op if schema doesn't contain the given column name.\n\n :param existing: string, name of the existing column to rename.\n :param new: string, new name of the column.\n\n >>> df.withColumnRenamed('age', 'age2').collect()\n [Row(age2=2, name=u'Alice'), Row(age2=5, name=u'Bob')]", "output": "def withColumnRenamed(self, existing, new):\n \"\"\"Returns a new :class:`DataFrame` by renaming an existing column.\n This is a no-op if schema doesn't contain the given column name.\n\n :param existing: string, name of the existing column to rename.\n :param new: string, new name of the column.\n\n >>> df.withColumnRenamed('age', 'age2').collect()\n [Row(age2=2, name=u'Alice'), Row(age2=5, name=u'Bob')]\n \"\"\"\n return DataFrame(self._jdf.withColumnRenamed(existing, new), self.sql_ctx)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns a new :class:`DataFrame` that drops the specified column.\n This is a no-op if schema doesn't contain the given column name(s).\n\n :param cols: a string name of the column to drop, or a\n :class:`Column` to drop, or a list of string name of the columns to drop.\n\n >>> df.drop('age').collect()\n [Row(name=u'Alice'), Row(name=u'Bob')]\n\n >>> df.drop(df.age).collect()\n [Row(name=u'Alice'), Row(name=u'Bob')]\n\n >>> df.join(df2, df.name == df2.name, 'inner').drop(df.name).collect()\n [Row(age=5, height=85, name=u'Bob')]\n\n >>> df.join(df2, df.name == df2.name, 'inner').drop(df2.name).collect()\n [Row(age=5, name=u'Bob', height=85)]\n\n >>> df.join(df2, 'name', 'inner').drop('age', 'height').collect()\n [Row(name=u'Bob')]", "output": "def drop(self, *cols):\n \"\"\"Returns a new :class:`DataFrame` that drops the specified column.\n This is a no-op if schema doesn't contain the given column name(s).\n\n :param cols: a string name of the column to drop, or a\n :class:`Column` to drop, or a list of string name of the columns to drop.\n\n >>> df.drop('age').collect()\n [Row(name=u'Alice'), Row(name=u'Bob')]\n\n >>> df.drop(df.age).collect()\n [Row(name=u'Alice'), Row(name=u'Bob')]\n\n >>> df.join(df2, df.name == df2.name, 'inner').drop(df.name).collect()\n [Row(age=5, height=85, name=u'Bob')]\n\n >>> df.join(df2, df.name == df2.name, 'inner').drop(df2.name).collect()\n [Row(age=5, name=u'Bob', height=85)]\n\n >>> df.join(df2, 'name', 'inner').drop('age', 'height').collect()\n [Row(name=u'Bob')]\n \"\"\"\n if len(cols) == 1:\n col = cols[0]\n if isinstance(col, basestring):\n jdf = self._jdf.drop(col)\n elif isinstance(col, Column):\n jdf = self._jdf.drop(col._jc)\n else:\n raise TypeError(\"col should be a string or a Column\")\n else:\n for col in cols:\n if not isinstance(col, basestring):\n raise TypeError(\"each col in the param list should be a string\")\n jdf = self._jdf.drop(self._jseq(cols))\n\n return DataFrame(jdf, self.sql_ctx)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns a new class:`DataFrame` that with new specified column names\n\n :param cols: list of new column names (string)\n\n >>> df.toDF('f1', 'f2').collect()\n [Row(f1=2, f2=u'Alice'), Row(f1=5, f2=u'Bob')]", "output": "def toDF(self, *cols):\n \"\"\"Returns a new class:`DataFrame` that with new specified column names\n\n :param cols: list of new column names (string)\n\n >>> df.toDF('f1', 'f2').collect()\n [Row(f1=2, f2=u'Alice'), Row(f1=5, f2=u'Bob')]\n \"\"\"\n jdf = self._jdf.toDF(self._jseq(cols))\n return DataFrame(jdf, self.sql_ctx)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns a new class:`DataFrame`. Concise syntax for chaining custom transformations.\n\n :param func: a function that takes and returns a class:`DataFrame`.\n\n >>> from pyspark.sql.functions import col\n >>> df = spark.createDataFrame([(1, 1.0), (2, 2.0)], [\"int\", \"float\"])\n >>> def cast_all_to_int(input_df):\n ... return input_df.select([col(col_name).cast(\"int\") for col_name in input_df.columns])\n >>> def sort_columns_asc(input_df):\n ... return input_df.select(*sorted(input_df.columns))\n >>> df.transform(cast_all_to_int).transform(sort_columns_asc).show()\n +-----+---+\n |float|int|\n +-----+---+\n | 1| 1|\n | 2| 2|\n +-----+---+", "output": "def transform(self, func):\n \"\"\"Returns a new class:`DataFrame`. Concise syntax for chaining custom transformations.\n\n :param func: a function that takes and returns a class:`DataFrame`.\n\n >>> from pyspark.sql.functions import col\n >>> df = spark.createDataFrame([(1, 1.0), (2, 2.0)], [\"int\", \"float\"])\n >>> def cast_all_to_int(input_df):\n ... return input_df.select([col(col_name).cast(\"int\") for col_name in input_df.columns])\n >>> def sort_columns_asc(input_df):\n ... return input_df.select(*sorted(input_df.columns))\n >>> df.transform(cast_all_to_int).transform(sort_columns_asc).show()\n +-----+---+\n |float|int|\n +-----+---+\n | 1| 1|\n | 2| 2|\n +-----+---+\n \"\"\"\n result = func(self)\n assert isinstance(result, DataFrame), \"Func returned an instance of type [%s], \" \\\n \"should have been DataFrame.\" % type(result)\n return result" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns the contents of this :class:`DataFrame` as Pandas ``pandas.DataFrame``.\n\n This is only available if Pandas is installed and available.\n\n .. note:: This method should only be used if the resulting Pandas's DataFrame is expected\n to be small, as all the data is loaded into the driver's memory.\n\n .. note:: Usage with spark.sql.execution.arrow.enabled=True is experimental.\n\n >>> df.toPandas() # doctest: +SKIP\n age name\n 0 2 Alice\n 1 5 Bob", "output": "def toPandas(self):\n \"\"\"\n Returns the contents of this :class:`DataFrame` as Pandas ``pandas.DataFrame``.\n\n This is only available if Pandas is installed and available.\n\n .. note:: This method should only be used if the resulting Pandas's DataFrame is expected\n to be small, as all the data is loaded into the driver's memory.\n\n .. note:: Usage with spark.sql.execution.arrow.enabled=True is experimental.\n\n >>> df.toPandas() # doctest: +SKIP\n age name\n 0 2 Alice\n 1 5 Bob\n \"\"\"\n from pyspark.sql.utils import require_minimum_pandas_version\n require_minimum_pandas_version()\n\n import pandas as pd\n\n if self.sql_ctx._conf.pandasRespectSessionTimeZone():\n timezone = self.sql_ctx._conf.sessionLocalTimeZone()\n else:\n timezone = None\n\n if self.sql_ctx._conf.arrowEnabled():\n use_arrow = True\n try:\n from pyspark.sql.types import to_arrow_schema\n from pyspark.sql.utils import require_minimum_pyarrow_version\n\n require_minimum_pyarrow_version()\n to_arrow_schema(self.schema)\n except Exception as e:\n\n if self.sql_ctx._conf.arrowFallbackEnabled():\n msg = (\n \"toPandas attempted Arrow optimization because \"\n \"'spark.sql.execution.arrow.enabled' is set to true; however, \"\n \"failed by the reason below:\\n %s\\n\"\n \"Attempting non-optimization as \"\n \"'spark.sql.execution.arrow.fallback.enabled' is set to \"\n \"true.\" % _exception_message(e))\n warnings.warn(msg)\n use_arrow = False\n else:\n msg = (\n \"toPandas attempted Arrow optimization because \"\n \"'spark.sql.execution.arrow.enabled' is set to true, but has reached \"\n \"the error below and will not continue because automatic fallback \"\n \"with 'spark.sql.execution.arrow.fallback.enabled' has been set to \"\n \"false.\\n %s\" % _exception_message(e))\n warnings.warn(msg)\n raise\n\n # Try to use Arrow optimization when the schema is supported and the required version\n # of PyArrow is found, if 'spark.sql.execution.arrow.enabled' is enabled.\n if use_arrow:\n try:\n from pyspark.sql.types import _check_dataframe_localize_timestamps\n import pyarrow\n batches = self._collectAsArrow()\n if len(batches) > 0:\n table = pyarrow.Table.from_batches(batches)\n # Pandas DataFrame created from PyArrow uses datetime64[ns] for date type\n # values, but we should use datetime.date to match the behavior with when\n # Arrow optimization is disabled.\n pdf = table.to_pandas(date_as_object=True)\n return _check_dataframe_localize_timestamps(pdf, timezone)\n else:\n return pd.DataFrame.from_records([], columns=self.columns)\n except Exception as e:\n # We might have to allow fallback here as well but multiple Spark jobs can\n # be executed. So, simply fail in this case for now.\n msg = (\n \"toPandas attempted Arrow optimization because \"\n \"'spark.sql.execution.arrow.enabled' is set to true, but has reached \"\n \"the error below and can not continue. Note that \"\n \"'spark.sql.execution.arrow.fallback.enabled' does not have an effect \"\n \"on failures in the middle of computation.\\n %s\" % _exception_message(e))\n warnings.warn(msg)\n raise\n\n # Below is toPandas without Arrow optimization.\n pdf = pd.DataFrame.from_records(self.collect(), columns=self.columns)\n\n dtype = {}\n for field in self.schema:\n pandas_type = _to_corrected_pandas_type(field.dataType)\n # SPARK-21766: if an integer field is nullable and has null values, it can be\n # inferred by pandas as float column. Once we convert the column with NaN back\n # to integer type e.g., np.int16, we will hit exception. So we use the inferred\n # float type, not the corrected type from the schema in this case.\n if pandas_type is not None and \\\n not(isinstance(field.dataType, IntegralType) and field.nullable and\n pdf[field.name].isnull().any()):\n dtype[field.name] = pandas_type\n\n for f, t in dtype.items():\n pdf[f] = pdf[f].astype(t, copy=False)\n\n if timezone is None:\n return pdf\n else:\n from pyspark.sql.types import _check_series_convert_timestamps_local_tz\n for field in self.schema:\n # TODO: handle nested timestamps, such as ArrayType(TimestampType())?\n if isinstance(field.dataType, TimestampType):\n pdf[field.name] = \\\n _check_series_convert_timestamps_local_tz(pdf[field.name], timezone)\n return pdf" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns all records as a list of ArrowRecordBatches, pyarrow must be installed\n and available on driver and worker Python environments.\n\n .. note:: Experimental.", "output": "def _collectAsArrow(self):\n \"\"\"\n Returns all records as a list of ArrowRecordBatches, pyarrow must be installed\n and available on driver and worker Python environments.\n\n .. note:: Experimental.\n \"\"\"\n with SCCallSiteSync(self._sc) as css:\n sock_info = self._jdf.collectAsArrowToPython()\n\n # Collect list of un-ordered batches where last element is a list of correct order indices\n results = list(_load_from_socket(sock_info, ArrowCollectSerializer()))\n batches = results[:-1]\n batch_order = results[-1]\n\n # Re-order the batch list using the correct order\n return [batches[i] for i in batch_order]" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns the :class:`StatCounter` members as a ``dict``.\n\n >>> sc.parallelize([1., 2., 3., 4.]).stats().asDict()\n {'count': 4L,\n 'max': 4.0,\n 'mean': 2.5,\n 'min': 1.0,\n 'stdev': 1.2909944487358056,\n 'sum': 10.0,\n 'variance': 1.6666666666666667}", "output": "def asDict(self, sample=False):\n \"\"\"Returns the :class:`StatCounter` members as a ``dict``.\n\n >>> sc.parallelize([1., 2., 3., 4.]).stats().asDict()\n {'count': 4L,\n 'max': 4.0,\n 'mean': 2.5,\n 'min': 1.0,\n 'stdev': 1.2909944487358056,\n 'sum': 10.0,\n 'variance': 1.6666666666666667}\n \"\"\"\n return {\n 'count': self.count(),\n 'mean': self.mean(),\n 'sum': self.sum(),\n 'min': self.min(),\n 'max': self.max(),\n 'stdev': self.stdev() if sample else self.sampleStdev(),\n 'variance': self.variance() if sample else self.sampleVariance()\n }" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns a list of function information via JVM. Sorts wrapped expression infos by name\n and returns them.", "output": "def _list_function_infos(jvm):\n \"\"\"\n Returns a list of function information via JVM. Sorts wrapped expression infos by name\n and returns them.\n \"\"\"\n\n jinfos = jvm.org.apache.spark.sql.api.python.PythonSQLUtils.listBuiltinFunctionInfos()\n infos = []\n for jinfo in jinfos:\n name = jinfo.getName()\n usage = jinfo.getUsage()\n usage = usage.replace(\"_FUNC_\", name) if usage is not None else usage\n infos.append(ExpressionInfo(\n className=jinfo.getClassName(),\n name=name,\n usage=usage,\n arguments=jinfo.getArguments().replace(\"_FUNC_\", name),\n examples=jinfo.getExamples().replace(\"_FUNC_\", name),\n note=jinfo.getNote(),\n since=jinfo.getSince(),\n deprecated=jinfo.getDeprecated()))\n return sorted(infos, key=lambda i: i.name)" }, { "instruction": "Write or improve a Python function based on this description:\n\nMakes the usage description pretty and returns a formatted string if `usage`\n is not an empty string. Otherwise, returns None.", "output": "def _make_pretty_usage(usage):\n \"\"\"\n Makes the usage description pretty and returns a formatted string if `usage`\n is not an empty string. Otherwise, returns None.\n \"\"\"\n\n if usage is not None and usage.strip() != \"\":\n usage = \"\\n\".join(map(lambda u: u.strip(), usage.split(\"\\n\")))\n return \"%s\\n\\n\" % usage" }, { "instruction": "Write or improve a Python function based on this description:\n\nMakes the arguments description pretty and returns a formatted string if `arguments`\n starts with the argument prefix. Otherwise, returns None.\n\n Expected input:\n\n Arguments:\n * arg0 - ...\n ...\n * arg0 - ...\n ...\n\n Expected output:\n **Arguments:**\n\n * arg0 - ...\n ...\n * arg0 - ...\n ...", "output": "def _make_pretty_arguments(arguments):\n \"\"\"\n Makes the arguments description pretty and returns a formatted string if `arguments`\n starts with the argument prefix. Otherwise, returns None.\n\n Expected input:\n\n Arguments:\n * arg0 - ...\n ...\n * arg0 - ...\n ...\n\n Expected output:\n **Arguments:**\n\n * arg0 - ...\n ...\n * arg0 - ...\n ...\n\n \"\"\"\n\n if arguments.startswith(\"\\n Arguments:\"):\n arguments = \"\\n\".join(map(lambda u: u[6:], arguments.strip().split(\"\\n\")[1:]))\n return \"**Arguments:**\\n\\n%s\\n\\n\" % arguments" }, { "instruction": "Write or improve a Python function based on this description:\n\nMakes the examples description pretty and returns a formatted string if `examples`\n starts with the example prefix. Otherwise, returns None.\n\n Expected input:\n\n Examples:\n > SELECT ...;\n ...\n > SELECT ...;\n ...\n\n Expected output:\n **Examples:**\n\n ```\n > SELECT ...;\n ...\n > SELECT ...;\n ...\n ```", "output": "def _make_pretty_examples(examples):\n \"\"\"\n Makes the examples description pretty and returns a formatted string if `examples`\n starts with the example prefix. Otherwise, returns None.\n\n Expected input:\n\n Examples:\n > SELECT ...;\n ...\n > SELECT ...;\n ...\n\n Expected output:\n **Examples:**\n\n ```\n > SELECT ...;\n ...\n > SELECT ...;\n ...\n ```\n\n \"\"\"\n\n if examples.startswith(\"\\n Examples:\"):\n examples = \"\\n\".join(map(lambda u: u[6:], examples.strip().split(\"\\n\")[1:]))\n return \"**Examples:**\\n\\n```\\n%s\\n```\\n\\n\" % examples" }, { "instruction": "Write or improve a Python function based on this description:\n\nMakes the note description pretty and returns a formatted string if `note` is not\n an empty string. Otherwise, returns None.\n\n Expected input:\n\n ...\n\n Expected output:\n **Note:**\n\n ...", "output": "def _make_pretty_note(note):\n \"\"\"\n Makes the note description pretty and returns a formatted string if `note` is not\n an empty string. Otherwise, returns None.\n\n Expected input:\n\n ...\n\n Expected output:\n **Note:**\n\n ...\n\n \"\"\"\n\n if note != \"\":\n note = \"\\n\".join(map(lambda n: n[4:], note.split(\"\\n\")))\n return \"**Note:**\\n%s\\n\" % note" }, { "instruction": "Write or improve a Python function based on this description:\n\nMakes the deprecated description pretty and returns a formatted string if `deprecated`\n is not an empty string. Otherwise, returns None.\n\n Expected input:\n\n ...\n\n Expected output:\n **Deprecated:**\n\n ...", "output": "def _make_pretty_deprecated(deprecated):\n \"\"\"\n Makes the deprecated description pretty and returns a formatted string if `deprecated`\n is not an empty string. Otherwise, returns None.\n\n Expected input:\n\n ...\n\n Expected output:\n **Deprecated:**\n\n ...\n\n \"\"\"\n\n if deprecated != \"\":\n deprecated = \"\\n\".join(map(lambda n: n[4:], deprecated.split(\"\\n\")))\n return \"**Deprecated:**\\n%s\\n\" % deprecated" }, { "instruction": "Write or improve a Python function based on this description:\n\nGenerates a markdown file after listing the function information. The output file\n is created in `path`.\n\n Expected output:\n ### NAME\n\n USAGE\n\n **Arguments:**\n\n ARGUMENTS\n\n **Examples:**\n\n ```\n EXAMPLES\n ```\n\n **Note:**\n\n NOTE\n\n **Since:** SINCE\n\n **Deprecated:**\n\n DEPRECATED\n\n
", "output": "def generate_sql_markdown(jvm, path):\n \"\"\"\n Generates a markdown file after listing the function information. The output file\n is created in `path`.\n\n Expected output:\n ### NAME\n\n USAGE\n\n **Arguments:**\n\n ARGUMENTS\n\n **Examples:**\n\n ```\n EXAMPLES\n ```\n\n **Note:**\n\n NOTE\n\n **Since:** SINCE\n\n **Deprecated:**\n\n DEPRECATED\n\n
\n\n \"\"\"\n\n with open(path, 'w') as mdfile:\n for info in _list_function_infos(jvm):\n name = info.name\n usage = _make_pretty_usage(info.usage)\n arguments = _make_pretty_arguments(info.arguments)\n examples = _make_pretty_examples(info.examples)\n note = _make_pretty_note(info.note)\n since = info.since\n deprecated = _make_pretty_deprecated(info.deprecated)\n\n mdfile.write(\"### %s\\n\\n\" % name)\n if usage is not None:\n mdfile.write(\"%s\\n\\n\" % usage.strip())\n if arguments is not None:\n mdfile.write(arguments)\n if examples is not None:\n mdfile.write(examples)\n if note is not None:\n mdfile.write(note)\n if since is not None and since != \"\":\n mdfile.write(\"**Since:** %s\\n\\n\" % since.strip())\n if deprecated is not None:\n mdfile.write(deprecated)\n mdfile.write(\"
\\n\\n\")" }, { "instruction": "Write or improve a Python function based on this description:\n\nPredict values for a single data point or an RDD of points\n using the model trained.", "output": "def predict(self, x):\n \"\"\"\n Predict values for a single data point or an RDD of points\n using the model trained.\n \"\"\"\n if isinstance(x, RDD):\n return x.map(lambda v: self.predict(v))\n\n x = _convert_to_vector(x)\n if self.numClasses == 2:\n margin = self.weights.dot(x) + self._intercept\n if margin > 0:\n prob = 1 / (1 + exp(-margin))\n else:\n exp_margin = exp(margin)\n prob = exp_margin / (1 + exp_margin)\n if self._threshold is None:\n return prob\n else:\n return 1 if prob > self._threshold else 0\n else:\n best_class = 0\n max_margin = 0.0\n if x.size + 1 == self._dataWithBiasSize:\n for i in range(0, self._numClasses - 1):\n margin = x.dot(self._weightsMatrix[i][0:x.size]) + \\\n self._weightsMatrix[i][x.size]\n if margin > max_margin:\n max_margin = margin\n best_class = i + 1\n else:\n for i in range(0, self._numClasses - 1):\n margin = x.dot(self._weightsMatrix[i])\n if margin > max_margin:\n max_margin = margin\n best_class = i + 1\n return best_class" }, { "instruction": "Write or improve a Python function based on this description:\n\nSave this model to the given path.", "output": "def save(self, sc, path):\n \"\"\"\n Save this model to the given path.\n \"\"\"\n java_model = sc._jvm.org.apache.spark.mllib.classification.LogisticRegressionModel(\n _py2java(sc, self._coeff), self.intercept, self.numFeatures, self.numClasses)\n java_model.save(sc._jsc.sc(), path)" }, { "instruction": "Write or improve a Python function based on this description:\n\nTrain a logistic regression model on the given data.\n\n :param data:\n The training data, an RDD of LabeledPoint.\n :param iterations:\n The number of iterations.\n (default: 100)\n :param initialWeights:\n The initial weights.\n (default: None)\n :param regParam:\n The regularizer parameter.\n (default: 0.0)\n :param regType:\n The type of regularizer used for training our model.\n Supported values:\n\n - \"l1\" for using L1 regularization\n - \"l2\" for using L2 regularization (default)\n - None for no regularization\n :param intercept:\n Boolean parameter which indicates the use or not of the\n augmented representation for training data (i.e., whether bias\n features are activated or not).\n (default: False)\n :param corrections:\n The number of corrections used in the LBFGS update.\n If a known updater is used for binary classification,\n it calls the ml implementation and this parameter will\n have no effect. (default: 10)\n :param tolerance:\n The convergence tolerance of iterations for L-BFGS.\n (default: 1e-6)\n :param validateData:\n Boolean parameter which indicates if the algorithm should\n validate data before training.\n (default: True)\n :param numClasses:\n The number of classes (i.e., outcomes) a label can take in\n Multinomial Logistic Regression.\n (default: 2)\n\n >>> data = [\n ... LabeledPoint(0.0, [0.0, 1.0]),\n ... LabeledPoint(1.0, [1.0, 0.0]),\n ... ]\n >>> lrm = LogisticRegressionWithLBFGS.train(sc.parallelize(data), iterations=10)\n >>> lrm.predict([1.0, 0.0])\n 1\n >>> lrm.predict([0.0, 1.0])\n 0", "output": "def train(cls, data, iterations=100, initialWeights=None, regParam=0.0, regType=\"l2\",\n intercept=False, corrections=10, tolerance=1e-6, validateData=True, numClasses=2):\n \"\"\"\n Train a logistic regression model on the given data.\n\n :param data:\n The training data, an RDD of LabeledPoint.\n :param iterations:\n The number of iterations.\n (default: 100)\n :param initialWeights:\n The initial weights.\n (default: None)\n :param regParam:\n The regularizer parameter.\n (default: 0.0)\n :param regType:\n The type of regularizer used for training our model.\n Supported values:\n\n - \"l1\" for using L1 regularization\n - \"l2\" for using L2 regularization (default)\n - None for no regularization\n :param intercept:\n Boolean parameter which indicates the use or not of the\n augmented representation for training data (i.e., whether bias\n features are activated or not).\n (default: False)\n :param corrections:\n The number of corrections used in the LBFGS update.\n If a known updater is used for binary classification,\n it calls the ml implementation and this parameter will\n have no effect. (default: 10)\n :param tolerance:\n The convergence tolerance of iterations for L-BFGS.\n (default: 1e-6)\n :param validateData:\n Boolean parameter which indicates if the algorithm should\n validate data before training.\n (default: True)\n :param numClasses:\n The number of classes (i.e., outcomes) a label can take in\n Multinomial Logistic Regression.\n (default: 2)\n\n >>> data = [\n ... LabeledPoint(0.0, [0.0, 1.0]),\n ... LabeledPoint(1.0, [1.0, 0.0]),\n ... ]\n >>> lrm = LogisticRegressionWithLBFGS.train(sc.parallelize(data), iterations=10)\n >>> lrm.predict([1.0, 0.0])\n 1\n >>> lrm.predict([0.0, 1.0])\n 0\n \"\"\"\n def train(rdd, i):\n return callMLlibFunc(\"trainLogisticRegressionModelWithLBFGS\", rdd, int(iterations), i,\n float(regParam), regType, bool(intercept), int(corrections),\n float(tolerance), bool(validateData), int(numClasses))\n\n if initialWeights is None:\n if numClasses == 2:\n initialWeights = [0.0] * len(data.first().features)\n else:\n if intercept:\n initialWeights = [0.0] * (len(data.first().features) + 1) * (numClasses - 1)\n else:\n initialWeights = [0.0] * len(data.first().features) * (numClasses - 1)\n return _regression_train_wrapper(train, LogisticRegressionModel, data, initialWeights)" }, { "instruction": "Write or improve a Python function based on this description:\n\nPredict values for a single data point or an RDD of points\n using the model trained.", "output": "def predict(self, x):\n \"\"\"\n Predict values for a single data point or an RDD of points\n using the model trained.\n \"\"\"\n if isinstance(x, RDD):\n return x.map(lambda v: self.predict(v))\n\n x = _convert_to_vector(x)\n margin = self.weights.dot(x) + self.intercept\n if self._threshold is None:\n return margin\n else:\n return 1 if margin > self._threshold else 0" }, { "instruction": "Write or improve a Python function based on this description:\n\nSave this model to the given path.", "output": "def save(self, sc, path):\n \"\"\"\n Save this model to the given path.\n \"\"\"\n java_model = sc._jvm.org.apache.spark.mllib.classification.SVMModel(\n _py2java(sc, self._coeff), self.intercept)\n java_model.save(sc._jsc.sc(), path)" }, { "instruction": "Write or improve a Python function based on this description:\n\nLoad a model from the given path.", "output": "def load(cls, sc, path):\n \"\"\"\n Load a model from the given path.\n \"\"\"\n java_model = sc._jvm.org.apache.spark.mllib.classification.SVMModel.load(\n sc._jsc.sc(), path)\n weights = _java2py(sc, java_model.weights())\n intercept = java_model.intercept()\n threshold = java_model.getThreshold().get()\n model = SVMModel(weights, intercept)\n model.setThreshold(threshold)\n return model" }, { "instruction": "Write or improve a Python function based on this description:\n\nTrain a Naive Bayes model given an RDD of (label, features)\n vectors.\n\n This is the Multinomial NB (U{http://tinyurl.com/lsdw6p}) which\n can handle all kinds of discrete data. For example, by\n converting documents into TF-IDF vectors, it can be used for\n document classification. By making every vector a 0-1 vector,\n it can also be used as Bernoulli NB (U{http://tinyurl.com/p7c96j6}).\n The input feature values must be nonnegative.\n\n :param data:\n RDD of LabeledPoint.\n :param lambda_:\n The smoothing parameter.\n (default: 1.0)", "output": "def train(cls, data, lambda_=1.0):\n \"\"\"\n Train a Naive Bayes model given an RDD of (label, features)\n vectors.\n\n This is the Multinomial NB (U{http://tinyurl.com/lsdw6p}) which\n can handle all kinds of discrete data. For example, by\n converting documents into TF-IDF vectors, it can be used for\n document classification. By making every vector a 0-1 vector,\n it can also be used as Bernoulli NB (U{http://tinyurl.com/p7c96j6}).\n The input feature values must be nonnegative.\n\n :param data:\n RDD of LabeledPoint.\n :param lambda_:\n The smoothing parameter.\n (default: 1.0)\n \"\"\"\n first = data.first()\n if not isinstance(first, LabeledPoint):\n raise ValueError(\"`data` should be an RDD of LabeledPoint\")\n labels, pi, theta = callMLlibFunc(\"trainNaiveBayesModel\", data, lambda_)\n return NaiveBayesModel(labels.toArray(), pi.toArray(), numpy.array(theta))" }, { "instruction": "Write or improve a Python function based on this description:\n\nPush item onto heap, maintaining the heap invariant.", "output": "def heappush(heap, item):\n \"\"\"Push item onto heap, maintaining the heap invariant.\"\"\"\n heap.append(item)\n _siftdown(heap, 0, len(heap)-1)" }, { "instruction": "Write or improve a Python function based on this description:\n\nPop the smallest item off the heap, maintaining the heap invariant.", "output": "def heappop(heap):\n \"\"\"Pop the smallest item off the heap, maintaining the heap invariant.\"\"\"\n lastelt = heap.pop() # raises appropriate IndexError if heap is empty\n if heap:\n returnitem = heap[0]\n heap[0] = lastelt\n _siftup(heap, 0)\n return returnitem\n return lastelt" }, { "instruction": "Write or improve a Python function based on this description:\n\nPop and return the current smallest value, and add the new item.\n\n This is more efficient than heappop() followed by heappush(), and can be\n more appropriate when using a fixed-size heap. Note that the value\n returned may be larger than item! That constrains reasonable uses of\n this routine unless written as part of a conditional replacement:\n\n if item > heap[0]:\n item = heapreplace(heap, item)", "output": "def heapreplace(heap, item):\n \"\"\"Pop and return the current smallest value, and add the new item.\n\n This is more efficient than heappop() followed by heappush(), and can be\n more appropriate when using a fixed-size heap. Note that the value\n returned may be larger than item! That constrains reasonable uses of\n this routine unless written as part of a conditional replacement:\n\n if item > heap[0]:\n item = heapreplace(heap, item)\n \"\"\"\n returnitem = heap[0] # raises appropriate IndexError if heap is empty\n heap[0] = item\n _siftup(heap, 0)\n return returnitem" }, { "instruction": "Write or improve a Python function based on this description:\n\nFast version of a heappush followed by a heappop.", "output": "def heappushpop(heap, item):\n \"\"\"Fast version of a heappush followed by a heappop.\"\"\"\n if heap and heap[0] < item:\n item, heap[0] = heap[0], item\n _siftup(heap, 0)\n return item" }, { "instruction": "Write or improve a Python function based on this description:\n\nTransform list into a heap, in-place, in O(len(x)) time.", "output": "def heapify(x):\n \"\"\"Transform list into a heap, in-place, in O(len(x)) time.\"\"\"\n n = len(x)\n # Transform bottom-up. The largest index there's any point to looking at\n # is the largest with a child index in-range, so must have 2*i + 1 < n,\n # or i < (n-1)/2. If n is even = 2*j, this is (2*j-1)/2 = j-1/2 so\n # j-1 is the largest, which is n//2 - 1. If n is odd = 2*j+1, this is\n # (2*j+1-1)/2 = j so j-1 is the largest, and that's again n//2-1.\n for i in reversed(range(n//2)):\n _siftup(x, i)" }, { "instruction": "Write or improve a Python function based on this description:\n\nMaxheap version of a heappop.", "output": "def _heappop_max(heap):\n \"\"\"Maxheap version of a heappop.\"\"\"\n lastelt = heap.pop() # raises appropriate IndexError if heap is empty\n if heap:\n returnitem = heap[0]\n heap[0] = lastelt\n _siftup_max(heap, 0)\n return returnitem\n return lastelt" }, { "instruction": "Write or improve a Python function based on this description:\n\nMaxheap version of a heappop followed by a heappush.", "output": "def _heapreplace_max(heap, item):\n \"\"\"Maxheap version of a heappop followed by a heappush.\"\"\"\n returnitem = heap[0] # raises appropriate IndexError if heap is empty\n heap[0] = item\n _siftup_max(heap, 0)\n return returnitem" }, { "instruction": "Write or improve a Python function based on this description:\n\nTransform list into a maxheap, in-place, in O(len(x)) time.", "output": "def _heapify_max(x):\n \"\"\"Transform list into a maxheap, in-place, in O(len(x)) time.\"\"\"\n n = len(x)\n for i in reversed(range(n//2)):\n _siftup_max(x, i)" }, { "instruction": "Write or improve a Python function based on this description:\n\nMaxheap variant of _siftdown", "output": "def _siftdown_max(heap, startpos, pos):\n 'Maxheap variant of _siftdown'\n newitem = heap[pos]\n # Follow the path to the root, moving parents down until finding a place\n # newitem fits.\n while pos > startpos:\n parentpos = (pos - 1) >> 1\n parent = heap[parentpos]\n if parent < newitem:\n heap[pos] = parent\n pos = parentpos\n continue\n break\n heap[pos] = newitem" }, { "instruction": "Write or improve a Python function based on this description:\n\nMaxheap variant of _siftup", "output": "def _siftup_max(heap, pos):\n 'Maxheap variant of _siftup'\n endpos = len(heap)\n startpos = pos\n newitem = heap[pos]\n # Bubble up the larger child until hitting a leaf.\n childpos = 2*pos + 1 # leftmost child position\n while childpos < endpos:\n # Set childpos to index of larger child.\n rightpos = childpos + 1\n if rightpos < endpos and not heap[rightpos] < heap[childpos]:\n childpos = rightpos\n # Move the larger child up.\n heap[pos] = heap[childpos]\n pos = childpos\n childpos = 2*pos + 1\n # The leaf at pos is empty now. Put newitem there, and bubble it up\n # to its final resting place (by sifting its parents down).\n heap[pos] = newitem\n _siftdown_max(heap, startpos, pos)" }, { "instruction": "Write or improve a Python function based on this description:\n\nMerge multiple sorted inputs into a single sorted output.\n\n Similar to sorted(itertools.chain(*iterables)) but returns a generator,\n does not pull the data into memory all at once, and assumes that each of\n the input streams is already sorted (smallest to largest).\n\n >>> list(merge([1,3,5,7], [0,2,4,8], [5,10,15,20], [], [25]))\n [0, 1, 2, 3, 4, 5, 5, 7, 8, 10, 15, 20, 25]\n\n If *key* is not None, applies a key function to each element to determine\n its sort order.\n\n >>> list(merge(['dog', 'horse'], ['cat', 'fish', 'kangaroo'], key=len))\n ['dog', 'cat', 'fish', 'horse', 'kangaroo']", "output": "def merge(iterables, key=None, reverse=False):\n '''Merge multiple sorted inputs into a single sorted output.\n\n Similar to sorted(itertools.chain(*iterables)) but returns a generator,\n does not pull the data into memory all at once, and assumes that each of\n the input streams is already sorted (smallest to largest).\n\n >>> list(merge([1,3,5,7], [0,2,4,8], [5,10,15,20], [], [25]))\n [0, 1, 2, 3, 4, 5, 5, 7, 8, 10, 15, 20, 25]\n\n If *key* is not None, applies a key function to each element to determine\n its sort order.\n\n >>> list(merge(['dog', 'horse'], ['cat', 'fish', 'kangaroo'], key=len))\n ['dog', 'cat', 'fish', 'horse', 'kangaroo']\n\n '''\n\n h = []\n h_append = h.append\n\n if reverse:\n _heapify = _heapify_max\n _heappop = _heappop_max\n _heapreplace = _heapreplace_max\n direction = -1\n else:\n _heapify = heapify\n _heappop = heappop\n _heapreplace = heapreplace\n direction = 1\n\n if key is None:\n for order, it in enumerate(map(iter, iterables)):\n try:\n h_append([next(it), order * direction, it])\n except StopIteration:\n pass\n _heapify(h)\n while len(h) > 1:\n try:\n while True:\n value, order, it = s = h[0]\n yield value\n s[0] = next(it) # raises StopIteration when exhausted\n _heapreplace(h, s) # restore heap condition\n except StopIteration:\n _heappop(h) # remove empty iterator\n if h:\n # fast case when only a single iterator remains\n value, order, it = h[0]\n yield value\n for value in it:\n yield value\n return\n\n for order, it in enumerate(map(iter, iterables)):\n try:\n value = next(it)\n h_append([key(value), order * direction, value, it])\n except StopIteration:\n pass\n _heapify(h)\n while len(h) > 1:\n try:\n while True:\n key_value, order, value, it = s = h[0]\n yield value\n value = next(it)\n s[0] = key(value)\n s[2] = value\n _heapreplace(h, s)\n except StopIteration:\n _heappop(h)\n if h:\n key_value, order, value, it = h[0]\n yield value\n for value in it:\n yield value" }, { "instruction": "Write or improve a Python function based on this description:\n\nFind the n smallest elements in a dataset.\n\n Equivalent to: sorted(iterable, key=key)[:n]", "output": "def nsmallest(n, iterable, key=None):\n \"\"\"Find the n smallest elements in a dataset.\n\n Equivalent to: sorted(iterable, key=key)[:n]\n \"\"\"\n\n # Short-cut for n==1 is to use min()\n if n == 1:\n it = iter(iterable)\n sentinel = object()\n if key is None:\n result = min(it, default=sentinel)\n else:\n result = min(it, default=sentinel, key=key)\n return [] if result is sentinel else [result]\n\n # When n>=size, it's faster to use sorted()\n try:\n size = len(iterable)\n except (TypeError, AttributeError):\n pass\n else:\n if n >= size:\n return sorted(iterable, key=key)[:n]\n\n # When key is none, use simpler decoration\n if key is None:\n it = iter(iterable)\n # put the range(n) first so that zip() doesn't\n # consume one too many elements from the iterator\n result = [(elem, i) for i, elem in zip(range(n), it)]\n if not result:\n return result\n _heapify_max(result)\n top = result[0][0]\n order = n\n _heapreplace = _heapreplace_max\n for elem in it:\n if elem < top:\n _heapreplace(result, (elem, order))\n top = result[0][0]\n order += 1\n result.sort()\n return [r[0] for r in result]\n\n # General case, slowest method\n it = iter(iterable)\n result = [(key(elem), i, elem) for i, elem in zip(range(n), it)]\n if not result:\n return result\n _heapify_max(result)\n top = result[0][0]\n order = n\n _heapreplace = _heapreplace_max\n for elem in it:\n k = key(elem)\n if k < top:\n _heapreplace(result, (k, order, elem))\n top = result[0][0]\n order += 1\n result.sort()\n return [r[2] for r in result]" }, { "instruction": "Write or improve a Python function based on this description:\n\nFind the n largest elements in a dataset.\n\n Equivalent to: sorted(iterable, key=key, reverse=True)[:n]", "output": "def nlargest(n, iterable, key=None):\n \"\"\"Find the n largest elements in a dataset.\n\n Equivalent to: sorted(iterable, key=key, reverse=True)[:n]\n \"\"\"\n\n # Short-cut for n==1 is to use max()\n if n == 1:\n it = iter(iterable)\n sentinel = object()\n if key is None:\n result = max(it, default=sentinel)\n else:\n result = max(it, default=sentinel, key=key)\n return [] if result is sentinel else [result]\n\n # When n>=size, it's faster to use sorted()\n try:\n size = len(iterable)\n except (TypeError, AttributeError):\n pass\n else:\n if n >= size:\n return sorted(iterable, key=key, reverse=True)[:n]\n\n # When key is none, use simpler decoration\n if key is None:\n it = iter(iterable)\n result = [(elem, i) for i, elem in zip(range(0, -n, -1), it)]\n if not result:\n return result\n heapify(result)\n top = result[0][0]\n order = -n\n _heapreplace = heapreplace\n for elem in it:\n if top < elem:\n _heapreplace(result, (elem, order))\n top = result[0][0]\n order -= 1\n result.sort(reverse=True)\n return [r[0] for r in result]\n\n # General case, slowest method\n it = iter(iterable)\n result = [(key(elem), i, elem) for i, elem in zip(range(0, -n, -1), it)]\n if not result:\n return result\n heapify(result)\n top = result[0][0]\n order = -n\n _heapreplace = heapreplace\n for elem in it:\n k = key(elem)\n if top < k:\n _heapreplace(result, (k, order, elem))\n top = result[0][0]\n order -= 1\n result.sort(reverse=True)\n return [r[2] for r in result]" }, { "instruction": "Write or improve a Python function based on this description:\n\nCompute the correlation matrix with specified method using dataset.\n\n :param dataset:\n A Dataset or a DataFrame.\n :param column:\n The name of the column of vectors for which the correlation coefficient needs\n to be computed. This must be a column of the dataset, and it must contain\n Vector objects.\n :param method:\n String specifying the method to use for computing correlation.\n Supported: `pearson` (default), `spearman`.\n :return:\n A DataFrame that contains the correlation matrix of the column of vectors. This\n DataFrame contains a single row and a single column of name\n '$METHODNAME($COLUMN)'.\n\n >>> from pyspark.ml.linalg import Vectors\n >>> from pyspark.ml.stat import Correlation\n >>> dataset = [[Vectors.dense([1, 0, 0, -2])],\n ... [Vectors.dense([4, 5, 0, 3])],\n ... [Vectors.dense([6, 7, 0, 8])],\n ... [Vectors.dense([9, 0, 0, 1])]]\n >>> dataset = spark.createDataFrame(dataset, ['features'])\n >>> pearsonCorr = Correlation.corr(dataset, 'features', 'pearson').collect()[0][0]\n >>> print(str(pearsonCorr).replace('nan', 'NaN'))\n DenseMatrix([[ 1. , 0.0556..., NaN, 0.4004...],\n [ 0.0556..., 1. , NaN, 0.9135...],\n [ NaN, NaN, 1. , NaN],\n [ 0.4004..., 0.9135..., NaN, 1. ]])\n >>> spearmanCorr = Correlation.corr(dataset, 'features', method='spearman').collect()[0][0]\n >>> print(str(spearmanCorr).replace('nan', 'NaN'))\n DenseMatrix([[ 1. , 0.1054..., NaN, 0.4 ],\n [ 0.1054..., 1. , NaN, 0.9486... ],\n [ NaN, NaN, 1. , NaN],\n [ 0.4 , 0.9486... , NaN, 1. ]])", "output": "def corr(dataset, column, method=\"pearson\"):\n \"\"\"\n Compute the correlation matrix with specified method using dataset.\n\n :param dataset:\n A Dataset or a DataFrame.\n :param column:\n The name of the column of vectors for which the correlation coefficient needs\n to be computed. This must be a column of the dataset, and it must contain\n Vector objects.\n :param method:\n String specifying the method to use for computing correlation.\n Supported: `pearson` (default), `spearman`.\n :return:\n A DataFrame that contains the correlation matrix of the column of vectors. This\n DataFrame contains a single row and a single column of name\n '$METHODNAME($COLUMN)'.\n\n >>> from pyspark.ml.linalg import Vectors\n >>> from pyspark.ml.stat import Correlation\n >>> dataset = [[Vectors.dense([1, 0, 0, -2])],\n ... [Vectors.dense([4, 5, 0, 3])],\n ... [Vectors.dense([6, 7, 0, 8])],\n ... [Vectors.dense([9, 0, 0, 1])]]\n >>> dataset = spark.createDataFrame(dataset, ['features'])\n >>> pearsonCorr = Correlation.corr(dataset, 'features', 'pearson').collect()[0][0]\n >>> print(str(pearsonCorr).replace('nan', 'NaN'))\n DenseMatrix([[ 1. , 0.0556..., NaN, 0.4004...],\n [ 0.0556..., 1. , NaN, 0.9135...],\n [ NaN, NaN, 1. , NaN],\n [ 0.4004..., 0.9135..., NaN, 1. ]])\n >>> spearmanCorr = Correlation.corr(dataset, 'features', method='spearman').collect()[0][0]\n >>> print(str(spearmanCorr).replace('nan', 'NaN'))\n DenseMatrix([[ 1. , 0.1054..., NaN, 0.4 ],\n [ 0.1054..., 1. , NaN, 0.9486... ],\n [ NaN, NaN, 1. , NaN],\n [ 0.4 , 0.9486... , NaN, 1. ]])\n \"\"\"\n sc = SparkContext._active_spark_context\n javaCorrObj = _jvm().org.apache.spark.ml.stat.Correlation\n args = [_py2java(sc, arg) for arg in (dataset, column, method)]\n return _java2py(sc, javaCorrObj.corr(*args))" }, { "instruction": "Write or improve a Python function based on this description:\n\nGiven a list of metrics, provides a builder that it turns computes metrics from a column.\n\n See the documentation of [[Summarizer]] for an example.\n\n The following metrics are accepted (case sensitive):\n - mean: a vector that contains the coefficient-wise mean.\n - variance: a vector tha contains the coefficient-wise variance.\n - count: the count of all vectors seen.\n - numNonzeros: a vector with the number of non-zeros for each coefficients\n - max: the maximum for each coefficient.\n - min: the minimum for each coefficient.\n - normL2: the Euclidean norm for each coefficient.\n - normL1: the L1 norm of each coefficient (sum of the absolute values).\n\n :param metrics:\n metrics that can be provided.\n :return:\n an object of :py:class:`pyspark.ml.stat.SummaryBuilder`\n\n Note: Currently, the performance of this interface is about 2x~3x slower then using the RDD\n interface.", "output": "def metrics(*metrics):\n \"\"\"\n Given a list of metrics, provides a builder that it turns computes metrics from a column.\n\n See the documentation of [[Summarizer]] for an example.\n\n The following metrics are accepted (case sensitive):\n - mean: a vector that contains the coefficient-wise mean.\n - variance: a vector tha contains the coefficient-wise variance.\n - count: the count of all vectors seen.\n - numNonzeros: a vector with the number of non-zeros for each coefficients\n - max: the maximum for each coefficient.\n - min: the minimum for each coefficient.\n - normL2: the Euclidean norm for each coefficient.\n - normL1: the L1 norm of each coefficient (sum of the absolute values).\n\n :param metrics:\n metrics that can be provided.\n :return:\n an object of :py:class:`pyspark.ml.stat.SummaryBuilder`\n\n Note: Currently, the performance of this interface is about 2x~3x slower then using the RDD\n interface.\n \"\"\"\n sc = SparkContext._active_spark_context\n js = JavaWrapper._new_java_obj(\"org.apache.spark.ml.stat.Summarizer.metrics\",\n _to_seq(sc, metrics))\n return SummaryBuilder(js)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns an aggregate object that contains the summary of the column with the requested\n metrics.\n\n :param featuresCol:\n a column that contains features Vector object.\n :param weightCol:\n a column that contains weight value. Default weight is 1.0.\n :return:\n an aggregate column that contains the statistics. The exact content of this\n structure is determined during the creation of the builder.", "output": "def summary(self, featuresCol, weightCol=None):\n \"\"\"\n Returns an aggregate object that contains the summary of the column with the requested\n metrics.\n\n :param featuresCol:\n a column that contains features Vector object.\n :param weightCol:\n a column that contains weight value. Default weight is 1.0.\n :return:\n an aggregate column that contains the statistics. The exact content of this\n structure is determined during the creation of the builder.\n \"\"\"\n featuresCol, weightCol = Summarizer._check_param(featuresCol, weightCol)\n return Column(self._java_obj.summary(featuresCol._jc, weightCol._jc))" }, { "instruction": "Write or improve a Python function based on this description:\n\nCompute the correlation (matrix) for the input RDD(s) using the\n specified method.\n Methods currently supported: I{pearson (default), spearman}.\n\n If a single RDD of Vectors is passed in, a correlation matrix\n comparing the columns in the input RDD is returned. Use C{method=}\n to specify the method to be used for single RDD inout.\n If two RDDs of floats are passed in, a single float is returned.\n\n :param x: an RDD of vector for which the correlation matrix is to be computed,\n or an RDD of float of the same cardinality as y when y is specified.\n :param y: an RDD of float of the same cardinality as x.\n :param method: String specifying the method to use for computing correlation.\n Supported: `pearson` (default), `spearman`\n :return: Correlation matrix comparing columns in x.\n\n >>> x = sc.parallelize([1.0, 0.0, -2.0], 2)\n >>> y = sc.parallelize([4.0, 5.0, 3.0], 2)\n >>> zeros = sc.parallelize([0.0, 0.0, 0.0], 2)\n >>> abs(Statistics.corr(x, y) - 0.6546537) < 1e-7\n True\n >>> Statistics.corr(x, y) == Statistics.corr(x, y, \"pearson\")\n True\n >>> Statistics.corr(x, y, \"spearman\")\n 0.5\n >>> from math import isnan\n >>> isnan(Statistics.corr(x, zeros))\n True\n >>> from pyspark.mllib.linalg import Vectors\n >>> rdd = sc.parallelize([Vectors.dense([1, 0, 0, -2]), Vectors.dense([4, 5, 0, 3]),\n ... Vectors.dense([6, 7, 0, 8]), Vectors.dense([9, 0, 0, 1])])\n >>> pearsonCorr = Statistics.corr(rdd)\n >>> print(str(pearsonCorr).replace('nan', 'NaN'))\n [[ 1. 0.05564149 NaN 0.40047142]\n [ 0.05564149 1. NaN 0.91359586]\n [ NaN NaN 1. NaN]\n [ 0.40047142 0.91359586 NaN 1. ]]\n >>> spearmanCorr = Statistics.corr(rdd, method=\"spearman\")\n >>> print(str(spearmanCorr).replace('nan', 'NaN'))\n [[ 1. 0.10540926 NaN 0.4 ]\n [ 0.10540926 1. NaN 0.9486833 ]\n [ NaN NaN 1. NaN]\n [ 0.4 0.9486833 NaN 1. ]]\n >>> try:\n ... Statistics.corr(rdd, \"spearman\")\n ... print(\"Method name as second argument without 'method=' shouldn't be allowed.\")\n ... except TypeError:\n ... pass", "output": "def corr(x, y=None, method=None):\n \"\"\"\n Compute the correlation (matrix) for the input RDD(s) using the\n specified method.\n Methods currently supported: I{pearson (default), spearman}.\n\n If a single RDD of Vectors is passed in, a correlation matrix\n comparing the columns in the input RDD is returned. Use C{method=}\n to specify the method to be used for single RDD inout.\n If two RDDs of floats are passed in, a single float is returned.\n\n :param x: an RDD of vector for which the correlation matrix is to be computed,\n or an RDD of float of the same cardinality as y when y is specified.\n :param y: an RDD of float of the same cardinality as x.\n :param method: String specifying the method to use for computing correlation.\n Supported: `pearson` (default), `spearman`\n :return: Correlation matrix comparing columns in x.\n\n >>> x = sc.parallelize([1.0, 0.0, -2.0], 2)\n >>> y = sc.parallelize([4.0, 5.0, 3.0], 2)\n >>> zeros = sc.parallelize([0.0, 0.0, 0.0], 2)\n >>> abs(Statistics.corr(x, y) - 0.6546537) < 1e-7\n True\n >>> Statistics.corr(x, y) == Statistics.corr(x, y, \"pearson\")\n True\n >>> Statistics.corr(x, y, \"spearman\")\n 0.5\n >>> from math import isnan\n >>> isnan(Statistics.corr(x, zeros))\n True\n >>> from pyspark.mllib.linalg import Vectors\n >>> rdd = sc.parallelize([Vectors.dense([1, 0, 0, -2]), Vectors.dense([4, 5, 0, 3]),\n ... Vectors.dense([6, 7, 0, 8]), Vectors.dense([9, 0, 0, 1])])\n >>> pearsonCorr = Statistics.corr(rdd)\n >>> print(str(pearsonCorr).replace('nan', 'NaN'))\n [[ 1. 0.05564149 NaN 0.40047142]\n [ 0.05564149 1. NaN 0.91359586]\n [ NaN NaN 1. NaN]\n [ 0.40047142 0.91359586 NaN 1. ]]\n >>> spearmanCorr = Statistics.corr(rdd, method=\"spearman\")\n >>> print(str(spearmanCorr).replace('nan', 'NaN'))\n [[ 1. 0.10540926 NaN 0.4 ]\n [ 0.10540926 1. NaN 0.9486833 ]\n [ NaN NaN 1. NaN]\n [ 0.4 0.9486833 NaN 1. ]]\n >>> try:\n ... Statistics.corr(rdd, \"spearman\")\n ... print(\"Method name as second argument without 'method=' shouldn't be allowed.\")\n ... except TypeError:\n ... pass\n \"\"\"\n # Check inputs to determine whether a single value or a matrix is needed for output.\n # Since it's legal for users to use the method name as the second argument, we need to\n # check if y is used to specify the method name instead.\n if type(y) == str:\n raise TypeError(\"Use 'method=' to specify method name.\")\n\n if not y:\n return callMLlibFunc(\"corr\", x.map(_convert_to_vector), method).toArray()\n else:\n return callMLlibFunc(\"corr\", x.map(float), y.map(float), method)" }, { "instruction": "Write or improve a Python function based on this description:\n\nCreates a list of callables which can be called from different threads to fit and evaluate\n an estimator in parallel. Each callable returns an `(index, metric)` pair.\n\n :param est: Estimator, the estimator to be fit.\n :param train: DataFrame, training data set, used for fitting.\n :param eva: Evaluator, used to compute `metric`\n :param validation: DataFrame, validation data set, used for evaluation.\n :param epm: Sequence of ParamMap, params maps to be used during fitting & evaluation.\n :param collectSubModel: Whether to collect sub model.\n :return: (int, float, subModel), an index into `epm` and the associated metric value.", "output": "def _parallelFitTasks(est, train, eva, validation, epm, collectSubModel):\n \"\"\"\n Creates a list of callables which can be called from different threads to fit and evaluate\n an estimator in parallel. Each callable returns an `(index, metric)` pair.\n\n :param est: Estimator, the estimator to be fit.\n :param train: DataFrame, training data set, used for fitting.\n :param eva: Evaluator, used to compute `metric`\n :param validation: DataFrame, validation data set, used for evaluation.\n :param epm: Sequence of ParamMap, params maps to be used during fitting & evaluation.\n :param collectSubModel: Whether to collect sub model.\n :return: (int, float, subModel), an index into `epm` and the associated metric value.\n \"\"\"\n modelIter = est.fitMultiple(train, epm)\n\n def singleTask():\n index, model = next(modelIter)\n metric = eva.evaluate(model.transform(validation, epm[index]))\n return index, metric, model if collectSubModel else None\n\n return [singleTask] * len(epm)" }, { "instruction": "Write or improve a Python function based on this description:\n\nSets the given parameters in this grid to fixed values.\n Accepts either a parameter dictionary or a list of (parameter, value) pairs.", "output": "def baseOn(self, *args):\n \"\"\"\n Sets the given parameters in this grid to fixed values.\n Accepts either a parameter dictionary or a list of (parameter, value) pairs.\n \"\"\"\n if isinstance(args[0], dict):\n self.baseOn(*args[0].items())\n else:\n for (param, value) in args:\n self.addGrid(param, [value])\n\n return self" }, { "instruction": "Write or improve a Python function based on this description:\n\nBuilds and returns all combinations of parameters specified\n by the param grid.", "output": "def build(self):\n \"\"\"\n Builds and returns all combinations of parameters specified\n by the param grid.\n \"\"\"\n keys = self._param_grid.keys()\n grid_values = self._param_grid.values()\n\n def to_key_value_pairs(keys, values):\n return [(key, key.typeConverter(value)) for key, value in zip(keys, values)]\n\n return [dict(to_key_value_pairs(keys, prod)) for prod in itertools.product(*grid_values)]" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn Python estimator, estimatorParamMaps, and evaluator from a Java ValidatorParams.", "output": "def _from_java_impl(cls, java_stage):\n \"\"\"\n Return Python estimator, estimatorParamMaps, and evaluator from a Java ValidatorParams.\n \"\"\"\n\n # Load information from java_stage to the instance.\n estimator = JavaParams._from_java(java_stage.getEstimator())\n evaluator = JavaParams._from_java(java_stage.getEvaluator())\n epms = [estimator._transfer_param_map_from_java(epm)\n for epm in java_stage.getEstimatorParamMaps()]\n return estimator, epms, evaluator" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn Java estimator, estimatorParamMaps, and evaluator from this Python instance.", "output": "def _to_java_impl(self):\n \"\"\"\n Return Java estimator, estimatorParamMaps, and evaluator from this Python instance.\n \"\"\"\n\n gateway = SparkContext._gateway\n cls = SparkContext._jvm.org.apache.spark.ml.param.ParamMap\n\n java_epms = gateway.new_array(cls, len(self.getEstimatorParamMaps()))\n for idx, epm in enumerate(self.getEstimatorParamMaps()):\n java_epms[idx] = self.getEstimator()._transfer_param_map_to_java(epm)\n\n java_estimator = self.getEstimator()._to_java()\n java_evaluator = self.getEvaluator()._to_java()\n return java_estimator, java_epms, java_evaluator" }, { "instruction": "Write or improve a Python function based on this description:\n\nGiven a Java CrossValidator, create and return a Python wrapper of it.\n Used for ML persistence.", "output": "def _from_java(cls, java_stage):\n \"\"\"\n Given a Java CrossValidator, create and return a Python wrapper of it.\n Used for ML persistence.\n \"\"\"\n\n estimator, epms, evaluator = super(CrossValidator, cls)._from_java_impl(java_stage)\n numFolds = java_stage.getNumFolds()\n seed = java_stage.getSeed()\n parallelism = java_stage.getParallelism()\n collectSubModels = java_stage.getCollectSubModels()\n # Create a new instance of this stage.\n py_stage = cls(estimator=estimator, estimatorParamMaps=epms, evaluator=evaluator,\n numFolds=numFolds, seed=seed, parallelism=parallelism,\n collectSubModels=collectSubModels)\n py_stage._resetUid(java_stage.uid())\n return py_stage" }, { "instruction": "Write or improve a Python function based on this description:\n\nTransfer this instance to a Java CrossValidator. Used for ML persistence.\n\n :return: Java object equivalent to this instance.", "output": "def _to_java(self):\n \"\"\"\n Transfer this instance to a Java CrossValidator. Used for ML persistence.\n\n :return: Java object equivalent to this instance.\n \"\"\"\n\n estimator, epms, evaluator = super(CrossValidator, self)._to_java_impl()\n\n _java_obj = JavaParams._new_java_obj(\"org.apache.spark.ml.tuning.CrossValidator\", self.uid)\n _java_obj.setEstimatorParamMaps(epms)\n _java_obj.setEvaluator(evaluator)\n _java_obj.setEstimator(estimator)\n _java_obj.setSeed(self.getSeed())\n _java_obj.setNumFolds(self.getNumFolds())\n _java_obj.setParallelism(self.getParallelism())\n _java_obj.setCollectSubModels(self.getCollectSubModels())\n\n return _java_obj" }, { "instruction": "Write or improve a Python function based on this description:\n\nCreates a copy of this instance with a randomly generated uid\n and some extra params. This copies the underlying bestModel,\n creates a deep copy of the embedded paramMap, and\n copies the embedded and extra parameters over.\n It does not copy the extra Params into the subModels.\n\n :param extra: Extra parameters to copy to the new instance\n :return: Copy of this instance", "output": "def copy(self, extra=None):\n \"\"\"\n Creates a copy of this instance with a randomly generated uid\n and some extra params. This copies the underlying bestModel,\n creates a deep copy of the embedded paramMap, and\n copies the embedded and extra parameters over.\n It does not copy the extra Params into the subModels.\n\n :param extra: Extra parameters to copy to the new instance\n :return: Copy of this instance\n \"\"\"\n if extra is None:\n extra = dict()\n bestModel = self.bestModel.copy(extra)\n avgMetrics = self.avgMetrics\n subModels = self.subModels\n return CrossValidatorModel(bestModel, avgMetrics, subModels)" }, { "instruction": "Write or improve a Python function based on this description:\n\nsetParams(self, estimator=None, estimatorParamMaps=None, evaluator=None, trainRatio=0.75,\\\n parallelism=1, collectSubModels=False, seed=None):\n Sets params for the train validation split.", "output": "def setParams(self, estimator=None, estimatorParamMaps=None, evaluator=None, trainRatio=0.75,\n parallelism=1, collectSubModels=False, seed=None):\n \"\"\"\n setParams(self, estimator=None, estimatorParamMaps=None, evaluator=None, trainRatio=0.75,\\\n parallelism=1, collectSubModels=False, seed=None):\n Sets params for the train validation split.\n \"\"\"\n kwargs = self._input_kwargs\n return self._set(**kwargs)" }, { "instruction": "Write or improve a Python function based on this description:\n\nCreates a copy of this instance with a randomly generated uid\n and some extra params. This copies creates a deep copy of\n the embedded paramMap, and copies the embedded and extra parameters over.\n\n :param extra: Extra parameters to copy to the new instance\n :return: Copy of this instance", "output": "def copy(self, extra=None):\n \"\"\"\n Creates a copy of this instance with a randomly generated uid\n and some extra params. This copies creates a deep copy of\n the embedded paramMap, and copies the embedded and extra parameters over.\n\n :param extra: Extra parameters to copy to the new instance\n :return: Copy of this instance\n \"\"\"\n if extra is None:\n extra = dict()\n newTVS = Params.copy(self, extra)\n if self.isSet(self.estimator):\n newTVS.setEstimator(self.getEstimator().copy(extra))\n # estimatorParamMaps remain the same\n if self.isSet(self.evaluator):\n newTVS.setEvaluator(self.getEvaluator().copy(extra))\n return newTVS" }, { "instruction": "Write or improve a Python function based on this description:\n\nGiven a Java TrainValidationSplit, create and return a Python wrapper of it.\n Used for ML persistence.", "output": "def _from_java(cls, java_stage):\n \"\"\"\n Given a Java TrainValidationSplit, create and return a Python wrapper of it.\n Used for ML persistence.\n \"\"\"\n\n estimator, epms, evaluator = super(TrainValidationSplit, cls)._from_java_impl(java_stage)\n trainRatio = java_stage.getTrainRatio()\n seed = java_stage.getSeed()\n parallelism = java_stage.getParallelism()\n collectSubModels = java_stage.getCollectSubModels()\n # Create a new instance of this stage.\n py_stage = cls(estimator=estimator, estimatorParamMaps=epms, evaluator=evaluator,\n trainRatio=trainRatio, seed=seed, parallelism=parallelism,\n collectSubModels=collectSubModels)\n py_stage._resetUid(java_stage.uid())\n return py_stage" }, { "instruction": "Write or improve a Python function based on this description:\n\nTransfer this instance to a Java TrainValidationSplit. Used for ML persistence.\n :return: Java object equivalent to this instance.", "output": "def _to_java(self):\n \"\"\"\n Transfer this instance to a Java TrainValidationSplit. Used for ML persistence.\n :return: Java object equivalent to this instance.\n \"\"\"\n\n estimator, epms, evaluator = super(TrainValidationSplit, self)._to_java_impl()\n\n _java_obj = JavaParams._new_java_obj(\"org.apache.spark.ml.tuning.TrainValidationSplit\",\n self.uid)\n _java_obj.setEstimatorParamMaps(epms)\n _java_obj.setEvaluator(evaluator)\n _java_obj.setEstimator(estimator)\n _java_obj.setTrainRatio(self.getTrainRatio())\n _java_obj.setSeed(self.getSeed())\n _java_obj.setParallelism(self.getParallelism())\n _java_obj.setCollectSubModels(self.getCollectSubModels())\n return _java_obj" }, { "instruction": "Write or improve a Python function based on this description:\n\nCreates a copy of this instance with a randomly generated uid\n and some extra params. This copies the underlying bestModel,\n creates a deep copy of the embedded paramMap, and\n copies the embedded and extra parameters over.\n And, this creates a shallow copy of the validationMetrics.\n It does not copy the extra Params into the subModels.\n\n :param extra: Extra parameters to copy to the new instance\n :return: Copy of this instance", "output": "def copy(self, extra=None):\n \"\"\"\n Creates a copy of this instance with a randomly generated uid\n and some extra params. This copies the underlying bestModel,\n creates a deep copy of the embedded paramMap, and\n copies the embedded and extra parameters over.\n And, this creates a shallow copy of the validationMetrics.\n It does not copy the extra Params into the subModels.\n\n :param extra: Extra parameters to copy to the new instance\n :return: Copy of this instance\n \"\"\"\n if extra is None:\n extra = dict()\n bestModel = self.bestModel.copy(extra)\n validationMetrics = list(self.validationMetrics)\n subModels = self.subModels\n return TrainValidationSplitModel(bestModel, validationMetrics, subModels)" }, { "instruction": "Write or improve a Python function based on this description:\n\nGiven a Java TrainValidationSplitModel, create and return a Python wrapper of it.\n Used for ML persistence.", "output": "def _from_java(cls, java_stage):\n \"\"\"\n Given a Java TrainValidationSplitModel, create and return a Python wrapper of it.\n Used for ML persistence.\n \"\"\"\n\n # Load information from java_stage to the instance.\n bestModel = JavaParams._from_java(java_stage.bestModel())\n estimator, epms, evaluator = super(TrainValidationSplitModel,\n cls)._from_java_impl(java_stage)\n # Create a new instance of this stage.\n py_stage = cls(bestModel=bestModel).setEstimator(estimator)\n py_stage = py_stage.setEstimatorParamMaps(epms).setEvaluator(evaluator)\n\n if java_stage.hasSubModels():\n py_stage.subModels = [JavaParams._from_java(sub_model)\n for sub_model in java_stage.subModels()]\n\n py_stage._resetUid(java_stage.uid())\n return py_stage" }, { "instruction": "Write or improve a Python function based on this description:\n\nTransfer this instance to a Java TrainValidationSplitModel. Used for ML persistence.\n :return: Java object equivalent to this instance.", "output": "def _to_java(self):\n \"\"\"\n Transfer this instance to a Java TrainValidationSplitModel. Used for ML persistence.\n :return: Java object equivalent to this instance.\n \"\"\"\n\n sc = SparkContext._active_spark_context\n # TODO: persst validation metrics as well\n _java_obj = JavaParams._new_java_obj(\n \"org.apache.spark.ml.tuning.TrainValidationSplitModel\",\n self.uid,\n self.bestModel._to_java(),\n _py2java(sc, []))\n estimator, epms, evaluator = super(TrainValidationSplitModel, self)._to_java_impl()\n\n _java_obj.set(\"evaluator\", evaluator)\n _java_obj.set(\"estimator\", estimator)\n _java_obj.set(\"estimatorParamMaps\", epms)\n\n if self.subModels is not None:\n java_sub_models = [sub_model._to_java() for sub_model in self.subModels]\n _java_obj.setSubModels(java_sub_models)\n\n return _java_obj" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns the value of Spark runtime configuration property for the given key,\n assuming it is set.", "output": "def get(self, key, default=_NoValue):\n \"\"\"Returns the value of Spark runtime configuration property for the given key,\n assuming it is set.\n \"\"\"\n self._checkType(key, \"key\")\n if default is _NoValue:\n return self._jconf.get(key)\n else:\n if default is not None:\n self._checkType(default, \"default\")\n return self._jconf.get(key, default)" }, { "instruction": "Write or improve a Python function based on this description:\n\nAssert that an object is of type str.", "output": "def _checkType(self, obj, identifier):\n \"\"\"Assert that an object is of type str.\"\"\"\n if not isinstance(obj, basestring):\n raise TypeError(\"expected %s '%s' to be a string (was '%s')\" %\n (identifier, obj, type(obj).__name__))" }, { "instruction": "Write or improve a Python function based on this description:\n\nCreate a PySpark function by its name", "output": "def _create_function(name, doc=\"\"):\n \"\"\"Create a PySpark function by its name\"\"\"\n def _(col):\n sc = SparkContext._active_spark_context\n jc = getattr(sc._jvm.functions, name)(col._jc if isinstance(col, Column) else col)\n return Column(jc)\n _.__name__ = name\n _.__doc__ = doc\n return _" }, { "instruction": "Write or improve a Python function based on this description:\n\nSimilar with `_create_function` but creates a PySpark function that takes a column\n (as string as well). This is mainly for PySpark functions to take strings as\n column names.", "output": "def _create_function_over_column(name, doc=\"\"):\n \"\"\"Similar with `_create_function` but creates a PySpark function that takes a column\n (as string as well). This is mainly for PySpark functions to take strings as\n column names.\n \"\"\"\n def _(col):\n sc = SparkContext._active_spark_context\n jc = getattr(sc._jvm.functions, name)(_to_java_column(col))\n return Column(jc)\n _.__name__ = name\n _.__doc__ = doc\n return _" }, { "instruction": "Write or improve a Python function based on this description:\n\nWrap the deprecated function to print out deprecation warnings", "output": "def _wrap_deprecated_function(func, message):\n \"\"\" Wrap the deprecated function to print out deprecation warnings\"\"\"\n def _(col):\n warnings.warn(message, DeprecationWarning)\n return func(col)\n return functools.wraps(func)(_)" }, { "instruction": "Write or improve a Python function based on this description:\n\nCreate a binary mathfunction by name", "output": "def _create_binary_mathfunction(name, doc=\"\"):\n \"\"\" Create a binary mathfunction by name\"\"\"\n def _(col1, col2):\n sc = SparkContext._active_spark_context\n # For legacy reasons, the arguments here can be implicitly converted into floats,\n # if they are not columns or strings.\n if isinstance(col1, Column):\n arg1 = col1._jc\n elif isinstance(col1, basestring):\n arg1 = _create_column_from_name(col1)\n else:\n arg1 = float(col1)\n\n if isinstance(col2, Column):\n arg2 = col2._jc\n elif isinstance(col2, basestring):\n arg2 = _create_column_from_name(col2)\n else:\n arg2 = float(col2)\n\n jc = getattr(sc._jvm.functions, name)(arg1, arg2)\n return Column(jc)\n _.__name__ = name\n _.__doc__ = doc\n return _" }, { "instruction": "Write or improve a Python function based on this description:\n\nCreate a window function by name", "output": "def _create_window_function(name, doc=''):\n \"\"\" Create a window function by name \"\"\"\n def _():\n sc = SparkContext._active_spark_context\n jc = getattr(sc._jvm.functions, name)()\n return Column(jc)\n _.__name__ = name\n _.__doc__ = 'Window function: ' + doc\n return _" }, { "instruction": "Write or improve a Python function based on this description:\n\nAggregate function: returns a new :class:`Column` for approximate distinct count of\n column `col`.\n\n :param rsd: maximum estimation error allowed (default = 0.05). For rsd < 0.01, it is more\n efficient to use :func:`countDistinct`\n\n >>> df.agg(approx_count_distinct(df.age).alias('distinct_ages')).collect()\n [Row(distinct_ages=2)]", "output": "def approx_count_distinct(col, rsd=None):\n \"\"\"Aggregate function: returns a new :class:`Column` for approximate distinct count of\n column `col`.\n\n :param rsd: maximum estimation error allowed (default = 0.05). For rsd < 0.01, it is more\n efficient to use :func:`countDistinct`\n\n >>> df.agg(approx_count_distinct(df.age).alias('distinct_ages')).collect()\n [Row(distinct_ages=2)]\n \"\"\"\n sc = SparkContext._active_spark_context\n if rsd is None:\n jc = sc._jvm.functions.approx_count_distinct(_to_java_column(col))\n else:\n jc = sc._jvm.functions.approx_count_distinct(_to_java_column(col), rsd)\n return Column(jc)" }, { "instruction": "Write or improve a Python function based on this description:\n\nMarks a DataFrame as small enough for use in broadcast joins.", "output": "def broadcast(df):\n \"\"\"Marks a DataFrame as small enough for use in broadcast joins.\"\"\"\n\n sc = SparkContext._active_spark_context\n return DataFrame(sc._jvm.functions.broadcast(df._jdf), df.sql_ctx)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns a new :class:`Column` for distinct count of ``col`` or ``cols``.\n\n >>> df.agg(countDistinct(df.age, df.name).alias('c')).collect()\n [Row(c=2)]\n\n >>> df.agg(countDistinct(\"age\", \"name\").alias('c')).collect()\n [Row(c=2)]", "output": "def countDistinct(col, *cols):\n \"\"\"Returns a new :class:`Column` for distinct count of ``col`` or ``cols``.\n\n >>> df.agg(countDistinct(df.age, df.name).alias('c')).collect()\n [Row(c=2)]\n\n >>> df.agg(countDistinct(\"age\", \"name\").alias('c')).collect()\n [Row(c=2)]\n \"\"\"\n sc = SparkContext._active_spark_context\n jc = sc._jvm.functions.countDistinct(_to_java_column(col), _to_seq(sc, cols, _to_java_column))\n return Column(jc)" }, { "instruction": "Write or improve a Python function based on this description:\n\nAggregate function: returns the last value in a group.\n\n The function by default returns the last values it sees. It will return the last non-null\n value it sees when ignoreNulls is set to true. If all values are null, then null is returned.\n\n .. note:: The function is non-deterministic because its results depends on order of rows\n which may be non-deterministic after a shuffle.", "output": "def last(col, ignorenulls=False):\n \"\"\"Aggregate function: returns the last value in a group.\n\n The function by default returns the last values it sees. It will return the last non-null\n value it sees when ignoreNulls is set to true. If all values are null, then null is returned.\n\n .. note:: The function is non-deterministic because its results depends on order of rows\n which may be non-deterministic after a shuffle.\n \"\"\"\n sc = SparkContext._active_spark_context\n jc = sc._jvm.functions.last(_to_java_column(col), ignorenulls)\n return Column(jc)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns col1 if it is not NaN, or col2 if col1 is NaN.\n\n Both inputs should be floating point columns (:class:`DoubleType` or :class:`FloatType`).\n\n >>> df = spark.createDataFrame([(1.0, float('nan')), (float('nan'), 2.0)], (\"a\", \"b\"))\n >>> df.select(nanvl(\"a\", \"b\").alias(\"r1\"), nanvl(df.a, df.b).alias(\"r2\")).collect()\n [Row(r1=1.0, r2=1.0), Row(r1=2.0, r2=2.0)]", "output": "def nanvl(col1, col2):\n \"\"\"Returns col1 if it is not NaN, or col2 if col1 is NaN.\n\n Both inputs should be floating point columns (:class:`DoubleType` or :class:`FloatType`).\n\n >>> df = spark.createDataFrame([(1.0, float('nan')), (float('nan'), 2.0)], (\"a\", \"b\"))\n >>> df.select(nanvl(\"a\", \"b\").alias(\"r1\"), nanvl(df.a, df.b).alias(\"r2\")).collect()\n [Row(r1=1.0, r2=1.0), Row(r1=2.0, r2=2.0)]\n \"\"\"\n sc = SparkContext._active_spark_context\n return Column(sc._jvm.functions.nanvl(_to_java_column(col1), _to_java_column(col2)))" }, { "instruction": "Write or improve a Python function based on this description:\n\nGenerates a random column with independent and identically distributed (i.i.d.) samples\n from U[0.0, 1.0].\n\n .. note:: The function is non-deterministic in general case.\n\n >>> df.withColumn('rand', rand(seed=42) * 3).collect()\n [Row(age=2, name=u'Alice', rand=2.4052597283576684),\n Row(age=5, name=u'Bob', rand=2.3913904055683974)]", "output": "def rand(seed=None):\n \"\"\"Generates a random column with independent and identically distributed (i.i.d.) samples\n from U[0.0, 1.0].\n\n .. note:: The function is non-deterministic in general case.\n\n >>> df.withColumn('rand', rand(seed=42) * 3).collect()\n [Row(age=2, name=u'Alice', rand=2.4052597283576684),\n Row(age=5, name=u'Bob', rand=2.3913904055683974)]\n \"\"\"\n sc = SparkContext._active_spark_context\n if seed is not None:\n jc = sc._jvm.functions.rand(seed)\n else:\n jc = sc._jvm.functions.rand()\n return Column(jc)" }, { "instruction": "Write or improve a Python function based on this description:\n\nRound the given value to `scale` decimal places using HALF_UP rounding mode if `scale` >= 0\n or at integral part when `scale` < 0.\n\n >>> spark.createDataFrame([(2.5,)], ['a']).select(round('a', 0).alias('r')).collect()\n [Row(r=3.0)]", "output": "def round(col, scale=0):\n \"\"\"\n Round the given value to `scale` decimal places using HALF_UP rounding mode if `scale` >= 0\n or at integral part when `scale` < 0.\n\n >>> spark.createDataFrame([(2.5,)], ['a']).select(round('a', 0).alias('r')).collect()\n [Row(r=3.0)]\n \"\"\"\n sc = SparkContext._active_spark_context\n return Column(sc._jvm.functions.round(_to_java_column(col), scale))" }, { "instruction": "Write or improve a Python function based on this description:\n\nShift the given value numBits left.\n\n >>> spark.createDataFrame([(21,)], ['a']).select(shiftLeft('a', 1).alias('r')).collect()\n [Row(r=42)]", "output": "def shiftLeft(col, numBits):\n \"\"\"Shift the given value numBits left.\n\n >>> spark.createDataFrame([(21,)], ['a']).select(shiftLeft('a', 1).alias('r')).collect()\n [Row(r=42)]\n \"\"\"\n sc = SparkContext._active_spark_context\n return Column(sc._jvm.functions.shiftLeft(_to_java_column(col), numBits))" }, { "instruction": "Write or improve a Python function based on this description:\n\n(Signed) shift the given value numBits right.\n\n >>> spark.createDataFrame([(42,)], ['a']).select(shiftRight('a', 1).alias('r')).collect()\n [Row(r=21)]", "output": "def shiftRight(col, numBits):\n \"\"\"(Signed) shift the given value numBits right.\n\n >>> spark.createDataFrame([(42,)], ['a']).select(shiftRight('a', 1).alias('r')).collect()\n [Row(r=21)]\n \"\"\"\n sc = SparkContext._active_spark_context\n jc = sc._jvm.functions.shiftRight(_to_java_column(col), numBits)\n return Column(jc)" }, { "instruction": "Write or improve a Python function based on this description:\n\nParses the expression string into the column that it represents\n\n >>> df.select(expr(\"length(name)\")).collect()\n [Row(length(name)=5), Row(length(name)=3)]", "output": "def expr(str):\n \"\"\"Parses the expression string into the column that it represents\n\n >>> df.select(expr(\"length(name)\")).collect()\n [Row(length(name)=5), Row(length(name)=3)]\n \"\"\"\n sc = SparkContext._active_spark_context\n return Column(sc._jvm.functions.expr(str))" }, { "instruction": "Write or improve a Python function based on this description:\n\nEvaluates a list of conditions and returns one of multiple possible result expressions.\n If :func:`Column.otherwise` is not invoked, None is returned for unmatched conditions.\n\n :param condition: a boolean :class:`Column` expression.\n :param value: a literal value, or a :class:`Column` expression.\n\n >>> df.select(when(df['age'] == 2, 3).otherwise(4).alias(\"age\")).collect()\n [Row(age=3), Row(age=4)]\n\n >>> df.select(when(df.age == 2, df.age + 1).alias(\"age\")).collect()\n [Row(age=3), Row(age=None)]", "output": "def when(condition, value):\n \"\"\"Evaluates a list of conditions and returns one of multiple possible result expressions.\n If :func:`Column.otherwise` is not invoked, None is returned for unmatched conditions.\n\n :param condition: a boolean :class:`Column` expression.\n :param value: a literal value, or a :class:`Column` expression.\n\n >>> df.select(when(df['age'] == 2, 3).otherwise(4).alias(\"age\")).collect()\n [Row(age=3), Row(age=4)]\n\n >>> df.select(when(df.age == 2, df.age + 1).alias(\"age\")).collect()\n [Row(age=3), Row(age=None)]\n \"\"\"\n sc = SparkContext._active_spark_context\n if not isinstance(condition, Column):\n raise TypeError(\"condition should be a Column\")\n v = value._jc if isinstance(value, Column) else value\n jc = sc._jvm.functions.when(condition._jc, v)\n return Column(jc)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns the first argument-based logarithm of the second argument.\n\n If there is only one argument, then this takes the natural logarithm of the argument.\n\n >>> df.select(log(10.0, df.age).alias('ten')).rdd.map(lambda l: str(l.ten)[:7]).collect()\n ['0.30102', '0.69897']\n\n >>> df.select(log(df.age).alias('e')).rdd.map(lambda l: str(l.e)[:7]).collect()\n ['0.69314', '1.60943']", "output": "def log(arg1, arg2=None):\n \"\"\"Returns the first argument-based logarithm of the second argument.\n\n If there is only one argument, then this takes the natural logarithm of the argument.\n\n >>> df.select(log(10.0, df.age).alias('ten')).rdd.map(lambda l: str(l.ten)[:7]).collect()\n ['0.30102', '0.69897']\n\n >>> df.select(log(df.age).alias('e')).rdd.map(lambda l: str(l.e)[:7]).collect()\n ['0.69314', '1.60943']\n \"\"\"\n sc = SparkContext._active_spark_context\n if arg2 is None:\n jc = sc._jvm.functions.log(_to_java_column(arg1))\n else:\n jc = sc._jvm.functions.log(arg1, _to_java_column(arg2))\n return Column(jc)" }, { "instruction": "Write or improve a Python function based on this description:\n\nConvert a number in a string column from one base to another.\n\n >>> df = spark.createDataFrame([(\"010101\",)], ['n'])\n >>> df.select(conv(df.n, 2, 16).alias('hex')).collect()\n [Row(hex=u'15')]", "output": "def conv(col, fromBase, toBase):\n \"\"\"\n Convert a number in a string column from one base to another.\n\n >>> df = spark.createDataFrame([(\"010101\",)], ['n'])\n >>> df.select(conv(df.n, 2, 16).alias('hex')).collect()\n [Row(hex=u'15')]\n \"\"\"\n sc = SparkContext._active_spark_context\n return Column(sc._jvm.functions.conv(_to_java_column(col), fromBase, toBase))" }, { "instruction": "Write or improve a Python function based on this description:\n\nWindow function: returns the value that is `offset` rows before the current row, and\n `defaultValue` if there is less than `offset` rows before the current row. For example,\n an `offset` of one will return the previous row at any given point in the window partition.\n\n This is equivalent to the LAG function in SQL.\n\n :param col: name of column or expression\n :param offset: number of row to extend\n :param default: default value", "output": "def lag(col, offset=1, default=None):\n \"\"\"\n Window function: returns the value that is `offset` rows before the current row, and\n `defaultValue` if there is less than `offset` rows before the current row. For example,\n an `offset` of one will return the previous row at any given point in the window partition.\n\n This is equivalent to the LAG function in SQL.\n\n :param col: name of column or expression\n :param offset: number of row to extend\n :param default: default value\n \"\"\"\n sc = SparkContext._active_spark_context\n return Column(sc._jvm.functions.lag(_to_java_column(col), offset, default))" }, { "instruction": "Write or improve a Python function based on this description:\n\nWindow function: returns the ntile group id (from 1 to `n` inclusive)\n in an ordered window partition. For example, if `n` is 4, the first\n quarter of the rows will get value 1, the second quarter will get 2,\n the third quarter will get 3, and the last quarter will get 4.\n\n This is equivalent to the NTILE function in SQL.\n\n :param n: an integer", "output": "def ntile(n):\n \"\"\"\n Window function: returns the ntile group id (from 1 to `n` inclusive)\n in an ordered window partition. For example, if `n` is 4, the first\n quarter of the rows will get value 1, the second quarter will get 2,\n the third quarter will get 3, and the last quarter will get 4.\n\n This is equivalent to the NTILE function in SQL.\n\n :param n: an integer\n \"\"\"\n sc = SparkContext._active_spark_context\n return Column(sc._jvm.functions.ntile(int(n)))" }, { "instruction": "Write or improve a Python function based on this description:\n\nConverts a date/timestamp/string to a value of string in the format specified by the date\n format given by the second argument.\n\n A pattern could be for instance `dd.MM.yyyy` and could return a string like '18.03.1993'. All\n pattern letters of the Java class `java.time.format.DateTimeFormatter` can be used.\n\n .. note:: Use when ever possible specialized functions like `year`. These benefit from a\n specialized implementation.\n\n >>> df = spark.createDataFrame([('2015-04-08',)], ['dt'])\n >>> df.select(date_format('dt', 'MM/dd/yyy').alias('date')).collect()\n [Row(date=u'04/08/2015')]", "output": "def date_format(date, format):\n \"\"\"\n Converts a date/timestamp/string to a value of string in the format specified by the date\n format given by the second argument.\n\n A pattern could be for instance `dd.MM.yyyy` and could return a string like '18.03.1993'. All\n pattern letters of the Java class `java.time.format.DateTimeFormatter` can be used.\n\n .. note:: Use when ever possible specialized functions like `year`. These benefit from a\n specialized implementation.\n\n >>> df = spark.createDataFrame([('2015-04-08',)], ['dt'])\n >>> df.select(date_format('dt', 'MM/dd/yyy').alias('date')).collect()\n [Row(date=u'04/08/2015')]\n \"\"\"\n sc = SparkContext._active_spark_context\n return Column(sc._jvm.functions.date_format(_to_java_column(date), format))" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns the date that is `days` days after `start`\n\n >>> df = spark.createDataFrame([('2015-04-08',)], ['dt'])\n >>> df.select(date_add(df.dt, 1).alias('next_date')).collect()\n [Row(next_date=datetime.date(2015, 4, 9))]", "output": "def date_add(start, days):\n \"\"\"\n Returns the date that is `days` days after `start`\n\n >>> df = spark.createDataFrame([('2015-04-08',)], ['dt'])\n >>> df.select(date_add(df.dt, 1).alias('next_date')).collect()\n [Row(next_date=datetime.date(2015, 4, 9))]\n \"\"\"\n sc = SparkContext._active_spark_context\n return Column(sc._jvm.functions.date_add(_to_java_column(start), days))" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns the number of days from `start` to `end`.\n\n >>> df = spark.createDataFrame([('2015-04-08','2015-05-10')], ['d1', 'd2'])\n >>> df.select(datediff(df.d2, df.d1).alias('diff')).collect()\n [Row(diff=32)]", "output": "def datediff(end, start):\n \"\"\"\n Returns the number of days from `start` to `end`.\n\n >>> df = spark.createDataFrame([('2015-04-08','2015-05-10')], ['d1', 'd2'])\n >>> df.select(datediff(df.d2, df.d1).alias('diff')).collect()\n [Row(diff=32)]\n \"\"\"\n sc = SparkContext._active_spark_context\n return Column(sc._jvm.functions.datediff(_to_java_column(end), _to_java_column(start)))" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns the date that is `months` months after `start`\n\n >>> df = spark.createDataFrame([('2015-04-08',)], ['dt'])\n >>> df.select(add_months(df.dt, 1).alias('next_month')).collect()\n [Row(next_month=datetime.date(2015, 5, 8))]", "output": "def add_months(start, months):\n \"\"\"\n Returns the date that is `months` months after `start`\n\n >>> df = spark.createDataFrame([('2015-04-08',)], ['dt'])\n >>> df.select(add_months(df.dt, 1).alias('next_month')).collect()\n [Row(next_month=datetime.date(2015, 5, 8))]\n \"\"\"\n sc = SparkContext._active_spark_context\n return Column(sc._jvm.functions.add_months(_to_java_column(start), months))" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns number of months between dates date1 and date2.\n If date1 is later than date2, then the result is positive.\n If date1 and date2 are on the same day of month, or both are the last day of month,\n returns an integer (time of day will be ignored).\n The result is rounded off to 8 digits unless `roundOff` is set to `False`.\n\n >>> df = spark.createDataFrame([('1997-02-28 10:30:00', '1996-10-30')], ['date1', 'date2'])\n >>> df.select(months_between(df.date1, df.date2).alias('months')).collect()\n [Row(months=3.94959677)]\n >>> df.select(months_between(df.date1, df.date2, False).alias('months')).collect()\n [Row(months=3.9495967741935485)]", "output": "def months_between(date1, date2, roundOff=True):\n \"\"\"\n Returns number of months between dates date1 and date2.\n If date1 is later than date2, then the result is positive.\n If date1 and date2 are on the same day of month, or both are the last day of month,\n returns an integer (time of day will be ignored).\n The result is rounded off to 8 digits unless `roundOff` is set to `False`.\n\n >>> df = spark.createDataFrame([('1997-02-28 10:30:00', '1996-10-30')], ['date1', 'date2'])\n >>> df.select(months_between(df.date1, df.date2).alias('months')).collect()\n [Row(months=3.94959677)]\n >>> df.select(months_between(df.date1, df.date2, False).alias('months')).collect()\n [Row(months=3.9495967741935485)]\n \"\"\"\n sc = SparkContext._active_spark_context\n return Column(sc._jvm.functions.months_between(\n _to_java_column(date1), _to_java_column(date2), roundOff))" }, { "instruction": "Write or improve a Python function based on this description:\n\nConverts a :class:`Column` of :class:`pyspark.sql.types.StringType` or\n :class:`pyspark.sql.types.TimestampType` into :class:`pyspark.sql.types.DateType`\n using the optionally specified format. Specify formats according to\n `DateTimeFormatter `_. # noqa\n By default, it follows casting rules to :class:`pyspark.sql.types.DateType` if the format\n is omitted (equivalent to ``col.cast(\"date\")``).\n\n >>> df = spark.createDataFrame([('1997-02-28 10:30:00',)], ['t'])\n >>> df.select(to_date(df.t).alias('date')).collect()\n [Row(date=datetime.date(1997, 2, 28))]\n\n >>> df = spark.createDataFrame([('1997-02-28 10:30:00',)], ['t'])\n >>> df.select(to_date(df.t, 'yyyy-MM-dd HH:mm:ss').alias('date')).collect()\n [Row(date=datetime.date(1997, 2, 28))]", "output": "def to_date(col, format=None):\n \"\"\"Converts a :class:`Column` of :class:`pyspark.sql.types.StringType` or\n :class:`pyspark.sql.types.TimestampType` into :class:`pyspark.sql.types.DateType`\n using the optionally specified format. Specify formats according to\n `DateTimeFormatter `_. # noqa\n By default, it follows casting rules to :class:`pyspark.sql.types.DateType` if the format\n is omitted (equivalent to ``col.cast(\"date\")``).\n\n >>> df = spark.createDataFrame([('1997-02-28 10:30:00',)], ['t'])\n >>> df.select(to_date(df.t).alias('date')).collect()\n [Row(date=datetime.date(1997, 2, 28))]\n\n >>> df = spark.createDataFrame([('1997-02-28 10:30:00',)], ['t'])\n >>> df.select(to_date(df.t, 'yyyy-MM-dd HH:mm:ss').alias('date')).collect()\n [Row(date=datetime.date(1997, 2, 28))]\n \"\"\"\n sc = SparkContext._active_spark_context\n if format is None:\n jc = sc._jvm.functions.to_date(_to_java_column(col))\n else:\n jc = sc._jvm.functions.to_date(_to_java_column(col), format)\n return Column(jc)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns timestamp truncated to the unit specified by the format.\n\n :param format: 'year', 'yyyy', 'yy', 'month', 'mon', 'mm',\n 'day', 'dd', 'hour', 'minute', 'second', 'week', 'quarter'\n\n >>> df = spark.createDataFrame([('1997-02-28 05:02:11',)], ['t'])\n >>> df.select(date_trunc('year', df.t).alias('year')).collect()\n [Row(year=datetime.datetime(1997, 1, 1, 0, 0))]\n >>> df.select(date_trunc('mon', df.t).alias('month')).collect()\n [Row(month=datetime.datetime(1997, 2, 1, 0, 0))]", "output": "def date_trunc(format, timestamp):\n \"\"\"\n Returns timestamp truncated to the unit specified by the format.\n\n :param format: 'year', 'yyyy', 'yy', 'month', 'mon', 'mm',\n 'day', 'dd', 'hour', 'minute', 'second', 'week', 'quarter'\n\n >>> df = spark.createDataFrame([('1997-02-28 05:02:11',)], ['t'])\n >>> df.select(date_trunc('year', df.t).alias('year')).collect()\n [Row(year=datetime.datetime(1997, 1, 1, 0, 0))]\n >>> df.select(date_trunc('mon', df.t).alias('month')).collect()\n [Row(month=datetime.datetime(1997, 2, 1, 0, 0))]\n \"\"\"\n sc = SparkContext._active_spark_context\n return Column(sc._jvm.functions.date_trunc(format, _to_java_column(timestamp)))" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns the first date which is later than the value of the date column.\n\n Day of the week parameter is case insensitive, and accepts:\n \"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\", \"Sun\".\n\n >>> df = spark.createDataFrame([('2015-07-27',)], ['d'])\n >>> df.select(next_day(df.d, 'Sun').alias('date')).collect()\n [Row(date=datetime.date(2015, 8, 2))]", "output": "def next_day(date, dayOfWeek):\n \"\"\"\n Returns the first date which is later than the value of the date column.\n\n Day of the week parameter is case insensitive, and accepts:\n \"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\", \"Sun\".\n\n >>> df = spark.createDataFrame([('2015-07-27',)], ['d'])\n >>> df.select(next_day(df.d, 'Sun').alias('date')).collect()\n [Row(date=datetime.date(2015, 8, 2))]\n \"\"\"\n sc = SparkContext._active_spark_context\n return Column(sc._jvm.functions.next_day(_to_java_column(date), dayOfWeek))" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns the last day of the month which the given date belongs to.\n\n >>> df = spark.createDataFrame([('1997-02-10',)], ['d'])\n >>> df.select(last_day(df.d).alias('date')).collect()\n [Row(date=datetime.date(1997, 2, 28))]", "output": "def last_day(date):\n \"\"\"\n Returns the last day of the month which the given date belongs to.\n\n >>> df = spark.createDataFrame([('1997-02-10',)], ['d'])\n >>> df.select(last_day(df.d).alias('date')).collect()\n [Row(date=datetime.date(1997, 2, 28))]\n \"\"\"\n sc = SparkContext._active_spark_context\n return Column(sc._jvm.functions.last_day(_to_java_column(date)))" }, { "instruction": "Write or improve a Python function based on this description:\n\nConvert time string with given pattern ('yyyy-MM-dd HH:mm:ss', by default)\n to Unix time stamp (in seconds), using the default timezone and the default\n locale, return null if fail.\n\n if `timestamp` is None, then it returns current timestamp.\n\n >>> spark.conf.set(\"spark.sql.session.timeZone\", \"America/Los_Angeles\")\n >>> time_df = spark.createDataFrame([('2015-04-08',)], ['dt'])\n >>> time_df.select(unix_timestamp('dt', 'yyyy-MM-dd').alias('unix_time')).collect()\n [Row(unix_time=1428476400)]\n >>> spark.conf.unset(\"spark.sql.session.timeZone\")", "output": "def unix_timestamp(timestamp=None, format='yyyy-MM-dd HH:mm:ss'):\n \"\"\"\n Convert time string with given pattern ('yyyy-MM-dd HH:mm:ss', by default)\n to Unix time stamp (in seconds), using the default timezone and the default\n locale, return null if fail.\n\n if `timestamp` is None, then it returns current timestamp.\n\n >>> spark.conf.set(\"spark.sql.session.timeZone\", \"America/Los_Angeles\")\n >>> time_df = spark.createDataFrame([('2015-04-08',)], ['dt'])\n >>> time_df.select(unix_timestamp('dt', 'yyyy-MM-dd').alias('unix_time')).collect()\n [Row(unix_time=1428476400)]\n >>> spark.conf.unset(\"spark.sql.session.timeZone\")\n \"\"\"\n sc = SparkContext._active_spark_context\n if timestamp is None:\n return Column(sc._jvm.functions.unix_timestamp())\n return Column(sc._jvm.functions.unix_timestamp(_to_java_column(timestamp), format))" }, { "instruction": "Write or improve a Python function based on this description:\n\nThis is a common function for databases supporting TIMESTAMP WITHOUT TIMEZONE. This function\n takes a timestamp which is timezone-agnostic, and interprets it as a timestamp in UTC, and\n renders that timestamp as a timestamp in the given time zone.\n\n However, timestamp in Spark represents number of microseconds from the Unix epoch, which is not\n timezone-agnostic. So in Spark this function just shift the timestamp value from UTC timezone to\n the given timezone.\n\n This function may return confusing result if the input is a string with timezone, e.g.\n '2018-03-13T06:18:23+00:00'. The reason is that, Spark firstly cast the string to timestamp\n according to the timezone in the string, and finally display the result by converting the\n timestamp to string according to the session local timezone.\n\n :param timestamp: the column that contains timestamps\n :param tz: a string that has the ID of timezone, e.g. \"GMT\", \"America/Los_Angeles\", etc\n\n .. versionchanged:: 2.4\n `tz` can take a :class:`Column` containing timezone ID strings.\n\n >>> df = spark.createDataFrame([('1997-02-28 10:30:00', 'JST')], ['ts', 'tz'])\n >>> df.select(from_utc_timestamp(df.ts, \"PST\").alias('local_time')).collect()\n [Row(local_time=datetime.datetime(1997, 2, 28, 2, 30))]\n >>> df.select(from_utc_timestamp(df.ts, df.tz).alias('local_time')).collect()\n [Row(local_time=datetime.datetime(1997, 2, 28, 19, 30))]\n\n .. note:: Deprecated in 3.0. See SPARK-25496", "output": "def from_utc_timestamp(timestamp, tz):\n \"\"\"\n This is a common function for databases supporting TIMESTAMP WITHOUT TIMEZONE. This function\n takes a timestamp which is timezone-agnostic, and interprets it as a timestamp in UTC, and\n renders that timestamp as a timestamp in the given time zone.\n\n However, timestamp in Spark represents number of microseconds from the Unix epoch, which is not\n timezone-agnostic. So in Spark this function just shift the timestamp value from UTC timezone to\n the given timezone.\n\n This function may return confusing result if the input is a string with timezone, e.g.\n '2018-03-13T06:18:23+00:00'. The reason is that, Spark firstly cast the string to timestamp\n according to the timezone in the string, and finally display the result by converting the\n timestamp to string according to the session local timezone.\n\n :param timestamp: the column that contains timestamps\n :param tz: a string that has the ID of timezone, e.g. \"GMT\", \"America/Los_Angeles\", etc\n\n .. versionchanged:: 2.4\n `tz` can take a :class:`Column` containing timezone ID strings.\n\n >>> df = spark.createDataFrame([('1997-02-28 10:30:00', 'JST')], ['ts', 'tz'])\n >>> df.select(from_utc_timestamp(df.ts, \"PST\").alias('local_time')).collect()\n [Row(local_time=datetime.datetime(1997, 2, 28, 2, 30))]\n >>> df.select(from_utc_timestamp(df.ts, df.tz).alias('local_time')).collect()\n [Row(local_time=datetime.datetime(1997, 2, 28, 19, 30))]\n\n .. note:: Deprecated in 3.0. See SPARK-25496\n \"\"\"\n warnings.warn(\"Deprecated in 3.0. See SPARK-25496\", DeprecationWarning)\n sc = SparkContext._active_spark_context\n if isinstance(tz, Column):\n tz = _to_java_column(tz)\n return Column(sc._jvm.functions.from_utc_timestamp(_to_java_column(timestamp), tz))" }, { "instruction": "Write or improve a Python function based on this description:\n\nBucketize rows into one or more time windows given a timestamp specifying column. Window\n starts are inclusive but the window ends are exclusive, e.g. 12:05 will be in the window\n [12:05,12:10) but not in [12:00,12:05). Windows can support microsecond precision. Windows in\n the order of months are not supported.\n\n The time column must be of :class:`pyspark.sql.types.TimestampType`.\n\n Durations are provided as strings, e.g. '1 second', '1 day 12 hours', '2 minutes'. Valid\n interval strings are 'week', 'day', 'hour', 'minute', 'second', 'millisecond', 'microsecond'.\n If the ``slideDuration`` is not provided, the windows will be tumbling windows.\n\n The startTime is the offset with respect to 1970-01-01 00:00:00 UTC with which to start\n window intervals. For example, in order to have hourly tumbling windows that start 15 minutes\n past the hour, e.g. 12:15-13:15, 13:15-14:15... provide `startTime` as `15 minutes`.\n\n The output column will be a struct called 'window' by default with the nested columns 'start'\n and 'end', where 'start' and 'end' will be of :class:`pyspark.sql.types.TimestampType`.\n\n >>> df = spark.createDataFrame([(\"2016-03-11 09:00:07\", 1)]).toDF(\"date\", \"val\")\n >>> w = df.groupBy(window(\"date\", \"5 seconds\")).agg(sum(\"val\").alias(\"sum\"))\n >>> w.select(w.window.start.cast(\"string\").alias(\"start\"),\n ... w.window.end.cast(\"string\").alias(\"end\"), \"sum\").collect()\n [Row(start=u'2016-03-11 09:00:05', end=u'2016-03-11 09:00:10', sum=1)]", "output": "def window(timeColumn, windowDuration, slideDuration=None, startTime=None):\n \"\"\"Bucketize rows into one or more time windows given a timestamp specifying column. Window\n starts are inclusive but the window ends are exclusive, e.g. 12:05 will be in the window\n [12:05,12:10) but not in [12:00,12:05). Windows can support microsecond precision. Windows in\n the order of months are not supported.\n\n The time column must be of :class:`pyspark.sql.types.TimestampType`.\n\n Durations are provided as strings, e.g. '1 second', '1 day 12 hours', '2 minutes'. Valid\n interval strings are 'week', 'day', 'hour', 'minute', 'second', 'millisecond', 'microsecond'.\n If the ``slideDuration`` is not provided, the windows will be tumbling windows.\n\n The startTime is the offset with respect to 1970-01-01 00:00:00 UTC with which to start\n window intervals. For example, in order to have hourly tumbling windows that start 15 minutes\n past the hour, e.g. 12:15-13:15, 13:15-14:15... provide `startTime` as `15 minutes`.\n\n The output column will be a struct called 'window' by default with the nested columns 'start'\n and 'end', where 'start' and 'end' will be of :class:`pyspark.sql.types.TimestampType`.\n\n >>> df = spark.createDataFrame([(\"2016-03-11 09:00:07\", 1)]).toDF(\"date\", \"val\")\n >>> w = df.groupBy(window(\"date\", \"5 seconds\")).agg(sum(\"val\").alias(\"sum\"))\n >>> w.select(w.window.start.cast(\"string\").alias(\"start\"),\n ... w.window.end.cast(\"string\").alias(\"end\"), \"sum\").collect()\n [Row(start=u'2016-03-11 09:00:05', end=u'2016-03-11 09:00:10', sum=1)]\n \"\"\"\n def check_string_field(field, fieldName):\n if not field or type(field) is not str:\n raise TypeError(\"%s should be provided as a string\" % fieldName)\n\n sc = SparkContext._active_spark_context\n time_col = _to_java_column(timeColumn)\n check_string_field(windowDuration, \"windowDuration\")\n if slideDuration and startTime:\n check_string_field(slideDuration, \"slideDuration\")\n check_string_field(startTime, \"startTime\")\n res = sc._jvm.functions.window(time_col, windowDuration, slideDuration, startTime)\n elif slideDuration:\n check_string_field(slideDuration, \"slideDuration\")\n res = sc._jvm.functions.window(time_col, windowDuration, slideDuration)\n elif startTime:\n check_string_field(startTime, \"startTime\")\n res = sc._jvm.functions.window(time_col, windowDuration, windowDuration, startTime)\n else:\n res = sc._jvm.functions.window(time_col, windowDuration)\n return Column(res)" }, { "instruction": "Write or improve a Python function based on this description:\n\nCalculates the hash code of given columns, and returns the result as an int column.\n\n >>> spark.createDataFrame([('ABC',)], ['a']).select(hash('a').alias('hash')).collect()\n [Row(hash=-757602832)]", "output": "def hash(*cols):\n \"\"\"Calculates the hash code of given columns, and returns the result as an int column.\n\n >>> spark.createDataFrame([('ABC',)], ['a']).select(hash('a').alias('hash')).collect()\n [Row(hash=-757602832)]\n \"\"\"\n sc = SparkContext._active_spark_context\n jc = sc._jvm.functions.hash(_to_seq(sc, cols, _to_java_column))\n return Column(jc)" }, { "instruction": "Write or improve a Python function based on this description:\n\nConcatenates multiple input string columns together into a single string column,\n using the given separator.\n\n >>> df = spark.createDataFrame([('abcd','123')], ['s', 'd'])\n >>> df.select(concat_ws('-', df.s, df.d).alias('s')).collect()\n [Row(s=u'abcd-123')]", "output": "def concat_ws(sep, *cols):\n \"\"\"\n Concatenates multiple input string columns together into a single string column,\n using the given separator.\n\n >>> df = spark.createDataFrame([('abcd','123')], ['s', 'd'])\n >>> df.select(concat_ws('-', df.s, df.d).alias('s')).collect()\n [Row(s=u'abcd-123')]\n \"\"\"\n sc = SparkContext._active_spark_context\n return Column(sc._jvm.functions.concat_ws(sep, _to_seq(sc, cols, _to_java_column)))" }, { "instruction": "Write or improve a Python function based on this description:\n\nComputes the first argument into a string from a binary using the provided character set\n (one of 'US-ASCII', 'ISO-8859-1', 'UTF-8', 'UTF-16BE', 'UTF-16LE', 'UTF-16').", "output": "def decode(col, charset):\n \"\"\"\n Computes the first argument into a string from a binary using the provided character set\n (one of 'US-ASCII', 'ISO-8859-1', 'UTF-8', 'UTF-16BE', 'UTF-16LE', 'UTF-16').\n \"\"\"\n sc = SparkContext._active_spark_context\n return Column(sc._jvm.functions.decode(_to_java_column(col), charset))" }, { "instruction": "Write or improve a Python function based on this description:\n\nFormats the number X to a format like '#,--#,--#.--', rounded to d decimal places\n with HALF_EVEN round mode, and returns the result as a string.\n\n :param col: the column name of the numeric value to be formatted\n :param d: the N decimal places\n\n >>> spark.createDataFrame([(5,)], ['a']).select(format_number('a', 4).alias('v')).collect()\n [Row(v=u'5.0000')]", "output": "def format_number(col, d):\n \"\"\"\n Formats the number X to a format like '#,--#,--#.--', rounded to d decimal places\n with HALF_EVEN round mode, and returns the result as a string.\n\n :param col: the column name of the numeric value to be formatted\n :param d: the N decimal places\n\n >>> spark.createDataFrame([(5,)], ['a']).select(format_number('a', 4).alias('v')).collect()\n [Row(v=u'5.0000')]\n \"\"\"\n sc = SparkContext._active_spark_context\n return Column(sc._jvm.functions.format_number(_to_java_column(col), d))" }, { "instruction": "Write or improve a Python function based on this description:\n\nFormats the arguments in printf-style and returns the result as a string column.\n\n :param col: the column name of the numeric value to be formatted\n :param d: the N decimal places\n\n >>> df = spark.createDataFrame([(5, \"hello\")], ['a', 'b'])\n >>> df.select(format_string('%d %s', df.a, df.b).alias('v')).collect()\n [Row(v=u'5 hello')]", "output": "def format_string(format, *cols):\n \"\"\"\n Formats the arguments in printf-style and returns the result as a string column.\n\n :param col: the column name of the numeric value to be formatted\n :param d: the N decimal places\n\n >>> df = spark.createDataFrame([(5, \"hello\")], ['a', 'b'])\n >>> df.select(format_string('%d %s', df.a, df.b).alias('v')).collect()\n [Row(v=u'5 hello')]\n \"\"\"\n sc = SparkContext._active_spark_context\n return Column(sc._jvm.functions.format_string(format, _to_seq(sc, cols, _to_java_column)))" }, { "instruction": "Write or improve a Python function based on this description:\n\nLocate the position of the first occurrence of substr column in the given string.\n Returns null if either of the arguments are null.\n\n .. note:: The position is not zero based, but 1 based index. Returns 0 if substr\n could not be found in str.\n\n >>> df = spark.createDataFrame([('abcd',)], ['s',])\n >>> df.select(instr(df.s, 'b').alias('s')).collect()\n [Row(s=2)]", "output": "def instr(str, substr):\n \"\"\"\n Locate the position of the first occurrence of substr column in the given string.\n Returns null if either of the arguments are null.\n\n .. note:: The position is not zero based, but 1 based index. Returns 0 if substr\n could not be found in str.\n\n >>> df = spark.createDataFrame([('abcd',)], ['s',])\n >>> df.select(instr(df.s, 'b').alias('s')).collect()\n [Row(s=2)]\n \"\"\"\n sc = SparkContext._active_spark_context\n return Column(sc._jvm.functions.instr(_to_java_column(str), substr))" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns the substring from string str before count occurrences of the delimiter delim.\n If count is positive, everything the left of the final delimiter (counting from left) is\n returned. If count is negative, every to the right of the final delimiter (counting from the\n right) is returned. substring_index performs a case-sensitive match when searching for delim.\n\n >>> df = spark.createDataFrame([('a.b.c.d',)], ['s'])\n >>> df.select(substring_index(df.s, '.', 2).alias('s')).collect()\n [Row(s=u'a.b')]\n >>> df.select(substring_index(df.s, '.', -3).alias('s')).collect()\n [Row(s=u'b.c.d')]", "output": "def substring_index(str, delim, count):\n \"\"\"\n Returns the substring from string str before count occurrences of the delimiter delim.\n If count is positive, everything the left of the final delimiter (counting from left) is\n returned. If count is negative, every to the right of the final delimiter (counting from the\n right) is returned. substring_index performs a case-sensitive match when searching for delim.\n\n >>> df = spark.createDataFrame([('a.b.c.d',)], ['s'])\n >>> df.select(substring_index(df.s, '.', 2).alias('s')).collect()\n [Row(s=u'a.b')]\n >>> df.select(substring_index(df.s, '.', -3).alias('s')).collect()\n [Row(s=u'b.c.d')]\n \"\"\"\n sc = SparkContext._active_spark_context\n return Column(sc._jvm.functions.substring_index(_to_java_column(str), delim, count))" }, { "instruction": "Write or improve a Python function based on this description:\n\nComputes the Levenshtein distance of the two given strings.\n\n >>> df0 = spark.createDataFrame([('kitten', 'sitting',)], ['l', 'r'])\n >>> df0.select(levenshtein('l', 'r').alias('d')).collect()\n [Row(d=3)]", "output": "def levenshtein(left, right):\n \"\"\"Computes the Levenshtein distance of the two given strings.\n\n >>> df0 = spark.createDataFrame([('kitten', 'sitting',)], ['l', 'r'])\n >>> df0.select(levenshtein('l', 'r').alias('d')).collect()\n [Row(d=3)]\n \"\"\"\n sc = SparkContext._active_spark_context\n jc = sc._jvm.functions.levenshtein(_to_java_column(left), _to_java_column(right))\n return Column(jc)" }, { "instruction": "Write or improve a Python function based on this description:\n\nLocate the position of the first occurrence of substr in a string column, after position pos.\n\n .. note:: The position is not zero based, but 1 based index. Returns 0 if substr\n could not be found in str.\n\n :param substr: a string\n :param str: a Column of :class:`pyspark.sql.types.StringType`\n :param pos: start position (zero based)\n\n >>> df = spark.createDataFrame([('abcd',)], ['s',])\n >>> df.select(locate('b', df.s, 1).alias('s')).collect()\n [Row(s=2)]", "output": "def locate(substr, str, pos=1):\n \"\"\"\n Locate the position of the first occurrence of substr in a string column, after position pos.\n\n .. note:: The position is not zero based, but 1 based index. Returns 0 if substr\n could not be found in str.\n\n :param substr: a string\n :param str: a Column of :class:`pyspark.sql.types.StringType`\n :param pos: start position (zero based)\n\n >>> df = spark.createDataFrame([('abcd',)], ['s',])\n >>> df.select(locate('b', df.s, 1).alias('s')).collect()\n [Row(s=2)]\n \"\"\"\n sc = SparkContext._active_spark_context\n return Column(sc._jvm.functions.locate(substr, _to_java_column(str), pos))" }, { "instruction": "Write or improve a Python function based on this description:\n\nLeft-pad the string column to width `len` with `pad`.\n\n >>> df = spark.createDataFrame([('abcd',)], ['s',])\n >>> df.select(lpad(df.s, 6, '#').alias('s')).collect()\n [Row(s=u'##abcd')]", "output": "def lpad(col, len, pad):\n \"\"\"\n Left-pad the string column to width `len` with `pad`.\n\n >>> df = spark.createDataFrame([('abcd',)], ['s',])\n >>> df.select(lpad(df.s, 6, '#').alias('s')).collect()\n [Row(s=u'##abcd')]\n \"\"\"\n sc = SparkContext._active_spark_context\n return Column(sc._jvm.functions.lpad(_to_java_column(col), len, pad))" }, { "instruction": "Write or improve a Python function based on this description:\n\nRepeats a string column n times, and returns it as a new string column.\n\n >>> df = spark.createDataFrame([('ab',)], ['s',])\n >>> df.select(repeat(df.s, 3).alias('s')).collect()\n [Row(s=u'ababab')]", "output": "def repeat(col, n):\n \"\"\"\n Repeats a string column n times, and returns it as a new string column.\n\n >>> df = spark.createDataFrame([('ab',)], ['s',])\n >>> df.select(repeat(df.s, 3).alias('s')).collect()\n [Row(s=u'ababab')]\n \"\"\"\n sc = SparkContext._active_spark_context\n return Column(sc._jvm.functions.repeat(_to_java_column(col), n))" }, { "instruction": "Write or improve a Python function based on this description:\n\nSplits str around matches of the given pattern.\n\n :param str: a string expression to split\n :param pattern: a string representing a regular expression. The regex string should be\n a Java regular expression.\n :param limit: an integer which controls the number of times `pattern` is applied.\n\n * ``limit > 0``: The resulting array's length will not be more than `limit`, and the\n resulting array's last entry will contain all input beyond the last\n matched pattern.\n * ``limit <= 0``: `pattern` will be applied as many times as possible, and the resulting\n array can be of any size.\n\n .. versionchanged:: 3.0\n `split` now takes an optional `limit` field. If not provided, default limit value is -1.\n\n >>> df = spark.createDataFrame([('oneAtwoBthreeC',)], ['s',])\n >>> df.select(split(df.s, '[ABC]', 2).alias('s')).collect()\n [Row(s=[u'one', u'twoBthreeC'])]\n >>> df.select(split(df.s, '[ABC]', -1).alias('s')).collect()\n [Row(s=[u'one', u'two', u'three', u''])]", "output": "def split(str, pattern, limit=-1):\n \"\"\"\n Splits str around matches of the given pattern.\n\n :param str: a string expression to split\n :param pattern: a string representing a regular expression. The regex string should be\n a Java regular expression.\n :param limit: an integer which controls the number of times `pattern` is applied.\n\n * ``limit > 0``: The resulting array's length will not be more than `limit`, and the\n resulting array's last entry will contain all input beyond the last\n matched pattern.\n * ``limit <= 0``: `pattern` will be applied as many times as possible, and the resulting\n array can be of any size.\n\n .. versionchanged:: 3.0\n `split` now takes an optional `limit` field. If not provided, default limit value is -1.\n\n >>> df = spark.createDataFrame([('oneAtwoBthreeC',)], ['s',])\n >>> df.select(split(df.s, '[ABC]', 2).alias('s')).collect()\n [Row(s=[u'one', u'twoBthreeC'])]\n >>> df.select(split(df.s, '[ABC]', -1).alias('s')).collect()\n [Row(s=[u'one', u'two', u'three', u''])]\n \"\"\"\n sc = SparkContext._active_spark_context\n return Column(sc._jvm.functions.split(_to_java_column(str), pattern, limit))" }, { "instruction": "Write or improve a Python function based on this description:\n\nr\"\"\"Extract a specific group matched by a Java regex, from the specified string column.\n If the regex did not match, or the specified group did not match, an empty string is returned.\n\n >>> df = spark.createDataFrame([('100-200',)], ['str'])\n >>> df.select(regexp_extract('str', r'(\\d+)-(\\d+)', 1).alias('d')).collect()\n [Row(d=u'100')]\n >>> df = spark.createDataFrame([('foo',)], ['str'])\n >>> df.select(regexp_extract('str', r'(\\d+)', 1).alias('d')).collect()\n [Row(d=u'')]\n >>> df = spark.createDataFrame([('aaaac',)], ['str'])\n >>> df.select(regexp_extract('str', '(a+)(b)?(c)', 2).alias('d')).collect()\n [Row(d=u'')]", "output": "def regexp_extract(str, pattern, idx):\n r\"\"\"Extract a specific group matched by a Java regex, from the specified string column.\n If the regex did not match, or the specified group did not match, an empty string is returned.\n\n >>> df = spark.createDataFrame([('100-200',)], ['str'])\n >>> df.select(regexp_extract('str', r'(\\d+)-(\\d+)', 1).alias('d')).collect()\n [Row(d=u'100')]\n >>> df = spark.createDataFrame([('foo',)], ['str'])\n >>> df.select(regexp_extract('str', r'(\\d+)', 1).alias('d')).collect()\n [Row(d=u'')]\n >>> df = spark.createDataFrame([('aaaac',)], ['str'])\n >>> df.select(regexp_extract('str', '(a+)(b)?(c)', 2).alias('d')).collect()\n [Row(d=u'')]\n \"\"\"\n sc = SparkContext._active_spark_context\n jc = sc._jvm.functions.regexp_extract(_to_java_column(str), pattern, idx)\n return Column(jc)" }, { "instruction": "Write or improve a Python function based on this description:\n\nr\"\"\"Replace all substrings of the specified string value that match regexp with rep.\n\n >>> df = spark.createDataFrame([('100-200',)], ['str'])\n >>> df.select(regexp_replace('str', r'(\\d+)', '--').alias('d')).collect()\n [Row(d=u'-----')]", "output": "def regexp_replace(str, pattern, replacement):\n r\"\"\"Replace all substrings of the specified string value that match regexp with rep.\n\n >>> df = spark.createDataFrame([('100-200',)], ['str'])\n >>> df.select(regexp_replace('str', r'(\\d+)', '--').alias('d')).collect()\n [Row(d=u'-----')]\n \"\"\"\n sc = SparkContext._active_spark_context\n jc = sc._jvm.functions.regexp_replace(_to_java_column(str), pattern, replacement)\n return Column(jc)" }, { "instruction": "Write or improve a Python function based on this description:\n\nA function translate any character in the `srcCol` by a character in `matching`.\n The characters in `replace` is corresponding to the characters in `matching`.\n The translate will happen when any character in the string matching with the character\n in the `matching`.\n\n >>> spark.createDataFrame([('translate',)], ['a']).select(translate('a', \"rnlt\", \"123\") \\\\\n ... .alias('r')).collect()\n [Row(r=u'1a2s3ae')]", "output": "def translate(srcCol, matching, replace):\n \"\"\"A function translate any character in the `srcCol` by a character in `matching`.\n The characters in `replace` is corresponding to the characters in `matching`.\n The translate will happen when any character in the string matching with the character\n in the `matching`.\n\n >>> spark.createDataFrame([('translate',)], ['a']).select(translate('a', \"rnlt\", \"123\") \\\\\n ... .alias('r')).collect()\n [Row(r=u'1a2s3ae')]\n \"\"\"\n sc = SparkContext._active_spark_context\n return Column(sc._jvm.functions.translate(_to_java_column(srcCol), matching, replace))" }, { "instruction": "Write or improve a Python function based on this description:\n\nCollection function: returns true if the arrays contain any common non-null element; if not,\n returns null if both the arrays are non-empty and any of them contains a null element; returns\n false otherwise.\n\n >>> df = spark.createDataFrame([([\"a\", \"b\"], [\"b\", \"c\"]), ([\"a\"], [\"b\", \"c\"])], ['x', 'y'])\n >>> df.select(arrays_overlap(df.x, df.y).alias(\"overlap\")).collect()\n [Row(overlap=True), Row(overlap=False)]", "output": "def arrays_overlap(a1, a2):\n \"\"\"\n Collection function: returns true if the arrays contain any common non-null element; if not,\n returns null if both the arrays are non-empty and any of them contains a null element; returns\n false otherwise.\n\n >>> df = spark.createDataFrame([([\"a\", \"b\"], [\"b\", \"c\"]), ([\"a\"], [\"b\", \"c\"])], ['x', 'y'])\n >>> df.select(arrays_overlap(df.x, df.y).alias(\"overlap\")).collect()\n [Row(overlap=True), Row(overlap=False)]\n \"\"\"\n sc = SparkContext._active_spark_context\n return Column(sc._jvm.functions.arrays_overlap(_to_java_column(a1), _to_java_column(a2)))" }, { "instruction": "Write or improve a Python function based on this description:\n\nCollection function: returns an array containing all the elements in `x` from index `start`\n (or starting from the end if `start` is negative) with the specified `length`.\n >>> df = spark.createDataFrame([([1, 2, 3],), ([4, 5],)], ['x'])\n >>> df.select(slice(df.x, 2, 2).alias(\"sliced\")).collect()\n [Row(sliced=[2, 3]), Row(sliced=[5])]", "output": "def slice(x, start, length):\n \"\"\"\n Collection function: returns an array containing all the elements in `x` from index `start`\n (or starting from the end if `start` is negative) with the specified `length`.\n >>> df = spark.createDataFrame([([1, 2, 3],), ([4, 5],)], ['x'])\n >>> df.select(slice(df.x, 2, 2).alias(\"sliced\")).collect()\n [Row(sliced=[2, 3]), Row(sliced=[5])]\n \"\"\"\n sc = SparkContext._active_spark_context\n return Column(sc._jvm.functions.slice(_to_java_column(x), start, length))" }, { "instruction": "Write or improve a Python function based on this description:\n\nConcatenates the elements of `column` using the `delimiter`. Null values are replaced with\n `null_replacement` if set, otherwise they are ignored.\n\n >>> df = spark.createDataFrame([([\"a\", \"b\", \"c\"],), ([\"a\", None],)], ['data'])\n >>> df.select(array_join(df.data, \",\").alias(\"joined\")).collect()\n [Row(joined=u'a,b,c'), Row(joined=u'a')]\n >>> df.select(array_join(df.data, \",\", \"NULL\").alias(\"joined\")).collect()\n [Row(joined=u'a,b,c'), Row(joined=u'a,NULL')]", "output": "def array_join(col, delimiter, null_replacement=None):\n \"\"\"\n Concatenates the elements of `column` using the `delimiter`. Null values are replaced with\n `null_replacement` if set, otherwise they are ignored.\n\n >>> df = spark.createDataFrame([([\"a\", \"b\", \"c\"],), ([\"a\", None],)], ['data'])\n >>> df.select(array_join(df.data, \",\").alias(\"joined\")).collect()\n [Row(joined=u'a,b,c'), Row(joined=u'a')]\n >>> df.select(array_join(df.data, \",\", \"NULL\").alias(\"joined\")).collect()\n [Row(joined=u'a,b,c'), Row(joined=u'a,NULL')]\n \"\"\"\n sc = SparkContext._active_spark_context\n if null_replacement is None:\n return Column(sc._jvm.functions.array_join(_to_java_column(col), delimiter))\n else:\n return Column(sc._jvm.functions.array_join(\n _to_java_column(col), delimiter, null_replacement))" }, { "instruction": "Write or improve a Python function based on this description:\n\nConcatenates multiple input columns together into a single column.\n The function works with strings, binary and compatible array columns.\n\n >>> df = spark.createDataFrame([('abcd','123')], ['s', 'd'])\n >>> df.select(concat(df.s, df.d).alias('s')).collect()\n [Row(s=u'abcd123')]\n\n >>> df = spark.createDataFrame([([1, 2], [3, 4], [5]), ([1, 2], None, [3])], ['a', 'b', 'c'])\n >>> df.select(concat(df.a, df.b, df.c).alias(\"arr\")).collect()\n [Row(arr=[1, 2, 3, 4, 5]), Row(arr=None)]", "output": "def concat(*cols):\n \"\"\"\n Concatenates multiple input columns together into a single column.\n The function works with strings, binary and compatible array columns.\n\n >>> df = spark.createDataFrame([('abcd','123')], ['s', 'd'])\n >>> df.select(concat(df.s, df.d).alias('s')).collect()\n [Row(s=u'abcd123')]\n\n >>> df = spark.createDataFrame([([1, 2], [3, 4], [5]), ([1, 2], None, [3])], ['a', 'b', 'c'])\n >>> df.select(concat(df.a, df.b, df.c).alias(\"arr\")).collect()\n [Row(arr=[1, 2, 3, 4, 5]), Row(arr=None)]\n \"\"\"\n sc = SparkContext._active_spark_context\n return Column(sc._jvm.functions.concat(_to_seq(sc, cols, _to_java_column)))" }, { "instruction": "Write or improve a Python function based on this description:\n\nCollection function: Locates the position of the first occurrence of the given value\n in the given array. Returns null if either of the arguments are null.\n\n .. note:: The position is not zero based, but 1 based index. Returns 0 if the given\n value could not be found in the array.\n\n >>> df = spark.createDataFrame([([\"c\", \"b\", \"a\"],), ([],)], ['data'])\n >>> df.select(array_position(df.data, \"a\")).collect()\n [Row(array_position(data, a)=3), Row(array_position(data, a)=0)]", "output": "def array_position(col, value):\n \"\"\"\n Collection function: Locates the position of the first occurrence of the given value\n in the given array. Returns null if either of the arguments are null.\n\n .. note:: The position is not zero based, but 1 based index. Returns 0 if the given\n value could not be found in the array.\n\n >>> df = spark.createDataFrame([([\"c\", \"b\", \"a\"],), ([],)], ['data'])\n >>> df.select(array_position(df.data, \"a\")).collect()\n [Row(array_position(data, a)=3), Row(array_position(data, a)=0)]\n \"\"\"\n sc = SparkContext._active_spark_context\n return Column(sc._jvm.functions.array_position(_to_java_column(col), value))" }, { "instruction": "Write or improve a Python function based on this description:\n\nCollection function: Returns element of array at given index in extraction if col is array.\n Returns value for the given key in extraction if col is map.\n\n :param col: name of column containing array or map\n :param extraction: index to check for in array or key to check for in map\n\n .. note:: The position is not zero based, but 1 based index.\n\n >>> df = spark.createDataFrame([([\"a\", \"b\", \"c\"],), ([],)], ['data'])\n >>> df.select(element_at(df.data, 1)).collect()\n [Row(element_at(data, 1)=u'a'), Row(element_at(data, 1)=None)]\n\n >>> df = spark.createDataFrame([({\"a\": 1.0, \"b\": 2.0},), ({},)], ['data'])\n >>> df.select(element_at(df.data, \"a\")).collect()\n [Row(element_at(data, a)=1.0), Row(element_at(data, a)=None)]", "output": "def element_at(col, extraction):\n \"\"\"\n Collection function: Returns element of array at given index in extraction if col is array.\n Returns value for the given key in extraction if col is map.\n\n :param col: name of column containing array or map\n :param extraction: index to check for in array or key to check for in map\n\n .. note:: The position is not zero based, but 1 based index.\n\n >>> df = spark.createDataFrame([([\"a\", \"b\", \"c\"],), ([],)], ['data'])\n >>> df.select(element_at(df.data, 1)).collect()\n [Row(element_at(data, 1)=u'a'), Row(element_at(data, 1)=None)]\n\n >>> df = spark.createDataFrame([({\"a\": 1.0, \"b\": 2.0},), ({},)], ['data'])\n >>> df.select(element_at(df.data, \"a\")).collect()\n [Row(element_at(data, a)=1.0), Row(element_at(data, a)=None)]\n \"\"\"\n sc = SparkContext._active_spark_context\n return Column(sc._jvm.functions.element_at(_to_java_column(col), extraction))" }, { "instruction": "Write or improve a Python function based on this description:\n\nCollection function: Remove all elements that equal to element from the given array.\n\n :param col: name of column containing array\n :param element: element to be removed from the array\n\n >>> df = spark.createDataFrame([([1, 2, 3, 1, 1],), ([],)], ['data'])\n >>> df.select(array_remove(df.data, 1)).collect()\n [Row(array_remove(data, 1)=[2, 3]), Row(array_remove(data, 1)=[])]", "output": "def array_remove(col, element):\n \"\"\"\n Collection function: Remove all elements that equal to element from the given array.\n\n :param col: name of column containing array\n :param element: element to be removed from the array\n\n >>> df = spark.createDataFrame([([1, 2, 3, 1, 1],), ([],)], ['data'])\n >>> df.select(array_remove(df.data, 1)).collect()\n [Row(array_remove(data, 1)=[2, 3]), Row(array_remove(data, 1)=[])]\n \"\"\"\n sc = SparkContext._active_spark_context\n return Column(sc._jvm.functions.array_remove(_to_java_column(col), element))" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns a new row for each element in the given array or map.\n Uses the default column name `col` for elements in the array and\n `key` and `value` for elements in the map unless specified otherwise.\n\n >>> from pyspark.sql import Row\n >>> eDF = spark.createDataFrame([Row(a=1, intlist=[1,2,3], mapfield={\"a\": \"b\"})])\n >>> eDF.select(explode(eDF.intlist).alias(\"anInt\")).collect()\n [Row(anInt=1), Row(anInt=2), Row(anInt=3)]\n\n >>> eDF.select(explode(eDF.mapfield).alias(\"key\", \"value\")).show()\n +---+-----+\n |key|value|\n +---+-----+\n | a| b|\n +---+-----+", "output": "def explode(col):\n \"\"\"\n Returns a new row for each element in the given array or map.\n Uses the default column name `col` for elements in the array and\n `key` and `value` for elements in the map unless specified otherwise.\n\n >>> from pyspark.sql import Row\n >>> eDF = spark.createDataFrame([Row(a=1, intlist=[1,2,3], mapfield={\"a\": \"b\"})])\n >>> eDF.select(explode(eDF.intlist).alias(\"anInt\")).collect()\n [Row(anInt=1), Row(anInt=2), Row(anInt=3)]\n\n >>> eDF.select(explode(eDF.mapfield).alias(\"key\", \"value\")).show()\n +---+-----+\n |key|value|\n +---+-----+\n | a| b|\n +---+-----+\n \"\"\"\n sc = SparkContext._active_spark_context\n jc = sc._jvm.functions.explode(_to_java_column(col))\n return Column(jc)" }, { "instruction": "Write or improve a Python function based on this description:\n\nExtracts json object from a json string based on json path specified, and returns json string\n of the extracted json object. It will return null if the input json string is invalid.\n\n :param col: string column in json format\n :param path: path to the json object to extract\n\n >>> data = [(\"1\", '''{\"f1\": \"value1\", \"f2\": \"value2\"}'''), (\"2\", '''{\"f1\": \"value12\"}''')]\n >>> df = spark.createDataFrame(data, (\"key\", \"jstring\"))\n >>> df.select(df.key, get_json_object(df.jstring, '$.f1').alias(\"c0\"), \\\\\n ... get_json_object(df.jstring, '$.f2').alias(\"c1\") ).collect()\n [Row(key=u'1', c0=u'value1', c1=u'value2'), Row(key=u'2', c0=u'value12', c1=None)]", "output": "def get_json_object(col, path):\n \"\"\"\n Extracts json object from a json string based on json path specified, and returns json string\n of the extracted json object. It will return null if the input json string is invalid.\n\n :param col: string column in json format\n :param path: path to the json object to extract\n\n >>> data = [(\"1\", '''{\"f1\": \"value1\", \"f2\": \"value2\"}'''), (\"2\", '''{\"f1\": \"value12\"}''')]\n >>> df = spark.createDataFrame(data, (\"key\", \"jstring\"))\n >>> df.select(df.key, get_json_object(df.jstring, '$.f1').alias(\"c0\"), \\\\\n ... get_json_object(df.jstring, '$.f2').alias(\"c1\") ).collect()\n [Row(key=u'1', c0=u'value1', c1=u'value2'), Row(key=u'2', c0=u'value12', c1=None)]\n \"\"\"\n sc = SparkContext._active_spark_context\n jc = sc._jvm.functions.get_json_object(_to_java_column(col), path)\n return Column(jc)" }, { "instruction": "Write or improve a Python function based on this description:\n\nCreates a new row for a json column according to the given field names.\n\n :param col: string column in json format\n :param fields: list of fields to extract\n\n >>> data = [(\"1\", '''{\"f1\": \"value1\", \"f2\": \"value2\"}'''), (\"2\", '''{\"f1\": \"value12\"}''')]\n >>> df = spark.createDataFrame(data, (\"key\", \"jstring\"))\n >>> df.select(df.key, json_tuple(df.jstring, 'f1', 'f2')).collect()\n [Row(key=u'1', c0=u'value1', c1=u'value2'), Row(key=u'2', c0=u'value12', c1=None)]", "output": "def json_tuple(col, *fields):\n \"\"\"Creates a new row for a json column according to the given field names.\n\n :param col: string column in json format\n :param fields: list of fields to extract\n\n >>> data = [(\"1\", '''{\"f1\": \"value1\", \"f2\": \"value2\"}'''), (\"2\", '''{\"f1\": \"value12\"}''')]\n >>> df = spark.createDataFrame(data, (\"key\", \"jstring\"))\n >>> df.select(df.key, json_tuple(df.jstring, 'f1', 'f2')).collect()\n [Row(key=u'1', c0=u'value1', c1=u'value2'), Row(key=u'2', c0=u'value12', c1=None)]\n \"\"\"\n sc = SparkContext._active_spark_context\n jc = sc._jvm.functions.json_tuple(_to_java_column(col), _to_seq(sc, fields))\n return Column(jc)" }, { "instruction": "Write or improve a Python function based on this description:\n\nParses a JSON string and infers its schema in DDL format.\n\n :param json: a JSON string or a string literal containing a JSON string.\n :param options: options to control parsing. accepts the same options as the JSON datasource\n\n .. versionchanged:: 3.0\n It accepts `options` parameter to control schema inferring.\n\n >>> df = spark.range(1)\n >>> df.select(schema_of_json(lit('{\"a\": 0}')).alias(\"json\")).collect()\n [Row(json=u'struct')]\n >>> schema = schema_of_json('{a: 1}', {'allowUnquotedFieldNames':'true'})\n >>> df.select(schema.alias(\"json\")).collect()\n [Row(json=u'struct')]", "output": "def schema_of_json(json, options={}):\n \"\"\"\n Parses a JSON string and infers its schema in DDL format.\n\n :param json: a JSON string or a string literal containing a JSON string.\n :param options: options to control parsing. accepts the same options as the JSON datasource\n\n .. versionchanged:: 3.0\n It accepts `options` parameter to control schema inferring.\n\n >>> df = spark.range(1)\n >>> df.select(schema_of_json(lit('{\"a\": 0}')).alias(\"json\")).collect()\n [Row(json=u'struct')]\n >>> schema = schema_of_json('{a: 1}', {'allowUnquotedFieldNames':'true'})\n >>> df.select(schema.alias(\"json\")).collect()\n [Row(json=u'struct')]\n \"\"\"\n if isinstance(json, basestring):\n col = _create_column_from_literal(json)\n elif isinstance(json, Column):\n col = _to_java_column(json)\n else:\n raise TypeError(\"schema argument should be a column or string\")\n\n sc = SparkContext._active_spark_context\n jc = sc._jvm.functions.schema_of_json(col, options)\n return Column(jc)" }, { "instruction": "Write or improve a Python function based on this description:\n\nParses a CSV string and infers its schema in DDL format.\n\n :param col: a CSV string or a string literal containing a CSV string.\n :param options: options to control parsing. accepts the same options as the CSV datasource\n\n >>> df = spark.range(1)\n >>> df.select(schema_of_csv(lit('1|a'), {'sep':'|'}).alias(\"csv\")).collect()\n [Row(csv=u'struct<_c0:int,_c1:string>')]\n >>> df.select(schema_of_csv('1|a', {'sep':'|'}).alias(\"csv\")).collect()\n [Row(csv=u'struct<_c0:int,_c1:string>')]", "output": "def schema_of_csv(csv, options={}):\n \"\"\"\n Parses a CSV string and infers its schema in DDL format.\n\n :param col: a CSV string or a string literal containing a CSV string.\n :param options: options to control parsing. accepts the same options as the CSV datasource\n\n >>> df = spark.range(1)\n >>> df.select(schema_of_csv(lit('1|a'), {'sep':'|'}).alias(\"csv\")).collect()\n [Row(csv=u'struct<_c0:int,_c1:string>')]\n >>> df.select(schema_of_csv('1|a', {'sep':'|'}).alias(\"csv\")).collect()\n [Row(csv=u'struct<_c0:int,_c1:string>')]\n \"\"\"\n if isinstance(csv, basestring):\n col = _create_column_from_literal(csv)\n elif isinstance(csv, Column):\n col = _to_java_column(csv)\n else:\n raise TypeError(\"schema argument should be a column or string\")\n\n sc = SparkContext._active_spark_context\n jc = sc._jvm.functions.schema_of_csv(col, options)\n return Column(jc)" }, { "instruction": "Write or improve a Python function based on this description:\n\nConverts a column containing a :class:`StructType` into a CSV string.\n Throws an exception, in the case of an unsupported type.\n\n :param col: name of column containing a struct.\n :param options: options to control converting. accepts the same options as the CSV datasource.\n\n >>> from pyspark.sql import Row\n >>> data = [(1, Row(name='Alice', age=2))]\n >>> df = spark.createDataFrame(data, (\"key\", \"value\"))\n >>> df.select(to_csv(df.value).alias(\"csv\")).collect()\n [Row(csv=u'2,Alice')]", "output": "def to_csv(col, options={}):\n \"\"\"\n Converts a column containing a :class:`StructType` into a CSV string.\n Throws an exception, in the case of an unsupported type.\n\n :param col: name of column containing a struct.\n :param options: options to control converting. accepts the same options as the CSV datasource.\n\n >>> from pyspark.sql import Row\n >>> data = [(1, Row(name='Alice', age=2))]\n >>> df = spark.createDataFrame(data, (\"key\", \"value\"))\n >>> df.select(to_csv(df.value).alias(\"csv\")).collect()\n [Row(csv=u'2,Alice')]\n \"\"\"\n\n sc = SparkContext._active_spark_context\n jc = sc._jvm.functions.to_csv(_to_java_column(col), options)\n return Column(jc)" }, { "instruction": "Write or improve a Python function based on this description:\n\nCollection function: returns the length of the array or map stored in the column.\n\n :param col: name of column or expression\n\n >>> df = spark.createDataFrame([([1, 2, 3],),([1],),([],)], ['data'])\n >>> df.select(size(df.data)).collect()\n [Row(size(data)=3), Row(size(data)=1), Row(size(data)=0)]", "output": "def size(col):\n \"\"\"\n Collection function: returns the length of the array or map stored in the column.\n\n :param col: name of column or expression\n\n >>> df = spark.createDataFrame([([1, 2, 3],),([1],),([],)], ['data'])\n >>> df.select(size(df.data)).collect()\n [Row(size(data)=3), Row(size(data)=1), Row(size(data)=0)]\n \"\"\"\n sc = SparkContext._active_spark_context\n return Column(sc._jvm.functions.size(_to_java_column(col)))" }, { "instruction": "Write or improve a Python function based on this description:\n\nCollection function: sorts the input array in ascending or descending order according\n to the natural ordering of the array elements. Null elements will be placed at the beginning\n of the returned array in ascending order or at the end of the returned array in descending\n order.\n\n :param col: name of column or expression\n\n >>> df = spark.createDataFrame([([2, 1, None, 3],),([1],),([],)], ['data'])\n >>> df.select(sort_array(df.data).alias('r')).collect()\n [Row(r=[None, 1, 2, 3]), Row(r=[1]), Row(r=[])]\n >>> df.select(sort_array(df.data, asc=False).alias('r')).collect()\n [Row(r=[3, 2, 1, None]), Row(r=[1]), Row(r=[])]", "output": "def sort_array(col, asc=True):\n \"\"\"\n Collection function: sorts the input array in ascending or descending order according\n to the natural ordering of the array elements. Null elements will be placed at the beginning\n of the returned array in ascending order or at the end of the returned array in descending\n order.\n\n :param col: name of column or expression\n\n >>> df = spark.createDataFrame([([2, 1, None, 3],),([1],),([],)], ['data'])\n >>> df.select(sort_array(df.data).alias('r')).collect()\n [Row(r=[None, 1, 2, 3]), Row(r=[1]), Row(r=[])]\n >>> df.select(sort_array(df.data, asc=False).alias('r')).collect()\n [Row(r=[3, 2, 1, None]), Row(r=[1]), Row(r=[])]\n \"\"\"\n sc = SparkContext._active_spark_context\n return Column(sc._jvm.functions.sort_array(_to_java_column(col), asc))" }, { "instruction": "Write or improve a Python function based on this description:\n\nCollection function: creates an array containing a column repeated count times.\n\n >>> df = spark.createDataFrame([('ab',)], ['data'])\n >>> df.select(array_repeat(df.data, 3).alias('r')).collect()\n [Row(r=[u'ab', u'ab', u'ab'])]", "output": "def array_repeat(col, count):\n \"\"\"\n Collection function: creates an array containing a column repeated count times.\n\n >>> df = spark.createDataFrame([('ab',)], ['data'])\n >>> df.select(array_repeat(df.data, 3).alias('r')).collect()\n [Row(r=[u'ab', u'ab', u'ab'])]\n \"\"\"\n sc = SparkContext._active_spark_context\n return Column(sc._jvm.functions.array_repeat(_to_java_column(col), count))" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns the union of all the given maps.\n\n :param cols: list of column names (string) or list of :class:`Column` expressions\n\n >>> from pyspark.sql.functions import map_concat\n >>> df = spark.sql(\"SELECT map(1, 'a', 2, 'b') as map1, map(3, 'c', 1, 'd') as map2\")\n >>> df.select(map_concat(\"map1\", \"map2\").alias(\"map3\")).show(truncate=False)\n +------------------------+\n |map3 |\n +------------------------+\n |[1 -> d, 2 -> b, 3 -> c]|\n +------------------------+", "output": "def map_concat(*cols):\n \"\"\"Returns the union of all the given maps.\n\n :param cols: list of column names (string) or list of :class:`Column` expressions\n\n >>> from pyspark.sql.functions import map_concat\n >>> df = spark.sql(\"SELECT map(1, 'a', 2, 'b') as map1, map(3, 'c', 1, 'd') as map2\")\n >>> df.select(map_concat(\"map1\", \"map2\").alias(\"map3\")).show(truncate=False)\n +------------------------+\n |map3 |\n +------------------------+\n |[1 -> d, 2 -> b, 3 -> c]|\n +------------------------+\n \"\"\"\n sc = SparkContext._active_spark_context\n if len(cols) == 1 and isinstance(cols[0], (list, set)):\n cols = cols[0]\n jc = sc._jvm.functions.map_concat(_to_seq(sc, cols, _to_java_column))\n return Column(jc)" }, { "instruction": "Write or improve a Python function based on this description:\n\nGenerate a sequence of integers from `start` to `stop`, incrementing by `step`.\n If `step` is not set, incrementing by 1 if `start` is less than or equal to `stop`,\n otherwise -1.\n\n >>> df1 = spark.createDataFrame([(-2, 2)], ('C1', 'C2'))\n >>> df1.select(sequence('C1', 'C2').alias('r')).collect()\n [Row(r=[-2, -1, 0, 1, 2])]\n >>> df2 = spark.createDataFrame([(4, -4, -2)], ('C1', 'C2', 'C3'))\n >>> df2.select(sequence('C1', 'C2', 'C3').alias('r')).collect()\n [Row(r=[4, 2, 0, -2, -4])]", "output": "def sequence(start, stop, step=None):\n \"\"\"\n Generate a sequence of integers from `start` to `stop`, incrementing by `step`.\n If `step` is not set, incrementing by 1 if `start` is less than or equal to `stop`,\n otherwise -1.\n\n >>> df1 = spark.createDataFrame([(-2, 2)], ('C1', 'C2'))\n >>> df1.select(sequence('C1', 'C2').alias('r')).collect()\n [Row(r=[-2, -1, 0, 1, 2])]\n >>> df2 = spark.createDataFrame([(4, -4, -2)], ('C1', 'C2', 'C3'))\n >>> df2.select(sequence('C1', 'C2', 'C3').alias('r')).collect()\n [Row(r=[4, 2, 0, -2, -4])]\n \"\"\"\n sc = SparkContext._active_spark_context\n if step is None:\n return Column(sc._jvm.functions.sequence(_to_java_column(start), _to_java_column(stop)))\n else:\n return Column(sc._jvm.functions.sequence(\n _to_java_column(start), _to_java_column(stop), _to_java_column(step)))" }, { "instruction": "Write or improve a Python function based on this description:\n\nParses a column containing a CSV string to a row with the specified schema.\n Returns `null`, in the case of an unparseable string.\n\n :param col: string column in CSV format\n :param schema: a string with schema in DDL format to use when parsing the CSV column.\n :param options: options to control parsing. accepts the same options as the CSV datasource\n\n >>> data = [(\"1,2,3\",)]\n >>> df = spark.createDataFrame(data, (\"value\",))\n >>> df.select(from_csv(df.value, \"a INT, b INT, c INT\").alias(\"csv\")).collect()\n [Row(csv=Row(a=1, b=2, c=3))]\n >>> value = data[0][0]\n >>> df.select(from_csv(df.value, schema_of_csv(value)).alias(\"csv\")).collect()\n [Row(csv=Row(_c0=1, _c1=2, _c2=3))]", "output": "def from_csv(col, schema, options={}):\n \"\"\"\n Parses a column containing a CSV string to a row with the specified schema.\n Returns `null`, in the case of an unparseable string.\n\n :param col: string column in CSV format\n :param schema: a string with schema in DDL format to use when parsing the CSV column.\n :param options: options to control parsing. accepts the same options as the CSV datasource\n\n >>> data = [(\"1,2,3\",)]\n >>> df = spark.createDataFrame(data, (\"value\",))\n >>> df.select(from_csv(df.value, \"a INT, b INT, c INT\").alias(\"csv\")).collect()\n [Row(csv=Row(a=1, b=2, c=3))]\n >>> value = data[0][0]\n >>> df.select(from_csv(df.value, schema_of_csv(value)).alias(\"csv\")).collect()\n [Row(csv=Row(_c0=1, _c1=2, _c2=3))]\n \"\"\"\n\n sc = SparkContext._active_spark_context\n if isinstance(schema, basestring):\n schema = _create_column_from_literal(schema)\n elif isinstance(schema, Column):\n schema = _to_java_column(schema)\n else:\n raise TypeError(\"schema argument should be a column or string\")\n\n jc = sc._jvm.functions.from_csv(_to_java_column(col), schema, options)\n return Column(jc)" }, { "instruction": "Write or improve a Python function based on this description:\n\nCreates a user defined function (UDF).\n\n .. note:: The user-defined functions are considered deterministic by default. Due to\n optimization, duplicate invocations may be eliminated or the function may even be invoked\n more times than it is present in the query. If your function is not deterministic, call\n `asNondeterministic` on the user defined function. E.g.:\n\n >>> from pyspark.sql.types import IntegerType\n >>> import random\n >>> random_udf = udf(lambda: int(random.random() * 100), IntegerType()).asNondeterministic()\n\n .. note:: The user-defined functions do not support conditional expressions or short circuiting\n in boolean expressions and it ends up with being executed all internally. If the functions\n can fail on special rows, the workaround is to incorporate the condition into the functions.\n\n .. note:: The user-defined functions do not take keyword arguments on the calling side.\n\n :param f: python function if used as a standalone function\n :param returnType: the return type of the user-defined function. The value can be either a\n :class:`pyspark.sql.types.DataType` object or a DDL-formatted type string.\n\n >>> from pyspark.sql.types import IntegerType\n >>> slen = udf(lambda s: len(s), IntegerType())\n >>> @udf\n ... def to_upper(s):\n ... if s is not None:\n ... return s.upper()\n ...\n >>> @udf(returnType=IntegerType())\n ... def add_one(x):\n ... if x is not None:\n ... return x + 1\n ...\n >>> df = spark.createDataFrame([(1, \"John Doe\", 21)], (\"id\", \"name\", \"age\"))\n >>> df.select(slen(\"name\").alias(\"slen(name)\"), to_upper(\"name\"), add_one(\"age\")).show()\n +----------+--------------+------------+\n |slen(name)|to_upper(name)|add_one(age)|\n +----------+--------------+------------+\n | 8| JOHN DOE| 22|\n +----------+--------------+------------+", "output": "def udf(f=None, returnType=StringType()):\n \"\"\"Creates a user defined function (UDF).\n\n .. note:: The user-defined functions are considered deterministic by default. Due to\n optimization, duplicate invocations may be eliminated or the function may even be invoked\n more times than it is present in the query. If your function is not deterministic, call\n `asNondeterministic` on the user defined function. E.g.:\n\n >>> from pyspark.sql.types import IntegerType\n >>> import random\n >>> random_udf = udf(lambda: int(random.random() * 100), IntegerType()).asNondeterministic()\n\n .. note:: The user-defined functions do not support conditional expressions or short circuiting\n in boolean expressions and it ends up with being executed all internally. If the functions\n can fail on special rows, the workaround is to incorporate the condition into the functions.\n\n .. note:: The user-defined functions do not take keyword arguments on the calling side.\n\n :param f: python function if used as a standalone function\n :param returnType: the return type of the user-defined function. The value can be either a\n :class:`pyspark.sql.types.DataType` object or a DDL-formatted type string.\n\n >>> from pyspark.sql.types import IntegerType\n >>> slen = udf(lambda s: len(s), IntegerType())\n >>> @udf\n ... def to_upper(s):\n ... if s is not None:\n ... return s.upper()\n ...\n >>> @udf(returnType=IntegerType())\n ... def add_one(x):\n ... if x is not None:\n ... return x + 1\n ...\n >>> df = spark.createDataFrame([(1, \"John Doe\", 21)], (\"id\", \"name\", \"age\"))\n >>> df.select(slen(\"name\").alias(\"slen(name)\"), to_upper(\"name\"), add_one(\"age\")).show()\n +----------+--------------+------------+\n |slen(name)|to_upper(name)|add_one(age)|\n +----------+--------------+------------+\n | 8| JOHN DOE| 22|\n +----------+--------------+------------+\n \"\"\"\n\n # The following table shows most of Python data and SQL type conversions in normal UDFs that\n # are not yet visible to the user. Some of behaviors are buggy and might be changed in the near\n # future. The table might have to be eventually documented externally.\n # Please see SPARK-25666's PR to see the codes in order to generate the table below.\n #\n # +-----------------------------+--------------+----------+------+-------+---------------+---------------+--------------------+-----------------------------+----------+----------------------+---------+--------------------+-----------------+------------+--------------+------------------+----------------------+ # noqa\n # |SQL Type \\ Python Value(Type)|None(NoneType)|True(bool)|1(int)|1(long)| a(str)| a(unicode)| 1970-01-01(date)|1970-01-01 00:00:00(datetime)|1.0(float)|array('i', [1])(array)|[1](list)| (1,)(tuple)| ABC(bytearray)| 1(Decimal)|{'a': 1}(dict)|Row(kwargs=1)(Row)|Row(namedtuple=1)(Row)| # noqa\n # +-----------------------------+--------------+----------+------+-------+---------------+---------------+--------------------+-----------------------------+----------+----------------------+---------+--------------------+-----------------+------------+--------------+------------------+----------------------+ # noqa\n # | boolean| None| True| None| None| None| None| None| None| None| None| None| None| None| None| None| X| X| # noqa\n # | tinyint| None| None| 1| 1| None| None| None| None| None| None| None| None| None| None| None| X| X| # noqa\n # | smallint| None| None| 1| 1| None| None| None| None| None| None| None| None| None| None| None| X| X| # noqa\n # | int| None| None| 1| 1| None| None| None| None| None| None| None| None| None| None| None| X| X| # noqa\n # | bigint| None| None| 1| 1| None| None| None| None| None| None| None| None| None| None| None| X| X| # noqa\n # | string| None| u'true'| u'1'| u'1'| u'a'| u'a'|u'java.util.Grego...| u'java.util.Grego...| u'1.0'| u'[I@24a83055'| u'[1]'|u'[Ljava.lang.Obj...| u'[B@49093632'| u'1'| u'{a=1}'| X| X| # noqa\n # | date| None| X| X| X| X| X|datetime.date(197...| datetime.date(197...| X| X| X| X| X| X| X| X| X| # noqa\n # | timestamp| None| X| X| X| X| X| X| datetime.datetime...| X| X| X| X| X| X| X| X| X| # noqa\n # | float| None| None| None| None| None| None| None| None| 1.0| None| None| None| None| None| None| X| X| # noqa\n # | double| None| None| None| None| None| None| None| None| 1.0| None| None| None| None| None| None| X| X| # noqa\n # | array| None| None| None| None| None| None| None| None| None| [1]| [1]| [1]| [65, 66, 67]| None| None| X| X| # noqa\n # | binary| None| None| None| None|bytearray(b'a')|bytearray(b'a')| None| None| None| None| None| None|bytearray(b'ABC')| None| None| X| X| # noqa\n # | decimal(10,0)| None| None| None| None| None| None| None| None| None| None| None| None| None|Decimal('1')| None| X| X| # noqa\n # | map| None| None| None| None| None| None| None| None| None| None| None| None| None| None| {u'a': 1}| X| X| # noqa\n # | struct<_1:int>| None| X| X| X| X| X| X| X| X| X|Row(_1=1)| Row(_1=1)| X| X| Row(_1=None)| Row(_1=1)| Row(_1=1)| # noqa\n # +-----------------------------+--------------+----------+------+-------+---------------+---------------+--------------------+-----------------------------+----------+----------------------+---------+--------------------+-----------------+------------+--------------+------------------+----------------------+ # noqa\n #\n # Note: DDL formatted string is used for 'SQL Type' for simplicity. This string can be\n # used in `returnType`.\n # Note: The values inside of the table are generated by `repr`.\n # Note: Python 2 is used to generate this table since it is used to check the backward\n # compatibility often in practice.\n # Note: 'X' means it throws an exception during the conversion.\n\n # decorator @udf, @udf(), @udf(dataType())\n if f is None or isinstance(f, (str, DataType)):\n # If DataType has been passed as a positional argument\n # for decorator use it as a returnType\n return_type = f or returnType\n return functools.partial(_create_udf, returnType=return_type,\n evalType=PythonEvalType.SQL_BATCHED_UDF)\n else:\n return _create_udf(f=f, returnType=returnType,\n evalType=PythonEvalType.SQL_BATCHED_UDF)" }, { "instruction": "Write or improve a Python function based on this description:\n\nCreates a vectorized user defined function (UDF).\n\n :param f: user-defined function. A python function if used as a standalone function\n :param returnType: the return type of the user-defined function. The value can be either a\n :class:`pyspark.sql.types.DataType` object or a DDL-formatted type string.\n :param functionType: an enum value in :class:`pyspark.sql.functions.PandasUDFType`.\n Default: SCALAR.\n\n .. note:: Experimental\n\n The function type of the UDF can be one of the following:\n\n 1. SCALAR\n\n A scalar UDF defines a transformation: One or more `pandas.Series` -> A `pandas.Series`.\n The length of the returned `pandas.Series` must be of the same as the input `pandas.Series`.\n If the return type is :class:`StructType`, the returned value should be a `pandas.DataFrame`.\n\n :class:`MapType`, nested :class:`StructType` are currently not supported as output types.\n\n Scalar UDFs are used with :meth:`pyspark.sql.DataFrame.withColumn` and\n :meth:`pyspark.sql.DataFrame.select`.\n\n >>> from pyspark.sql.functions import pandas_udf, PandasUDFType\n >>> from pyspark.sql.types import IntegerType, StringType\n >>> slen = pandas_udf(lambda s: s.str.len(), IntegerType()) # doctest: +SKIP\n >>> @pandas_udf(StringType()) # doctest: +SKIP\n ... def to_upper(s):\n ... return s.str.upper()\n ...\n >>> @pandas_udf(\"integer\", PandasUDFType.SCALAR) # doctest: +SKIP\n ... def add_one(x):\n ... return x + 1\n ...\n >>> df = spark.createDataFrame([(1, \"John Doe\", 21)],\n ... (\"id\", \"name\", \"age\")) # doctest: +SKIP\n >>> df.select(slen(\"name\").alias(\"slen(name)\"), to_upper(\"name\"), add_one(\"age\")) \\\\\n ... .show() # doctest: +SKIP\n +----------+--------------+------------+\n |slen(name)|to_upper(name)|add_one(age)|\n +----------+--------------+------------+\n | 8| JOHN DOE| 22|\n +----------+--------------+------------+\n >>> @pandas_udf(\"first string, last string\") # doctest: +SKIP\n ... def split_expand(n):\n ... return n.str.split(expand=True)\n >>> df.select(split_expand(\"name\")).show() # doctest: +SKIP\n +------------------+\n |split_expand(name)|\n +------------------+\n | [John, Doe]|\n +------------------+\n\n .. note:: The length of `pandas.Series` within a scalar UDF is not that of the whole input\n column, but is the length of an internal batch used for each call to the function.\n Therefore, this can be used, for example, to ensure the length of each returned\n `pandas.Series`, and can not be used as the column length.\n\n 2. GROUPED_MAP\n\n A grouped map UDF defines transformation: A `pandas.DataFrame` -> A `pandas.DataFrame`\n The returnType should be a :class:`StructType` describing the schema of the returned\n `pandas.DataFrame`. The column labels of the returned `pandas.DataFrame` must either match\n the field names in the defined returnType schema if specified as strings, or match the\n field data types by position if not strings, e.g. integer indices.\n The length of the returned `pandas.DataFrame` can be arbitrary.\n\n Grouped map UDFs are used with :meth:`pyspark.sql.GroupedData.apply`.\n\n >>> from pyspark.sql.functions import pandas_udf, PandasUDFType\n >>> df = spark.createDataFrame(\n ... [(1, 1.0), (1, 2.0), (2, 3.0), (2, 5.0), (2, 10.0)],\n ... (\"id\", \"v\")) # doctest: +SKIP\n >>> @pandas_udf(\"id long, v double\", PandasUDFType.GROUPED_MAP) # doctest: +SKIP\n ... def normalize(pdf):\n ... v = pdf.v\n ... return pdf.assign(v=(v - v.mean()) / v.std())\n >>> df.groupby(\"id\").apply(normalize).show() # doctest: +SKIP\n +---+-------------------+\n | id| v|\n +---+-------------------+\n | 1|-0.7071067811865475|\n | 1| 0.7071067811865475|\n | 2|-0.8320502943378437|\n | 2|-0.2773500981126146|\n | 2| 1.1094003924504583|\n +---+-------------------+\n\n Alternatively, the user can define a function that takes two arguments.\n In this case, the grouping key(s) will be passed as the first argument and the data will\n be passed as the second argument. The grouping key(s) will be passed as a tuple of numpy\n data types, e.g., `numpy.int32` and `numpy.float64`. The data will still be passed in\n as a `pandas.DataFrame` containing all columns from the original Spark DataFrame.\n This is useful when the user does not want to hardcode grouping key(s) in the function.\n\n >>> import pandas as pd # doctest: +SKIP\n >>> from pyspark.sql.functions import pandas_udf, PandasUDFType\n >>> df = spark.createDataFrame(\n ... [(1, 1.0), (1, 2.0), (2, 3.0), (2, 5.0), (2, 10.0)],\n ... (\"id\", \"v\")) # doctest: +SKIP\n >>> @pandas_udf(\"id long, v double\", PandasUDFType.GROUPED_MAP) # doctest: +SKIP\n ... def mean_udf(key, pdf):\n ... # key is a tuple of one numpy.int64, which is the value\n ... # of 'id' for the current group\n ... return pd.DataFrame([key + (pdf.v.mean(),)])\n >>> df.groupby('id').apply(mean_udf).show() # doctest: +SKIP\n +---+---+\n | id| v|\n +---+---+\n | 1|1.5|\n | 2|6.0|\n +---+---+\n >>> @pandas_udf(\n ... \"id long, `ceil(v / 2)` long, v double\",\n ... PandasUDFType.GROUPED_MAP) # doctest: +SKIP\n >>> def sum_udf(key, pdf):\n ... # key is a tuple of two numpy.int64s, which is the values\n ... # of 'id' and 'ceil(df.v / 2)' for the current group\n ... return pd.DataFrame([key + (pdf.v.sum(),)])\n >>> df.groupby(df.id, ceil(df.v / 2)).apply(sum_udf).show() # doctest: +SKIP\n +---+-----------+----+\n | id|ceil(v / 2)| v|\n +---+-----------+----+\n | 2| 5|10.0|\n | 1| 1| 3.0|\n | 2| 3| 5.0|\n | 2| 2| 3.0|\n +---+-----------+----+\n\n .. note:: If returning a new `pandas.DataFrame` constructed with a dictionary, it is\n recommended to explicitly index the columns by name to ensure the positions are correct,\n or alternatively use an `OrderedDict`.\n For example, `pd.DataFrame({'id': ids, 'a': data}, columns=['id', 'a'])` or\n `pd.DataFrame(OrderedDict([('id', ids), ('a', data)]))`.\n\n .. seealso:: :meth:`pyspark.sql.GroupedData.apply`\n\n 3. GROUPED_AGG\n\n A grouped aggregate UDF defines a transformation: One or more `pandas.Series` -> A scalar\n The `returnType` should be a primitive data type, e.g., :class:`DoubleType`.\n The returned scalar can be either a python primitive type, e.g., `int` or `float`\n or a numpy data type, e.g., `numpy.int64` or `numpy.float64`.\n\n :class:`MapType` and :class:`StructType` are currently not supported as output types.\n\n Group aggregate UDFs are used with :meth:`pyspark.sql.GroupedData.agg` and\n :class:`pyspark.sql.Window`\n\n This example shows using grouped aggregated UDFs with groupby:\n\n >>> from pyspark.sql.functions import pandas_udf, PandasUDFType\n >>> df = spark.createDataFrame(\n ... [(1, 1.0), (1, 2.0), (2, 3.0), (2, 5.0), (2, 10.0)],\n ... (\"id\", \"v\"))\n >>> @pandas_udf(\"double\", PandasUDFType.GROUPED_AGG) # doctest: +SKIP\n ... def mean_udf(v):\n ... return v.mean()\n >>> df.groupby(\"id\").agg(mean_udf(df['v'])).show() # doctest: +SKIP\n +---+-----------+\n | id|mean_udf(v)|\n +---+-----------+\n | 1| 1.5|\n | 2| 6.0|\n +---+-----------+\n\n This example shows using grouped aggregated UDFs as window functions.\n\n >>> from pyspark.sql.functions import pandas_udf, PandasUDFType\n >>> from pyspark.sql import Window\n >>> df = spark.createDataFrame(\n ... [(1, 1.0), (1, 2.0), (2, 3.0), (2, 5.0), (2, 10.0)],\n ... (\"id\", \"v\"))\n >>> @pandas_udf(\"double\", PandasUDFType.GROUPED_AGG) # doctest: +SKIP\n ... def mean_udf(v):\n ... return v.mean()\n >>> w = (Window.partitionBy('id')\n ... .orderBy('v')\n ... .rowsBetween(-1, 0))\n >>> df.withColumn('mean_v', mean_udf(df['v']).over(w)).show() # doctest: +SKIP\n +---+----+------+\n | id| v|mean_v|\n +---+----+------+\n | 1| 1.0| 1.0|\n | 1| 2.0| 1.5|\n | 2| 3.0| 3.0|\n | 2| 5.0| 4.0|\n | 2|10.0| 7.5|\n +---+----+------+\n\n .. note:: For performance reasons, the input series to window functions are not copied.\n Therefore, mutating the input series is not allowed and will cause incorrect results.\n For the same reason, users should also not rely on the index of the input series.\n\n .. seealso:: :meth:`pyspark.sql.GroupedData.agg` and :class:`pyspark.sql.Window`\n\n .. note:: The user-defined functions are considered deterministic by default. Due to\n optimization, duplicate invocations may be eliminated or the function may even be invoked\n more times than it is present in the query. If your function is not deterministic, call\n `asNondeterministic` on the user defined function. E.g.:\n\n >>> @pandas_udf('double', PandasUDFType.SCALAR) # doctest: +SKIP\n ... def random(v):\n ... import numpy as np\n ... import pandas as pd\n ... return pd.Series(np.random.randn(len(v))\n >>> random = random.asNondeterministic() # doctest: +SKIP\n\n .. note:: The user-defined functions do not support conditional expressions or short circuiting\n in boolean expressions and it ends up with being executed all internally. If the functions\n can fail on special rows, the workaround is to incorporate the condition into the functions.\n\n .. note:: The user-defined functions do not take keyword arguments on the calling side.\n\n .. note:: The data type of returned `pandas.Series` from the user-defined functions should be\n matched with defined returnType (see :meth:`types.to_arrow_type` and\n :meth:`types.from_arrow_type`). When there is mismatch between them, Spark might do\n conversion on returned data. The conversion is not guaranteed to be correct and results\n should be checked for accuracy by users.", "output": "def pandas_udf(f=None, returnType=None, functionType=None):\n \"\"\"\n Creates a vectorized user defined function (UDF).\n\n :param f: user-defined function. A python function if used as a standalone function\n :param returnType: the return type of the user-defined function. The value can be either a\n :class:`pyspark.sql.types.DataType` object or a DDL-formatted type string.\n :param functionType: an enum value in :class:`pyspark.sql.functions.PandasUDFType`.\n Default: SCALAR.\n\n .. note:: Experimental\n\n The function type of the UDF can be one of the following:\n\n 1. SCALAR\n\n A scalar UDF defines a transformation: One or more `pandas.Series` -> A `pandas.Series`.\n The length of the returned `pandas.Series` must be of the same as the input `pandas.Series`.\n If the return type is :class:`StructType`, the returned value should be a `pandas.DataFrame`.\n\n :class:`MapType`, nested :class:`StructType` are currently not supported as output types.\n\n Scalar UDFs are used with :meth:`pyspark.sql.DataFrame.withColumn` and\n :meth:`pyspark.sql.DataFrame.select`.\n\n >>> from pyspark.sql.functions import pandas_udf, PandasUDFType\n >>> from pyspark.sql.types import IntegerType, StringType\n >>> slen = pandas_udf(lambda s: s.str.len(), IntegerType()) # doctest: +SKIP\n >>> @pandas_udf(StringType()) # doctest: +SKIP\n ... def to_upper(s):\n ... return s.str.upper()\n ...\n >>> @pandas_udf(\"integer\", PandasUDFType.SCALAR) # doctest: +SKIP\n ... def add_one(x):\n ... return x + 1\n ...\n >>> df = spark.createDataFrame([(1, \"John Doe\", 21)],\n ... (\"id\", \"name\", \"age\")) # doctest: +SKIP\n >>> df.select(slen(\"name\").alias(\"slen(name)\"), to_upper(\"name\"), add_one(\"age\")) \\\\\n ... .show() # doctest: +SKIP\n +----------+--------------+------------+\n |slen(name)|to_upper(name)|add_one(age)|\n +----------+--------------+------------+\n | 8| JOHN DOE| 22|\n +----------+--------------+------------+\n >>> @pandas_udf(\"first string, last string\") # doctest: +SKIP\n ... def split_expand(n):\n ... return n.str.split(expand=True)\n >>> df.select(split_expand(\"name\")).show() # doctest: +SKIP\n +------------------+\n |split_expand(name)|\n +------------------+\n | [John, Doe]|\n +------------------+\n\n .. note:: The length of `pandas.Series` within a scalar UDF is not that of the whole input\n column, but is the length of an internal batch used for each call to the function.\n Therefore, this can be used, for example, to ensure the length of each returned\n `pandas.Series`, and can not be used as the column length.\n\n 2. GROUPED_MAP\n\n A grouped map UDF defines transformation: A `pandas.DataFrame` -> A `pandas.DataFrame`\n The returnType should be a :class:`StructType` describing the schema of the returned\n `pandas.DataFrame`. The column labels of the returned `pandas.DataFrame` must either match\n the field names in the defined returnType schema if specified as strings, or match the\n field data types by position if not strings, e.g. integer indices.\n The length of the returned `pandas.DataFrame` can be arbitrary.\n\n Grouped map UDFs are used with :meth:`pyspark.sql.GroupedData.apply`.\n\n >>> from pyspark.sql.functions import pandas_udf, PandasUDFType\n >>> df = spark.createDataFrame(\n ... [(1, 1.0), (1, 2.0), (2, 3.0), (2, 5.0), (2, 10.0)],\n ... (\"id\", \"v\")) # doctest: +SKIP\n >>> @pandas_udf(\"id long, v double\", PandasUDFType.GROUPED_MAP) # doctest: +SKIP\n ... def normalize(pdf):\n ... v = pdf.v\n ... return pdf.assign(v=(v - v.mean()) / v.std())\n >>> df.groupby(\"id\").apply(normalize).show() # doctest: +SKIP\n +---+-------------------+\n | id| v|\n +---+-------------------+\n | 1|-0.7071067811865475|\n | 1| 0.7071067811865475|\n | 2|-0.8320502943378437|\n | 2|-0.2773500981126146|\n | 2| 1.1094003924504583|\n +---+-------------------+\n\n Alternatively, the user can define a function that takes two arguments.\n In this case, the grouping key(s) will be passed as the first argument and the data will\n be passed as the second argument. The grouping key(s) will be passed as a tuple of numpy\n data types, e.g., `numpy.int32` and `numpy.float64`. The data will still be passed in\n as a `pandas.DataFrame` containing all columns from the original Spark DataFrame.\n This is useful when the user does not want to hardcode grouping key(s) in the function.\n\n >>> import pandas as pd # doctest: +SKIP\n >>> from pyspark.sql.functions import pandas_udf, PandasUDFType\n >>> df = spark.createDataFrame(\n ... [(1, 1.0), (1, 2.0), (2, 3.0), (2, 5.0), (2, 10.0)],\n ... (\"id\", \"v\")) # doctest: +SKIP\n >>> @pandas_udf(\"id long, v double\", PandasUDFType.GROUPED_MAP) # doctest: +SKIP\n ... def mean_udf(key, pdf):\n ... # key is a tuple of one numpy.int64, which is the value\n ... # of 'id' for the current group\n ... return pd.DataFrame([key + (pdf.v.mean(),)])\n >>> df.groupby('id').apply(mean_udf).show() # doctest: +SKIP\n +---+---+\n | id| v|\n +---+---+\n | 1|1.5|\n | 2|6.0|\n +---+---+\n >>> @pandas_udf(\n ... \"id long, `ceil(v / 2)` long, v double\",\n ... PandasUDFType.GROUPED_MAP) # doctest: +SKIP\n >>> def sum_udf(key, pdf):\n ... # key is a tuple of two numpy.int64s, which is the values\n ... # of 'id' and 'ceil(df.v / 2)' for the current group\n ... return pd.DataFrame([key + (pdf.v.sum(),)])\n >>> df.groupby(df.id, ceil(df.v / 2)).apply(sum_udf).show() # doctest: +SKIP\n +---+-----------+----+\n | id|ceil(v / 2)| v|\n +---+-----------+----+\n | 2| 5|10.0|\n | 1| 1| 3.0|\n | 2| 3| 5.0|\n | 2| 2| 3.0|\n +---+-----------+----+\n\n .. note:: If returning a new `pandas.DataFrame` constructed with a dictionary, it is\n recommended to explicitly index the columns by name to ensure the positions are correct,\n or alternatively use an `OrderedDict`.\n For example, `pd.DataFrame({'id': ids, 'a': data}, columns=['id', 'a'])` or\n `pd.DataFrame(OrderedDict([('id', ids), ('a', data)]))`.\n\n .. seealso:: :meth:`pyspark.sql.GroupedData.apply`\n\n 3. GROUPED_AGG\n\n A grouped aggregate UDF defines a transformation: One or more `pandas.Series` -> A scalar\n The `returnType` should be a primitive data type, e.g., :class:`DoubleType`.\n The returned scalar can be either a python primitive type, e.g., `int` or `float`\n or a numpy data type, e.g., `numpy.int64` or `numpy.float64`.\n\n :class:`MapType` and :class:`StructType` are currently not supported as output types.\n\n Group aggregate UDFs are used with :meth:`pyspark.sql.GroupedData.agg` and\n :class:`pyspark.sql.Window`\n\n This example shows using grouped aggregated UDFs with groupby:\n\n >>> from pyspark.sql.functions import pandas_udf, PandasUDFType\n >>> df = spark.createDataFrame(\n ... [(1, 1.0), (1, 2.0), (2, 3.0), (2, 5.0), (2, 10.0)],\n ... (\"id\", \"v\"))\n >>> @pandas_udf(\"double\", PandasUDFType.GROUPED_AGG) # doctest: +SKIP\n ... def mean_udf(v):\n ... return v.mean()\n >>> df.groupby(\"id\").agg(mean_udf(df['v'])).show() # doctest: +SKIP\n +---+-----------+\n | id|mean_udf(v)|\n +---+-----------+\n | 1| 1.5|\n | 2| 6.0|\n +---+-----------+\n\n This example shows using grouped aggregated UDFs as window functions.\n\n >>> from pyspark.sql.functions import pandas_udf, PandasUDFType\n >>> from pyspark.sql import Window\n >>> df = spark.createDataFrame(\n ... [(1, 1.0), (1, 2.0), (2, 3.0), (2, 5.0), (2, 10.0)],\n ... (\"id\", \"v\"))\n >>> @pandas_udf(\"double\", PandasUDFType.GROUPED_AGG) # doctest: +SKIP\n ... def mean_udf(v):\n ... return v.mean()\n >>> w = (Window.partitionBy('id')\n ... .orderBy('v')\n ... .rowsBetween(-1, 0))\n >>> df.withColumn('mean_v', mean_udf(df['v']).over(w)).show() # doctest: +SKIP\n +---+----+------+\n | id| v|mean_v|\n +---+----+------+\n | 1| 1.0| 1.0|\n | 1| 2.0| 1.5|\n | 2| 3.0| 3.0|\n | 2| 5.0| 4.0|\n | 2|10.0| 7.5|\n +---+----+------+\n\n .. note:: For performance reasons, the input series to window functions are not copied.\n Therefore, mutating the input series is not allowed and will cause incorrect results.\n For the same reason, users should also not rely on the index of the input series.\n\n .. seealso:: :meth:`pyspark.sql.GroupedData.agg` and :class:`pyspark.sql.Window`\n\n .. note:: The user-defined functions are considered deterministic by default. Due to\n optimization, duplicate invocations may be eliminated or the function may even be invoked\n more times than it is present in the query. If your function is not deterministic, call\n `asNondeterministic` on the user defined function. E.g.:\n\n >>> @pandas_udf('double', PandasUDFType.SCALAR) # doctest: +SKIP\n ... def random(v):\n ... import numpy as np\n ... import pandas as pd\n ... return pd.Series(np.random.randn(len(v))\n >>> random = random.asNondeterministic() # doctest: +SKIP\n\n .. note:: The user-defined functions do not support conditional expressions or short circuiting\n in boolean expressions and it ends up with being executed all internally. If the functions\n can fail on special rows, the workaround is to incorporate the condition into the functions.\n\n .. note:: The user-defined functions do not take keyword arguments on the calling side.\n\n .. note:: The data type of returned `pandas.Series` from the user-defined functions should be\n matched with defined returnType (see :meth:`types.to_arrow_type` and\n :meth:`types.from_arrow_type`). When there is mismatch between them, Spark might do\n conversion on returned data. The conversion is not guaranteed to be correct and results\n should be checked for accuracy by users.\n \"\"\"\n\n # The following table shows most of Pandas data and SQL type conversions in Pandas UDFs that\n # are not yet visible to the user. Some of behaviors are buggy and might be changed in the near\n # future. The table might have to be eventually documented externally.\n # Please see SPARK-25798's PR to see the codes in order to generate the table below.\n #\n # +-----------------------------+----------------------+----------+-------+--------+--------------------+--------------------+--------+---------+---------+---------+------------+------------+------------+-----------------------------------+-----------------------------------------------------+-----------------+--------------------+-----------------------------+-------------+-----------------+------------------+-----------+--------------------------------+ # noqa\n # |SQL Type \\ Pandas Value(Type)|None(object(NoneType))|True(bool)|1(int8)|1(int16)| 1(int32)| 1(int64)|1(uint8)|1(uint16)|1(uint32)|1(uint64)|1.0(float16)|1.0(float32)|1.0(float64)|1970-01-01 00:00:00(datetime64[ns])|1970-01-01 00:00:00-05:00(datetime64[ns, US/Eastern])|a(object(string))| 1(object(Decimal))|[1 2 3](object(array[int32]))|1.0(float128)|(1+0j)(complex64)|(1+0j)(complex128)|A(category)|1 days 00:00:00(timedelta64[ns])| # noqa\n # +-----------------------------+----------------------+----------+-------+--------+--------------------+--------------------+--------+---------+---------+---------+------------+------------+------------+-----------------------------------+-----------------------------------------------------+-----------------+--------------------+-----------------------------+-------------+-----------------+------------------+-----------+--------------------------------+ # noqa\n # | boolean| None| True| True| True| True| True| True| True| True| True| False| False| False| False| False| X| X| X| False| False| False| X| False| # noqa\n # | tinyint| None| 1| 1| 1| 1| 1| X| X| X| X| 1| 1| 1| X| X| X| X| X| X| X| X| 0| X| # noqa\n # | smallint| None| 1| 1| 1| 1| 1| 1| X| X| X| 1| 1| 1| X| X| X| X| X| X| X| X| X| X| # noqa\n # | int| None| 1| 1| 1| 1| 1| 1| 1| X| X| 1| 1| 1| X| X| X| X| X| X| X| X| X| X| # noqa\n # | bigint| None| 1| 1| 1| 1| 1| 1| 1| 1| X| 1| 1| 1| 0| 18000000000000| X| X| X| X| X| X| X| X| # noqa\n # | float| None| 1.0| 1.0| 1.0| 1.0| 1.0| 1.0| 1.0| 1.0| 1.0| 1.0| 1.0| 1.0| X| X| X|1.401298464324817...| X| X| X| X| X| X| # noqa\n # | double| None| 1.0| 1.0| 1.0| 1.0| 1.0| 1.0| 1.0| 1.0| 1.0| 1.0| 1.0| 1.0| X| X| X| X| X| X| X| X| X| X| # noqa\n # | date| None| X| X| X|datetime.date(197...| X| X| X| X| X| X| X| X| datetime.date(197...| X| X| X| X| X| X| X| X| X| # noqa\n # | timestamp| None| X| X| X| X|datetime.datetime...| X| X| X| X| X| X| X| datetime.datetime...| datetime.datetime...| X| X| X| X| X| X| X| X| # noqa\n # | string| None| u''|u'\\x01'| u'\\x01'| u'\\x01'| u'\\x01'| u'\\x01'| u'\\x01'| u'\\x01'| u'\\x01'| u''| u''| u''| X| X| u'a'| X| X| u''| u''| u''| X| X| # noqa\n # | decimal(10,0)| None| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| Decimal('1')| X| X| X| X| X| X| # noqa\n # | array| None| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| [1, 2, 3]| X| X| X| X| X| # noqa\n # | map| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| # noqa\n # | struct<_1:int>| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| # noqa\n # | binary| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| # noqa\n # +-----------------------------+----------------------+----------+-------+--------+--------------------+--------------------+--------+---------+---------+---------+------------+------------+------------+-----------------------------------+-----------------------------------------------------+-----------------+--------------------+-----------------------------+-------------+-----------------+------------------+-----------+--------------------------------+ # noqa\n #\n # Note: DDL formatted string is used for 'SQL Type' for simplicity. This string can be\n # used in `returnType`.\n # Note: The values inside of the table are generated by `repr`.\n # Note: Python 2 is used to generate this table since it is used to check the backward\n # compatibility often in practice.\n # Note: Pandas 0.19.2 and PyArrow 0.9.0 are used.\n # Note: Timezone is Singapore timezone.\n # Note: 'X' means it throws an exception during the conversion.\n # Note: 'binary' type is only supported with PyArrow 0.10.0+ (SPARK-23555).\n\n # decorator @pandas_udf(returnType, functionType)\n is_decorator = f is None or isinstance(f, (str, DataType))\n\n if is_decorator:\n # If DataType has been passed as a positional argument\n # for decorator use it as a returnType\n return_type = f or returnType\n\n if functionType is not None:\n # @pandas_udf(dataType, functionType=functionType)\n # @pandas_udf(returnType=dataType, functionType=functionType)\n eval_type = functionType\n elif returnType is not None and isinstance(returnType, int):\n # @pandas_udf(dataType, functionType)\n eval_type = returnType\n else:\n # @pandas_udf(dataType) or @pandas_udf(returnType=dataType)\n eval_type = PythonEvalType.SQL_SCALAR_PANDAS_UDF\n else:\n return_type = returnType\n\n if functionType is not None:\n eval_type = functionType\n else:\n eval_type = PythonEvalType.SQL_SCALAR_PANDAS_UDF\n\n if return_type is None:\n raise ValueError(\"Invalid returnType: returnType can not be None\")\n\n if eval_type not in [PythonEvalType.SQL_SCALAR_PANDAS_UDF,\n PythonEvalType.SQL_GROUPED_MAP_PANDAS_UDF,\n PythonEvalType.SQL_GROUPED_AGG_PANDAS_UDF]:\n raise ValueError(\"Invalid functionType: \"\n \"functionType must be one the values from PandasUDFType\")\n\n if is_decorator:\n return functools.partial(_create_udf, returnType=return_type, evalType=eval_type)\n else:\n return _create_udf(f=f, returnType=return_type, evalType=eval_type)" }, { "instruction": "Write or improve a Python function based on this description:\n\nA wrapper over str(), but converts bool values to lower case strings.\n If None is given, just returns None, instead of converting it to string \"None\".", "output": "def to_str(value):\n \"\"\"\n A wrapper over str(), but converts bool values to lower case strings.\n If None is given, just returns None, instead of converting it to string \"None\".\n \"\"\"\n if isinstance(value, bool):\n return str(value).lower()\n elif value is None:\n return value\n else:\n return str(value)" }, { "instruction": "Write or improve a Python function based on this description:\n\nSet named options (filter out those the value is None)", "output": "def _set_opts(self, schema=None, **options):\n \"\"\"\n Set named options (filter out those the value is None)\n \"\"\"\n if schema is not None:\n self.schema(schema)\n for k, v in options.items():\n if v is not None:\n self.option(k, v)" }, { "instruction": "Write or improve a Python function based on this description:\n\nSpecifies the input data source format.\n\n :param source: string, name of the data source, e.g. 'json', 'parquet'.\n\n >>> df = spark.read.format('json').load('python/test_support/sql/people.json')\n >>> df.dtypes\n [('age', 'bigint'), ('name', 'string')]", "output": "def format(self, source):\n \"\"\"Specifies the input data source format.\n\n :param source: string, name of the data source, e.g. 'json', 'parquet'.\n\n >>> df = spark.read.format('json').load('python/test_support/sql/people.json')\n >>> df.dtypes\n [('age', 'bigint'), ('name', 'string')]\n\n \"\"\"\n self._jreader = self._jreader.format(source)\n return self" }, { "instruction": "Write or improve a Python function based on this description:\n\nSpecifies the input schema.\n\n Some data sources (e.g. JSON) can infer the input schema automatically from data.\n By specifying the schema here, the underlying data source can skip the schema\n inference step, and thus speed up data loading.\n\n :param schema: a :class:`pyspark.sql.types.StructType` object or a DDL-formatted string\n (For example ``col0 INT, col1 DOUBLE``).\n\n >>> s = spark.read.schema(\"col0 INT, col1 DOUBLE\")", "output": "def schema(self, schema):\n \"\"\"Specifies the input schema.\n\n Some data sources (e.g. JSON) can infer the input schema automatically from data.\n By specifying the schema here, the underlying data source can skip the schema\n inference step, and thus speed up data loading.\n\n :param schema: a :class:`pyspark.sql.types.StructType` object or a DDL-formatted string\n (For example ``col0 INT, col1 DOUBLE``).\n\n >>> s = spark.read.schema(\"col0 INT, col1 DOUBLE\")\n \"\"\"\n from pyspark.sql import SparkSession\n spark = SparkSession.builder.getOrCreate()\n if isinstance(schema, StructType):\n jschema = spark._jsparkSession.parseDataType(schema.json())\n self._jreader = self._jreader.schema(jschema)\n elif isinstance(schema, basestring):\n self._jreader = self._jreader.schema(schema)\n else:\n raise TypeError(\"schema should be StructType or string\")\n return self" }, { "instruction": "Write or improve a Python function based on this description:\n\nAdds an input option for the underlying data source.\n\n You can set the following option(s) for reading files:\n * ``timeZone``: sets the string that indicates a timezone to be used to parse timestamps\n in the JSON/CSV datasources or partition values.\n If it isn't set, it uses the default value, session local timezone.", "output": "def option(self, key, value):\n \"\"\"Adds an input option for the underlying data source.\n\n You can set the following option(s) for reading files:\n * ``timeZone``: sets the string that indicates a timezone to be used to parse timestamps\n in the JSON/CSV datasources or partition values.\n If it isn't set, it uses the default value, session local timezone.\n \"\"\"\n self._jreader = self._jreader.option(key, to_str(value))\n return self" }, { "instruction": "Write or improve a Python function based on this description:\n\nAdds input options for the underlying data source.\n\n You can set the following option(s) for reading files:\n * ``timeZone``: sets the string that indicates a timezone to be used to parse timestamps\n in the JSON/CSV datasources or partition values.\n If it isn't set, it uses the default value, session local timezone.", "output": "def options(self, **options):\n \"\"\"Adds input options for the underlying data source.\n\n You can set the following option(s) for reading files:\n * ``timeZone``: sets the string that indicates a timezone to be used to parse timestamps\n in the JSON/CSV datasources or partition values.\n If it isn't set, it uses the default value, session local timezone.\n \"\"\"\n for k in options:\n self._jreader = self._jreader.option(k, to_str(options[k]))\n return self" }, { "instruction": "Write or improve a Python function based on this description:\n\nLoads data from a data source and returns it as a :class`DataFrame`.\n\n :param path: optional string or a list of string for file-system backed data sources.\n :param format: optional string for format of the data source. Default to 'parquet'.\n :param schema: optional :class:`pyspark.sql.types.StructType` for the input schema\n or a DDL-formatted string (For example ``col0 INT, col1 DOUBLE``).\n :param options: all other string options\n\n >>> df = spark.read.format(\"parquet\").load('python/test_support/sql/parquet_partitioned',\n ... opt1=True, opt2=1, opt3='str')\n >>> df.dtypes\n [('name', 'string'), ('year', 'int'), ('month', 'int'), ('day', 'int')]\n\n >>> df = spark.read.format('json').load(['python/test_support/sql/people.json',\n ... 'python/test_support/sql/people1.json'])\n >>> df.dtypes\n [('age', 'bigint'), ('aka', 'string'), ('name', 'string')]", "output": "def load(self, path=None, format=None, schema=None, **options):\n \"\"\"Loads data from a data source and returns it as a :class`DataFrame`.\n\n :param path: optional string or a list of string for file-system backed data sources.\n :param format: optional string for format of the data source. Default to 'parquet'.\n :param schema: optional :class:`pyspark.sql.types.StructType` for the input schema\n or a DDL-formatted string (For example ``col0 INT, col1 DOUBLE``).\n :param options: all other string options\n\n >>> df = spark.read.format(\"parquet\").load('python/test_support/sql/parquet_partitioned',\n ... opt1=True, opt2=1, opt3='str')\n >>> df.dtypes\n [('name', 'string'), ('year', 'int'), ('month', 'int'), ('day', 'int')]\n\n >>> df = spark.read.format('json').load(['python/test_support/sql/people.json',\n ... 'python/test_support/sql/people1.json'])\n >>> df.dtypes\n [('age', 'bigint'), ('aka', 'string'), ('name', 'string')]\n \"\"\"\n if format is not None:\n self.format(format)\n if schema is not None:\n self.schema(schema)\n self.options(**options)\n if isinstance(path, basestring):\n return self._df(self._jreader.load(path))\n elif path is not None:\n if type(path) != list:\n path = [path]\n return self._df(self._jreader.load(self._spark._sc._jvm.PythonUtils.toSeq(path)))\n else:\n return self._df(self._jreader.load())" }, { "instruction": "Write or improve a Python function based on this description:\n\nLoads JSON files and returns the results as a :class:`DataFrame`.\n\n `JSON Lines `_ (newline-delimited JSON) is supported by default.\n For JSON (one record per file), set the ``multiLine`` parameter to ``true``.\n\n If the ``schema`` parameter is not specified, this function goes\n through the input once to determine the input schema.\n\n :param path: string represents path to the JSON dataset, or a list of paths,\n or RDD of Strings storing JSON objects.\n :param schema: an optional :class:`pyspark.sql.types.StructType` for the input schema or\n a DDL-formatted string (For example ``col0 INT, col1 DOUBLE``).\n :param primitivesAsString: infers all primitive values as a string type. If None is set,\n it uses the default value, ``false``.\n :param prefersDecimal: infers all floating-point values as a decimal type. If the values\n do not fit in decimal, then it infers them as doubles. If None is\n set, it uses the default value, ``false``.\n :param allowComments: ignores Java/C++ style comment in JSON records. If None is set,\n it uses the default value, ``false``.\n :param allowUnquotedFieldNames: allows unquoted JSON field names. If None is set,\n it uses the default value, ``false``.\n :param allowSingleQuotes: allows single quotes in addition to double quotes. If None is\n set, it uses the default value, ``true``.\n :param allowNumericLeadingZero: allows leading zeros in numbers (e.g. 00012). If None is\n set, it uses the default value, ``false``.\n :param allowBackslashEscapingAnyCharacter: allows accepting quoting of all character\n using backslash quoting mechanism. If None is\n set, it uses the default value, ``false``.\n :param mode: allows a mode for dealing with corrupt records during parsing. If None is\n set, it uses the default value, ``PERMISSIVE``.\n\n * ``PERMISSIVE`` : when it meets a corrupted record, puts the malformed string \\\n into a field configured by ``columnNameOfCorruptRecord``, and sets malformed \\\n fields to ``null``. To keep corrupt records, an user can set a string type \\\n field named ``columnNameOfCorruptRecord`` in an user-defined schema. If a \\\n schema does not have the field, it drops corrupt records during parsing. \\\n When inferring a schema, it implicitly adds a ``columnNameOfCorruptRecord`` \\\n field in an output schema.\n * ``DROPMALFORMED`` : ignores the whole corrupted records.\n * ``FAILFAST`` : throws an exception when it meets corrupted records.\n\n :param columnNameOfCorruptRecord: allows renaming the new field having malformed string\n created by ``PERMISSIVE`` mode. This overrides\n ``spark.sql.columnNameOfCorruptRecord``. If None is set,\n it uses the value specified in\n ``spark.sql.columnNameOfCorruptRecord``.\n :param dateFormat: sets the string that indicates a date format. Custom date formats\n follow the formats at ``java.time.format.DateTimeFormatter``. This\n applies to date type. If None is set, it uses the\n default value, ``yyyy-MM-dd``.\n :param timestampFormat: sets the string that indicates a timestamp format.\n Custom date formats follow the formats at\n ``java.time.format.DateTimeFormatter``.\n This applies to timestamp type. If None is set, it uses the\n default value, ``yyyy-MM-dd'T'HH:mm:ss.SSSXXX``.\n :param multiLine: parse one record, which may span multiple lines, per file. If None is\n set, it uses the default value, ``false``.\n :param allowUnquotedControlChars: allows JSON Strings to contain unquoted control\n characters (ASCII characters with value less than 32,\n including tab and line feed characters) or not.\n :param encoding: allows to forcibly set one of standard basic or extended encoding for\n the JSON files. For example UTF-16BE, UTF-32LE. If None is set,\n the encoding of input JSON will be detected automatically\n when the multiLine option is set to ``true``.\n :param lineSep: defines the line separator that should be used for parsing. If None is\n set, it covers all ``\\\\r``, ``\\\\r\\\\n`` and ``\\\\n``.\n :param samplingRatio: defines fraction of input JSON objects used for schema inferring.\n If None is set, it uses the default value, ``1.0``.\n :param dropFieldIfAllNull: whether to ignore column of all null values or empty\n array/struct during schema inference. If None is set, it\n uses the default value, ``false``.\n :param locale: sets a locale as language tag in IETF BCP 47 format. If None is set,\n it uses the default value, ``en-US``. For instance, ``locale`` is used while\n parsing dates and timestamps.\n\n >>> df1 = spark.read.json('python/test_support/sql/people.json')\n >>> df1.dtypes\n [('age', 'bigint'), ('name', 'string')]\n >>> rdd = sc.textFile('python/test_support/sql/people.json')\n >>> df2 = spark.read.json(rdd)\n >>> df2.dtypes\n [('age', 'bigint'), ('name', 'string')]", "output": "def json(self, path, schema=None, primitivesAsString=None, prefersDecimal=None,\n allowComments=None, allowUnquotedFieldNames=None, allowSingleQuotes=None,\n allowNumericLeadingZero=None, allowBackslashEscapingAnyCharacter=None,\n mode=None, columnNameOfCorruptRecord=None, dateFormat=None, timestampFormat=None,\n multiLine=None, allowUnquotedControlChars=None, lineSep=None, samplingRatio=None,\n dropFieldIfAllNull=None, encoding=None, locale=None):\n \"\"\"\n Loads JSON files and returns the results as a :class:`DataFrame`.\n\n `JSON Lines `_ (newline-delimited JSON) is supported by default.\n For JSON (one record per file), set the ``multiLine`` parameter to ``true``.\n\n If the ``schema`` parameter is not specified, this function goes\n through the input once to determine the input schema.\n\n :param path: string represents path to the JSON dataset, or a list of paths,\n or RDD of Strings storing JSON objects.\n :param schema: an optional :class:`pyspark.sql.types.StructType` for the input schema or\n a DDL-formatted string (For example ``col0 INT, col1 DOUBLE``).\n :param primitivesAsString: infers all primitive values as a string type. If None is set,\n it uses the default value, ``false``.\n :param prefersDecimal: infers all floating-point values as a decimal type. If the values\n do not fit in decimal, then it infers them as doubles. If None is\n set, it uses the default value, ``false``.\n :param allowComments: ignores Java/C++ style comment in JSON records. If None is set,\n it uses the default value, ``false``.\n :param allowUnquotedFieldNames: allows unquoted JSON field names. If None is set,\n it uses the default value, ``false``.\n :param allowSingleQuotes: allows single quotes in addition to double quotes. If None is\n set, it uses the default value, ``true``.\n :param allowNumericLeadingZero: allows leading zeros in numbers (e.g. 00012). If None is\n set, it uses the default value, ``false``.\n :param allowBackslashEscapingAnyCharacter: allows accepting quoting of all character\n using backslash quoting mechanism. If None is\n set, it uses the default value, ``false``.\n :param mode: allows a mode for dealing with corrupt records during parsing. If None is\n set, it uses the default value, ``PERMISSIVE``.\n\n * ``PERMISSIVE`` : when it meets a corrupted record, puts the malformed string \\\n into a field configured by ``columnNameOfCorruptRecord``, and sets malformed \\\n fields to ``null``. To keep corrupt records, an user can set a string type \\\n field named ``columnNameOfCorruptRecord`` in an user-defined schema. If a \\\n schema does not have the field, it drops corrupt records during parsing. \\\n When inferring a schema, it implicitly adds a ``columnNameOfCorruptRecord`` \\\n field in an output schema.\n * ``DROPMALFORMED`` : ignores the whole corrupted records.\n * ``FAILFAST`` : throws an exception when it meets corrupted records.\n\n :param columnNameOfCorruptRecord: allows renaming the new field having malformed string\n created by ``PERMISSIVE`` mode. This overrides\n ``spark.sql.columnNameOfCorruptRecord``. If None is set,\n it uses the value specified in\n ``spark.sql.columnNameOfCorruptRecord``.\n :param dateFormat: sets the string that indicates a date format. Custom date formats\n follow the formats at ``java.time.format.DateTimeFormatter``. This\n applies to date type. If None is set, it uses the\n default value, ``yyyy-MM-dd``.\n :param timestampFormat: sets the string that indicates a timestamp format.\n Custom date formats follow the formats at\n ``java.time.format.DateTimeFormatter``.\n This applies to timestamp type. If None is set, it uses the\n default value, ``yyyy-MM-dd'T'HH:mm:ss.SSSXXX``.\n :param multiLine: parse one record, which may span multiple lines, per file. If None is\n set, it uses the default value, ``false``.\n :param allowUnquotedControlChars: allows JSON Strings to contain unquoted control\n characters (ASCII characters with value less than 32,\n including tab and line feed characters) or not.\n :param encoding: allows to forcibly set one of standard basic or extended encoding for\n the JSON files. For example UTF-16BE, UTF-32LE. If None is set,\n the encoding of input JSON will be detected automatically\n when the multiLine option is set to ``true``.\n :param lineSep: defines the line separator that should be used for parsing. If None is\n set, it covers all ``\\\\r``, ``\\\\r\\\\n`` and ``\\\\n``.\n :param samplingRatio: defines fraction of input JSON objects used for schema inferring.\n If None is set, it uses the default value, ``1.0``.\n :param dropFieldIfAllNull: whether to ignore column of all null values or empty\n array/struct during schema inference. If None is set, it\n uses the default value, ``false``.\n :param locale: sets a locale as language tag in IETF BCP 47 format. If None is set,\n it uses the default value, ``en-US``. For instance, ``locale`` is used while\n parsing dates and timestamps.\n\n >>> df1 = spark.read.json('python/test_support/sql/people.json')\n >>> df1.dtypes\n [('age', 'bigint'), ('name', 'string')]\n >>> rdd = sc.textFile('python/test_support/sql/people.json')\n >>> df2 = spark.read.json(rdd)\n >>> df2.dtypes\n [('age', 'bigint'), ('name', 'string')]\n\n \"\"\"\n self._set_opts(\n schema=schema, primitivesAsString=primitivesAsString, prefersDecimal=prefersDecimal,\n allowComments=allowComments, allowUnquotedFieldNames=allowUnquotedFieldNames,\n allowSingleQuotes=allowSingleQuotes, allowNumericLeadingZero=allowNumericLeadingZero,\n allowBackslashEscapingAnyCharacter=allowBackslashEscapingAnyCharacter,\n mode=mode, columnNameOfCorruptRecord=columnNameOfCorruptRecord, dateFormat=dateFormat,\n timestampFormat=timestampFormat, multiLine=multiLine,\n allowUnquotedControlChars=allowUnquotedControlChars, lineSep=lineSep,\n samplingRatio=samplingRatio, dropFieldIfAllNull=dropFieldIfAllNull, encoding=encoding,\n locale=locale)\n if isinstance(path, basestring):\n path = [path]\n if type(path) == list:\n return self._df(self._jreader.json(self._spark._sc._jvm.PythonUtils.toSeq(path)))\n elif isinstance(path, RDD):\n def func(iterator):\n for x in iterator:\n if not isinstance(x, basestring):\n x = unicode(x)\n if isinstance(x, unicode):\n x = x.encode(\"utf-8\")\n yield x\n keyed = path.mapPartitions(func)\n keyed._bypass_serializer = True\n jrdd = keyed._jrdd.map(self._spark._jvm.BytesToString())\n return self._df(self._jreader.json(jrdd))\n else:\n raise TypeError(\"path can be only string, list or RDD\")" }, { "instruction": "Write or improve a Python function based on this description:\n\nLoads Parquet files, returning the result as a :class:`DataFrame`.\n\n You can set the following Parquet-specific option(s) for reading Parquet files:\n * ``mergeSchema``: sets whether we should merge schemas collected from all \\\n Parquet part-files. This will override ``spark.sql.parquet.mergeSchema``. \\\n The default value is specified in ``spark.sql.parquet.mergeSchema``.\n\n >>> df = spark.read.parquet('python/test_support/sql/parquet_partitioned')\n >>> df.dtypes\n [('name', 'string'), ('year', 'int'), ('month', 'int'), ('day', 'int')]", "output": "def parquet(self, *paths):\n \"\"\"Loads Parquet files, returning the result as a :class:`DataFrame`.\n\n You can set the following Parquet-specific option(s) for reading Parquet files:\n * ``mergeSchema``: sets whether we should merge schemas collected from all \\\n Parquet part-files. This will override ``spark.sql.parquet.mergeSchema``. \\\n The default value is specified in ``spark.sql.parquet.mergeSchema``.\n\n >>> df = spark.read.parquet('python/test_support/sql/parquet_partitioned')\n >>> df.dtypes\n [('name', 'string'), ('year', 'int'), ('month', 'int'), ('day', 'int')]\n \"\"\"\n return self._df(self._jreader.parquet(_to_seq(self._spark._sc, paths)))" }, { "instruction": "Write or improve a Python function based on this description:\n\nLoads text files and returns a :class:`DataFrame` whose schema starts with a\n string column named \"value\", and followed by partitioned columns if there\n are any.\n The text files must be encoded as UTF-8.\n\n By default, each line in the text file is a new row in the resulting DataFrame.\n\n :param paths: string, or list of strings, for input path(s).\n :param wholetext: if true, read each file from input path(s) as a single row.\n :param lineSep: defines the line separator that should be used for parsing. If None is\n set, it covers all ``\\\\r``, ``\\\\r\\\\n`` and ``\\\\n``.\n\n >>> df = spark.read.text('python/test_support/sql/text-test.txt')\n >>> df.collect()\n [Row(value=u'hello'), Row(value=u'this')]\n >>> df = spark.read.text('python/test_support/sql/text-test.txt', wholetext=True)\n >>> df.collect()\n [Row(value=u'hello\\\\nthis')]", "output": "def text(self, paths, wholetext=False, lineSep=None):\n \"\"\"\n Loads text files and returns a :class:`DataFrame` whose schema starts with a\n string column named \"value\", and followed by partitioned columns if there\n are any.\n The text files must be encoded as UTF-8.\n\n By default, each line in the text file is a new row in the resulting DataFrame.\n\n :param paths: string, or list of strings, for input path(s).\n :param wholetext: if true, read each file from input path(s) as a single row.\n :param lineSep: defines the line separator that should be used for parsing. If None is\n set, it covers all ``\\\\r``, ``\\\\r\\\\n`` and ``\\\\n``.\n\n >>> df = spark.read.text('python/test_support/sql/text-test.txt')\n >>> df.collect()\n [Row(value=u'hello'), Row(value=u'this')]\n >>> df = spark.read.text('python/test_support/sql/text-test.txt', wholetext=True)\n >>> df.collect()\n [Row(value=u'hello\\\\nthis')]\n \"\"\"\n self._set_opts(wholetext=wholetext, lineSep=lineSep)\n if isinstance(paths, basestring):\n paths = [paths]\n return self._df(self._jreader.text(self._spark._sc._jvm.PythonUtils.toSeq(paths)))" }, { "instruction": "Write or improve a Python function based on this description:\n\nr\"\"\"Loads a CSV file and returns the result as a :class:`DataFrame`.\n\n This function will go through the input once to determine the input schema if\n ``inferSchema`` is enabled. To avoid going through the entire data once, disable\n ``inferSchema`` option or specify the schema explicitly using ``schema``.\n\n :param path: string, or list of strings, for input path(s),\n or RDD of Strings storing CSV rows.\n :param schema: an optional :class:`pyspark.sql.types.StructType` for the input schema\n or a DDL-formatted string (For example ``col0 INT, col1 DOUBLE``).\n :param sep: sets a single character as a separator for each field and value.\n If None is set, it uses the default value, ``,``.\n :param encoding: decodes the CSV files by the given encoding type. If None is set,\n it uses the default value, ``UTF-8``.\n :param quote: sets a single character used for escaping quoted values where the\n separator can be part of the value. If None is set, it uses the default\n value, ``\"``. If you would like to turn off quotations, you need to set an\n empty string.\n :param escape: sets a single character used for escaping quotes inside an already\n quoted value. If None is set, it uses the default value, ``\\``.\n :param comment: sets a single character used for skipping lines beginning with this\n character. By default (None), it is disabled.\n :param header: uses the first line as names of columns. If None is set, it uses the\n default value, ``false``.\n :param inferSchema: infers the input schema automatically from data. It requires one extra\n pass over the data. If None is set, it uses the default value, ``false``.\n :param enforceSchema: If it is set to ``true``, the specified or inferred schema will be\n forcibly applied to datasource files, and headers in CSV files will be\n ignored. If the option is set to ``false``, the schema will be\n validated against all headers in CSV files or the first header in RDD\n if the ``header`` option is set to ``true``. Field names in the schema\n and column names in CSV headers are checked by their positions\n taking into account ``spark.sql.caseSensitive``. If None is set,\n ``true`` is used by default. Though the default value is ``true``,\n it is recommended to disable the ``enforceSchema`` option\n to avoid incorrect results.\n :param ignoreLeadingWhiteSpace: A flag indicating whether or not leading whitespaces from\n values being read should be skipped. If None is set, it\n uses the default value, ``false``.\n :param ignoreTrailingWhiteSpace: A flag indicating whether or not trailing whitespaces from\n values being read should be skipped. If None is set, it\n uses the default value, ``false``.\n :param nullValue: sets the string representation of a null value. If None is set, it uses\n the default value, empty string. Since 2.0.1, this ``nullValue`` param\n applies to all supported types including the string type.\n :param nanValue: sets the string representation of a non-number value. If None is set, it\n uses the default value, ``NaN``.\n :param positiveInf: sets the string representation of a positive infinity value. If None\n is set, it uses the default value, ``Inf``.\n :param negativeInf: sets the string representation of a negative infinity value. If None\n is set, it uses the default value, ``Inf``.\n :param dateFormat: sets the string that indicates a date format. Custom date formats\n follow the formats at ``java.time.format.DateTimeFormatter``. This\n applies to date type. If None is set, it uses the\n default value, ``yyyy-MM-dd``.\n :param timestampFormat: sets the string that indicates a timestamp format.\n Custom date formats follow the formats at\n ``java.time.format.DateTimeFormatter``.\n This applies to timestamp type. If None is set, it uses the\n default value, ``yyyy-MM-dd'T'HH:mm:ss.SSSXXX``.\n :param maxColumns: defines a hard limit of how many columns a record can have. If None is\n set, it uses the default value, ``20480``.\n :param maxCharsPerColumn: defines the maximum number of characters allowed for any given\n value being read. If None is set, it uses the default value,\n ``-1`` meaning unlimited length.\n :param maxMalformedLogPerPartition: this parameter is no longer used since Spark 2.2.0.\n If specified, it is ignored.\n :param mode: allows a mode for dealing with corrupt records during parsing. If None is\n set, it uses the default value, ``PERMISSIVE``.\n\n * ``PERMISSIVE`` : when it meets a corrupted record, puts the malformed string \\\n into a field configured by ``columnNameOfCorruptRecord``, and sets malformed \\\n fields to ``null``. To keep corrupt records, an user can set a string type \\\n field named ``columnNameOfCorruptRecord`` in an user-defined schema. If a \\\n schema does not have the field, it drops corrupt records during parsing. \\\n A record with less/more tokens than schema is not a corrupted record to CSV. \\\n When it meets a record having fewer tokens than the length of the schema, \\\n sets ``null`` to extra fields. When the record has more tokens than the \\\n length of the schema, it drops extra tokens.\n * ``DROPMALFORMED`` : ignores the whole corrupted records.\n * ``FAILFAST`` : throws an exception when it meets corrupted records.\n\n :param columnNameOfCorruptRecord: allows renaming the new field having malformed string\n created by ``PERMISSIVE`` mode. This overrides\n ``spark.sql.columnNameOfCorruptRecord``. If None is set,\n it uses the value specified in\n ``spark.sql.columnNameOfCorruptRecord``.\n :param multiLine: parse records, which may span multiple lines. If None is\n set, it uses the default value, ``false``.\n :param charToEscapeQuoteEscaping: sets a single character used for escaping the escape for\n the quote character. If None is set, the default value is\n escape character when escape and quote characters are\n different, ``\\0`` otherwise.\n :param samplingRatio: defines fraction of rows used for schema inferring.\n If None is set, it uses the default value, ``1.0``.\n :param emptyValue: sets the string representation of an empty value. If None is set, it uses\n the default value, empty string.\n :param locale: sets a locale as language tag in IETF BCP 47 format. If None is set,\n it uses the default value, ``en-US``. For instance, ``locale`` is used while\n parsing dates and timestamps.\n :param lineSep: defines the line separator that should be used for parsing. If None is\n set, it covers all ``\\\\r``, ``\\\\r\\\\n`` and ``\\\\n``.\n Maximum length is 1 character.\n\n >>> df = spark.read.csv('python/test_support/sql/ages.csv')\n >>> df.dtypes\n [('_c0', 'string'), ('_c1', 'string')]\n >>> rdd = sc.textFile('python/test_support/sql/ages.csv')\n >>> df2 = spark.read.csv(rdd)\n >>> df2.dtypes\n [('_c0', 'string'), ('_c1', 'string')]", "output": "def csv(self, path, schema=None, sep=None, encoding=None, quote=None, escape=None,\n comment=None, header=None, inferSchema=None, ignoreLeadingWhiteSpace=None,\n ignoreTrailingWhiteSpace=None, nullValue=None, nanValue=None, positiveInf=None,\n negativeInf=None, dateFormat=None, timestampFormat=None, maxColumns=None,\n maxCharsPerColumn=None, maxMalformedLogPerPartition=None, mode=None,\n columnNameOfCorruptRecord=None, multiLine=None, charToEscapeQuoteEscaping=None,\n samplingRatio=None, enforceSchema=None, emptyValue=None, locale=None, lineSep=None):\n r\"\"\"Loads a CSV file and returns the result as a :class:`DataFrame`.\n\n This function will go through the input once to determine the input schema if\n ``inferSchema`` is enabled. To avoid going through the entire data once, disable\n ``inferSchema`` option or specify the schema explicitly using ``schema``.\n\n :param path: string, or list of strings, for input path(s),\n or RDD of Strings storing CSV rows.\n :param schema: an optional :class:`pyspark.sql.types.StructType` for the input schema\n or a DDL-formatted string (For example ``col0 INT, col1 DOUBLE``).\n :param sep: sets a single character as a separator for each field and value.\n If None is set, it uses the default value, ``,``.\n :param encoding: decodes the CSV files by the given encoding type. If None is set,\n it uses the default value, ``UTF-8``.\n :param quote: sets a single character used for escaping quoted values where the\n separator can be part of the value. If None is set, it uses the default\n value, ``\"``. If you would like to turn off quotations, you need to set an\n empty string.\n :param escape: sets a single character used for escaping quotes inside an already\n quoted value. If None is set, it uses the default value, ``\\``.\n :param comment: sets a single character used for skipping lines beginning with this\n character. By default (None), it is disabled.\n :param header: uses the first line as names of columns. If None is set, it uses the\n default value, ``false``.\n :param inferSchema: infers the input schema automatically from data. It requires one extra\n pass over the data. If None is set, it uses the default value, ``false``.\n :param enforceSchema: If it is set to ``true``, the specified or inferred schema will be\n forcibly applied to datasource files, and headers in CSV files will be\n ignored. If the option is set to ``false``, the schema will be\n validated against all headers in CSV files or the first header in RDD\n if the ``header`` option is set to ``true``. Field names in the schema\n and column names in CSV headers are checked by their positions\n taking into account ``spark.sql.caseSensitive``. If None is set,\n ``true`` is used by default. Though the default value is ``true``,\n it is recommended to disable the ``enforceSchema`` option\n to avoid incorrect results.\n :param ignoreLeadingWhiteSpace: A flag indicating whether or not leading whitespaces from\n values being read should be skipped. If None is set, it\n uses the default value, ``false``.\n :param ignoreTrailingWhiteSpace: A flag indicating whether or not trailing whitespaces from\n values being read should be skipped. If None is set, it\n uses the default value, ``false``.\n :param nullValue: sets the string representation of a null value. If None is set, it uses\n the default value, empty string. Since 2.0.1, this ``nullValue`` param\n applies to all supported types including the string type.\n :param nanValue: sets the string representation of a non-number value. If None is set, it\n uses the default value, ``NaN``.\n :param positiveInf: sets the string representation of a positive infinity value. If None\n is set, it uses the default value, ``Inf``.\n :param negativeInf: sets the string representation of a negative infinity value. If None\n is set, it uses the default value, ``Inf``.\n :param dateFormat: sets the string that indicates a date format. Custom date formats\n follow the formats at ``java.time.format.DateTimeFormatter``. This\n applies to date type. If None is set, it uses the\n default value, ``yyyy-MM-dd``.\n :param timestampFormat: sets the string that indicates a timestamp format.\n Custom date formats follow the formats at\n ``java.time.format.DateTimeFormatter``.\n This applies to timestamp type. If None is set, it uses the\n default value, ``yyyy-MM-dd'T'HH:mm:ss.SSSXXX``.\n :param maxColumns: defines a hard limit of how many columns a record can have. If None is\n set, it uses the default value, ``20480``.\n :param maxCharsPerColumn: defines the maximum number of characters allowed for any given\n value being read. If None is set, it uses the default value,\n ``-1`` meaning unlimited length.\n :param maxMalformedLogPerPartition: this parameter is no longer used since Spark 2.2.0.\n If specified, it is ignored.\n :param mode: allows a mode for dealing with corrupt records during parsing. If None is\n set, it uses the default value, ``PERMISSIVE``.\n\n * ``PERMISSIVE`` : when it meets a corrupted record, puts the malformed string \\\n into a field configured by ``columnNameOfCorruptRecord``, and sets malformed \\\n fields to ``null``. To keep corrupt records, an user can set a string type \\\n field named ``columnNameOfCorruptRecord`` in an user-defined schema. If a \\\n schema does not have the field, it drops corrupt records during parsing. \\\n A record with less/more tokens than schema is not a corrupted record to CSV. \\\n When it meets a record having fewer tokens than the length of the schema, \\\n sets ``null`` to extra fields. When the record has more tokens than the \\\n length of the schema, it drops extra tokens.\n * ``DROPMALFORMED`` : ignores the whole corrupted records.\n * ``FAILFAST`` : throws an exception when it meets corrupted records.\n\n :param columnNameOfCorruptRecord: allows renaming the new field having malformed string\n created by ``PERMISSIVE`` mode. This overrides\n ``spark.sql.columnNameOfCorruptRecord``. If None is set,\n it uses the value specified in\n ``spark.sql.columnNameOfCorruptRecord``.\n :param multiLine: parse records, which may span multiple lines. If None is\n set, it uses the default value, ``false``.\n :param charToEscapeQuoteEscaping: sets a single character used for escaping the escape for\n the quote character. If None is set, the default value is\n escape character when escape and quote characters are\n different, ``\\0`` otherwise.\n :param samplingRatio: defines fraction of rows used for schema inferring.\n If None is set, it uses the default value, ``1.0``.\n :param emptyValue: sets the string representation of an empty value. If None is set, it uses\n the default value, empty string.\n :param locale: sets a locale as language tag in IETF BCP 47 format. If None is set,\n it uses the default value, ``en-US``. For instance, ``locale`` is used while\n parsing dates and timestamps.\n :param lineSep: defines the line separator that should be used for parsing. If None is\n set, it covers all ``\\\\r``, ``\\\\r\\\\n`` and ``\\\\n``.\n Maximum length is 1 character.\n\n >>> df = spark.read.csv('python/test_support/sql/ages.csv')\n >>> df.dtypes\n [('_c0', 'string'), ('_c1', 'string')]\n >>> rdd = sc.textFile('python/test_support/sql/ages.csv')\n >>> df2 = spark.read.csv(rdd)\n >>> df2.dtypes\n [('_c0', 'string'), ('_c1', 'string')]\n \"\"\"\n self._set_opts(\n schema=schema, sep=sep, encoding=encoding, quote=quote, escape=escape, comment=comment,\n header=header, inferSchema=inferSchema, ignoreLeadingWhiteSpace=ignoreLeadingWhiteSpace,\n ignoreTrailingWhiteSpace=ignoreTrailingWhiteSpace, nullValue=nullValue,\n nanValue=nanValue, positiveInf=positiveInf, negativeInf=negativeInf,\n dateFormat=dateFormat, timestampFormat=timestampFormat, maxColumns=maxColumns,\n maxCharsPerColumn=maxCharsPerColumn,\n maxMalformedLogPerPartition=maxMalformedLogPerPartition, mode=mode,\n columnNameOfCorruptRecord=columnNameOfCorruptRecord, multiLine=multiLine,\n charToEscapeQuoteEscaping=charToEscapeQuoteEscaping, samplingRatio=samplingRatio,\n enforceSchema=enforceSchema, emptyValue=emptyValue, locale=locale, lineSep=lineSep)\n if isinstance(path, basestring):\n path = [path]\n if type(path) == list:\n return self._df(self._jreader.csv(self._spark._sc._jvm.PythonUtils.toSeq(path)))\n elif isinstance(path, RDD):\n def func(iterator):\n for x in iterator:\n if not isinstance(x, basestring):\n x = unicode(x)\n if isinstance(x, unicode):\n x = x.encode(\"utf-8\")\n yield x\n keyed = path.mapPartitions(func)\n keyed._bypass_serializer = True\n jrdd = keyed._jrdd.map(self._spark._jvm.BytesToString())\n # see SPARK-22112\n # There aren't any jvm api for creating a dataframe from rdd storing csv.\n # We can do it through creating a jvm dataset firstly and using the jvm api\n # for creating a dataframe from dataset storing csv.\n jdataset = self._spark._ssql_ctx.createDataset(\n jrdd.rdd(),\n self._spark._jvm.Encoders.STRING())\n return self._df(self._jreader.csv(jdataset))\n else:\n raise TypeError(\"path can be only string, list or RDD\")" }, { "instruction": "Write or improve a Python function based on this description:\n\nLoads ORC files, returning the result as a :class:`DataFrame`.\n\n >>> df = spark.read.orc('python/test_support/sql/orc_partitioned')\n >>> df.dtypes\n [('a', 'bigint'), ('b', 'int'), ('c', 'int')]", "output": "def orc(self, path):\n \"\"\"Loads ORC files, returning the result as a :class:`DataFrame`.\n\n >>> df = spark.read.orc('python/test_support/sql/orc_partitioned')\n >>> df.dtypes\n [('a', 'bigint'), ('b', 'int'), ('c', 'int')]\n \"\"\"\n if isinstance(path, basestring):\n path = [path]\n return self._df(self._jreader.orc(_to_seq(self._spark._sc, path)))" }, { "instruction": "Write or improve a Python function based on this description:\n\nConstruct a :class:`DataFrame` representing the database table named ``table``\n accessible via JDBC URL ``url`` and connection ``properties``.\n\n Partitions of the table will be retrieved in parallel if either ``column`` or\n ``predicates`` is specified. ``lowerBound`, ``upperBound`` and ``numPartitions``\n is needed when ``column`` is specified.\n\n If both ``column`` and ``predicates`` are specified, ``column`` will be used.\n\n .. note:: Don't create too many partitions in parallel on a large cluster;\n otherwise Spark might crash your external database systems.\n\n :param url: a JDBC URL of the form ``jdbc:subprotocol:subname``\n :param table: the name of the table\n :param column: the name of an integer column that will be used for partitioning;\n if this parameter is specified, then ``numPartitions``, ``lowerBound``\n (inclusive), and ``upperBound`` (exclusive) will form partition strides\n for generated WHERE clause expressions used to split the column\n ``column`` evenly\n :param lowerBound: the minimum value of ``column`` used to decide partition stride\n :param upperBound: the maximum value of ``column`` used to decide partition stride\n :param numPartitions: the number of partitions\n :param predicates: a list of expressions suitable for inclusion in WHERE clauses;\n each one defines one partition of the :class:`DataFrame`\n :param properties: a dictionary of JDBC database connection arguments. Normally at\n least properties \"user\" and \"password\" with their corresponding values.\n For example { 'user' : 'SYSTEM', 'password' : 'mypassword' }\n :return: a DataFrame", "output": "def jdbc(self, url, table, column=None, lowerBound=None, upperBound=None, numPartitions=None,\n predicates=None, properties=None):\n \"\"\"\n Construct a :class:`DataFrame` representing the database table named ``table``\n accessible via JDBC URL ``url`` and connection ``properties``.\n\n Partitions of the table will be retrieved in parallel if either ``column`` or\n ``predicates`` is specified. ``lowerBound`, ``upperBound`` and ``numPartitions``\n is needed when ``column`` is specified.\n\n If both ``column`` and ``predicates`` are specified, ``column`` will be used.\n\n .. note:: Don't create too many partitions in parallel on a large cluster;\n otherwise Spark might crash your external database systems.\n\n :param url: a JDBC URL of the form ``jdbc:subprotocol:subname``\n :param table: the name of the table\n :param column: the name of an integer column that will be used for partitioning;\n if this parameter is specified, then ``numPartitions``, ``lowerBound``\n (inclusive), and ``upperBound`` (exclusive) will form partition strides\n for generated WHERE clause expressions used to split the column\n ``column`` evenly\n :param lowerBound: the minimum value of ``column`` used to decide partition stride\n :param upperBound: the maximum value of ``column`` used to decide partition stride\n :param numPartitions: the number of partitions\n :param predicates: a list of expressions suitable for inclusion in WHERE clauses;\n each one defines one partition of the :class:`DataFrame`\n :param properties: a dictionary of JDBC database connection arguments. Normally at\n least properties \"user\" and \"password\" with their corresponding values.\n For example { 'user' : 'SYSTEM', 'password' : 'mypassword' }\n :return: a DataFrame\n \"\"\"\n if properties is None:\n properties = dict()\n jprop = JavaClass(\"java.util.Properties\", self._spark._sc._gateway._gateway_client)()\n for k in properties:\n jprop.setProperty(k, properties[k])\n if column is not None:\n assert lowerBound is not None, \"lowerBound can not be None when ``column`` is specified\"\n assert upperBound is not None, \"upperBound can not be None when ``column`` is specified\"\n assert numPartitions is not None, \\\n \"numPartitions can not be None when ``column`` is specified\"\n return self._df(self._jreader.jdbc(url, table, column, int(lowerBound), int(upperBound),\n int(numPartitions), jprop))\n if predicates is not None:\n gateway = self._spark._sc._gateway\n jpredicates = utils.toJArray(gateway, gateway.jvm.java.lang.String, predicates)\n return self._df(self._jreader.jdbc(url, table, jpredicates, jprop))\n return self._df(self._jreader.jdbc(url, table, jprop))" }, { "instruction": "Write or improve a Python function based on this description:\n\nSpecifies the behavior when data or table already exists.\n\n Options include:\n\n * `append`: Append contents of this :class:`DataFrame` to existing data.\n * `overwrite`: Overwrite existing data.\n * `error` or `errorifexists`: Throw an exception if data already exists.\n * `ignore`: Silently ignore this operation if data already exists.\n\n >>> df.write.mode('append').parquet(os.path.join(tempfile.mkdtemp(), 'data'))", "output": "def mode(self, saveMode):\n \"\"\"Specifies the behavior when data or table already exists.\n\n Options include:\n\n * `append`: Append contents of this :class:`DataFrame` to existing data.\n * `overwrite`: Overwrite existing data.\n * `error` or `errorifexists`: Throw an exception if data already exists.\n * `ignore`: Silently ignore this operation if data already exists.\n\n >>> df.write.mode('append').parquet(os.path.join(tempfile.mkdtemp(), 'data'))\n \"\"\"\n # At the JVM side, the default value of mode is already set to \"error\".\n # So, if the given saveMode is None, we will not call JVM-side's mode method.\n if saveMode is not None:\n self._jwrite = self._jwrite.mode(saveMode)\n return self" }, { "instruction": "Write or improve a Python function based on this description:\n\nSpecifies the underlying output data source.\n\n :param source: string, name of the data source, e.g. 'json', 'parquet'.\n\n >>> df.write.format('json').save(os.path.join(tempfile.mkdtemp(), 'data'))", "output": "def format(self, source):\n \"\"\"Specifies the underlying output data source.\n\n :param source: string, name of the data source, e.g. 'json', 'parquet'.\n\n >>> df.write.format('json').save(os.path.join(tempfile.mkdtemp(), 'data'))\n \"\"\"\n self._jwrite = self._jwrite.format(source)\n return self" }, { "instruction": "Write or improve a Python function based on this description:\n\nAdds an output option for the underlying data source.\n\n You can set the following option(s) for writing files:\n * ``timeZone``: sets the string that indicates a timezone to be used to format\n timestamps in the JSON/CSV datasources or partition values.\n If it isn't set, it uses the default value, session local timezone.", "output": "def option(self, key, value):\n \"\"\"Adds an output option for the underlying data source.\n\n You can set the following option(s) for writing files:\n * ``timeZone``: sets the string that indicates a timezone to be used to format\n timestamps in the JSON/CSV datasources or partition values.\n If it isn't set, it uses the default value, session local timezone.\n \"\"\"\n self._jwrite = self._jwrite.option(key, to_str(value))\n return self" }, { "instruction": "Write or improve a Python function based on this description:\n\nAdds output options for the underlying data source.\n\n You can set the following option(s) for writing files:\n * ``timeZone``: sets the string that indicates a timezone to be used to format\n timestamps in the JSON/CSV datasources or partition values.\n If it isn't set, it uses the default value, session local timezone.", "output": "def options(self, **options):\n \"\"\"Adds output options for the underlying data source.\n\n You can set the following option(s) for writing files:\n * ``timeZone``: sets the string that indicates a timezone to be used to format\n timestamps in the JSON/CSV datasources or partition values.\n If it isn't set, it uses the default value, session local timezone.\n \"\"\"\n for k in options:\n self._jwrite = self._jwrite.option(k, to_str(options[k]))\n return self" }, { "instruction": "Write or improve a Python function based on this description:\n\nPartitions the output by the given columns on the file system.\n\n If specified, the output is laid out on the file system similar\n to Hive's partitioning scheme.\n\n :param cols: name of columns\n\n >>> df.write.partitionBy('year', 'month').parquet(os.path.join(tempfile.mkdtemp(), 'data'))", "output": "def partitionBy(self, *cols):\n \"\"\"Partitions the output by the given columns on the file system.\n\n If specified, the output is laid out on the file system similar\n to Hive's partitioning scheme.\n\n :param cols: name of columns\n\n >>> df.write.partitionBy('year', 'month').parquet(os.path.join(tempfile.mkdtemp(), 'data'))\n \"\"\"\n if len(cols) == 1 and isinstance(cols[0], (list, tuple)):\n cols = cols[0]\n self._jwrite = self._jwrite.partitionBy(_to_seq(self._spark._sc, cols))\n return self" }, { "instruction": "Write or improve a Python function based on this description:\n\nSorts the output in each bucket by the given columns on the file system.\n\n :param col: a name of a column, or a list of names.\n :param cols: additional names (optional). If `col` is a list it should be empty.\n\n >>> (df.write.format('parquet') # doctest: +SKIP\n ... .bucketBy(100, 'year', 'month')\n ... .sortBy('day')\n ... .mode(\"overwrite\")\n ... .saveAsTable('sorted_bucketed_table'))", "output": "def sortBy(self, col, *cols):\n \"\"\"Sorts the output in each bucket by the given columns on the file system.\n\n :param col: a name of a column, or a list of names.\n :param cols: additional names (optional). If `col` is a list it should be empty.\n\n >>> (df.write.format('parquet') # doctest: +SKIP\n ... .bucketBy(100, 'year', 'month')\n ... .sortBy('day')\n ... .mode(\"overwrite\")\n ... .saveAsTable('sorted_bucketed_table'))\n \"\"\"\n if isinstance(col, (list, tuple)):\n if cols:\n raise ValueError(\"col is a {0} but cols are not empty\".format(type(col)))\n\n col, cols = col[0], col[1:]\n\n if not all(isinstance(c, basestring) for c in cols) or not(isinstance(col, basestring)):\n raise TypeError(\"all names should be `str`\")\n\n self._jwrite = self._jwrite.sortBy(col, _to_seq(self._spark._sc, cols))\n return self" }, { "instruction": "Write or improve a Python function based on this description:\n\nSaves the contents of the :class:`DataFrame` to a data source.\n\n The data source is specified by the ``format`` and a set of ``options``.\n If ``format`` is not specified, the default data source configured by\n ``spark.sql.sources.default`` will be used.\n\n :param path: the path in a Hadoop supported file system\n :param format: the format used to save\n :param mode: specifies the behavior of the save operation when data already exists.\n\n * ``append``: Append contents of this :class:`DataFrame` to existing data.\n * ``overwrite``: Overwrite existing data.\n * ``ignore``: Silently ignore this operation if data already exists.\n * ``error`` or ``errorifexists`` (default case): Throw an exception if data already \\\n exists.\n :param partitionBy: names of partitioning columns\n :param options: all other string options\n\n >>> df.write.mode('append').parquet(os.path.join(tempfile.mkdtemp(), 'data'))", "output": "def save(self, path=None, format=None, mode=None, partitionBy=None, **options):\n \"\"\"Saves the contents of the :class:`DataFrame` to a data source.\n\n The data source is specified by the ``format`` and a set of ``options``.\n If ``format`` is not specified, the default data source configured by\n ``spark.sql.sources.default`` will be used.\n\n :param path: the path in a Hadoop supported file system\n :param format: the format used to save\n :param mode: specifies the behavior of the save operation when data already exists.\n\n * ``append``: Append contents of this :class:`DataFrame` to existing data.\n * ``overwrite``: Overwrite existing data.\n * ``ignore``: Silently ignore this operation if data already exists.\n * ``error`` or ``errorifexists`` (default case): Throw an exception if data already \\\n exists.\n :param partitionBy: names of partitioning columns\n :param options: all other string options\n\n >>> df.write.mode('append').parquet(os.path.join(tempfile.mkdtemp(), 'data'))\n \"\"\"\n self.mode(mode).options(**options)\n if partitionBy is not None:\n self.partitionBy(partitionBy)\n if format is not None:\n self.format(format)\n if path is None:\n self._jwrite.save()\n else:\n self._jwrite.save(path)" }, { "instruction": "Write or improve a Python function based on this description:\n\nInserts the content of the :class:`DataFrame` to the specified table.\n\n It requires that the schema of the class:`DataFrame` is the same as the\n schema of the table.\n\n Optionally overwriting any existing data.", "output": "def insertInto(self, tableName, overwrite=False):\n \"\"\"Inserts the content of the :class:`DataFrame` to the specified table.\n\n It requires that the schema of the class:`DataFrame` is the same as the\n schema of the table.\n\n Optionally overwriting any existing data.\n \"\"\"\n self._jwrite.mode(\"overwrite\" if overwrite else \"append\").insertInto(tableName)" }, { "instruction": "Write or improve a Python function based on this description:\n\nSaves the content of the :class:`DataFrame` as the specified table.\n\n In the case the table already exists, behavior of this function depends on the\n save mode, specified by the `mode` function (default to throwing an exception).\n When `mode` is `Overwrite`, the schema of the :class:`DataFrame` does not need to be\n the same as that of the existing table.\n\n * `append`: Append contents of this :class:`DataFrame` to existing data.\n * `overwrite`: Overwrite existing data.\n * `error` or `errorifexists`: Throw an exception if data already exists.\n * `ignore`: Silently ignore this operation if data already exists.\n\n :param name: the table name\n :param format: the format used to save\n :param mode: one of `append`, `overwrite`, `error`, `errorifexists`, `ignore` \\\n (default: error)\n :param partitionBy: names of partitioning columns\n :param options: all other string options", "output": "def saveAsTable(self, name, format=None, mode=None, partitionBy=None, **options):\n \"\"\"Saves the content of the :class:`DataFrame` as the specified table.\n\n In the case the table already exists, behavior of this function depends on the\n save mode, specified by the `mode` function (default to throwing an exception).\n When `mode` is `Overwrite`, the schema of the :class:`DataFrame` does not need to be\n the same as that of the existing table.\n\n * `append`: Append contents of this :class:`DataFrame` to existing data.\n * `overwrite`: Overwrite existing data.\n * `error` or `errorifexists`: Throw an exception if data already exists.\n * `ignore`: Silently ignore this operation if data already exists.\n\n :param name: the table name\n :param format: the format used to save\n :param mode: one of `append`, `overwrite`, `error`, `errorifexists`, `ignore` \\\n (default: error)\n :param partitionBy: names of partitioning columns\n :param options: all other string options\n \"\"\"\n self.mode(mode).options(**options)\n if partitionBy is not None:\n self.partitionBy(partitionBy)\n if format is not None:\n self.format(format)\n self._jwrite.saveAsTable(name)" }, { "instruction": "Write or improve a Python function based on this description:\n\nSaves the content of the :class:`DataFrame` in JSON format\n (`JSON Lines text format or newline-delimited JSON `_) at the\n specified path.\n\n :param path: the path in any Hadoop supported file system\n :param mode: specifies the behavior of the save operation when data already exists.\n\n * ``append``: Append contents of this :class:`DataFrame` to existing data.\n * ``overwrite``: Overwrite existing data.\n * ``ignore``: Silently ignore this operation if data already exists.\n * ``error`` or ``errorifexists`` (default case): Throw an exception if data already \\\n exists.\n :param compression: compression codec to use when saving to file. This can be one of the\n known case-insensitive shorten names (none, bzip2, gzip, lz4,\n snappy and deflate).\n :param dateFormat: sets the string that indicates a date format. Custom date formats\n follow the formats at ``java.time.format.DateTimeFormatter``. This\n applies to date type. If None is set, it uses the\n default value, ``yyyy-MM-dd``.\n :param timestampFormat: sets the string that indicates a timestamp format.\n Custom date formats follow the formats at\n ``java.time.format.DateTimeFormatter``.\n This applies to timestamp type. If None is set, it uses the\n default value, ``yyyy-MM-dd'T'HH:mm:ss.SSSXXX``.\n :param encoding: specifies encoding (charset) of saved json files. If None is set,\n the default UTF-8 charset will be used.\n :param lineSep: defines the line separator that should be used for writing. If None is\n set, it uses the default value, ``\\\\n``.\n\n >>> df.write.json(os.path.join(tempfile.mkdtemp(), 'data'))", "output": "def json(self, path, mode=None, compression=None, dateFormat=None, timestampFormat=None,\n lineSep=None, encoding=None):\n \"\"\"Saves the content of the :class:`DataFrame` in JSON format\n (`JSON Lines text format or newline-delimited JSON `_) at the\n specified path.\n\n :param path: the path in any Hadoop supported file system\n :param mode: specifies the behavior of the save operation when data already exists.\n\n * ``append``: Append contents of this :class:`DataFrame` to existing data.\n * ``overwrite``: Overwrite existing data.\n * ``ignore``: Silently ignore this operation if data already exists.\n * ``error`` or ``errorifexists`` (default case): Throw an exception if data already \\\n exists.\n :param compression: compression codec to use when saving to file. This can be one of the\n known case-insensitive shorten names (none, bzip2, gzip, lz4,\n snappy and deflate).\n :param dateFormat: sets the string that indicates a date format. Custom date formats\n follow the formats at ``java.time.format.DateTimeFormatter``. This\n applies to date type. If None is set, it uses the\n default value, ``yyyy-MM-dd``.\n :param timestampFormat: sets the string that indicates a timestamp format.\n Custom date formats follow the formats at\n ``java.time.format.DateTimeFormatter``.\n This applies to timestamp type. If None is set, it uses the\n default value, ``yyyy-MM-dd'T'HH:mm:ss.SSSXXX``.\n :param encoding: specifies encoding (charset) of saved json files. If None is set,\n the default UTF-8 charset will be used.\n :param lineSep: defines the line separator that should be used for writing. If None is\n set, it uses the default value, ``\\\\n``.\n\n >>> df.write.json(os.path.join(tempfile.mkdtemp(), 'data'))\n \"\"\"\n self.mode(mode)\n self._set_opts(\n compression=compression, dateFormat=dateFormat, timestampFormat=timestampFormat,\n lineSep=lineSep, encoding=encoding)\n self._jwrite.json(path)" }, { "instruction": "Write or improve a Python function based on this description:\n\nSaves the content of the :class:`DataFrame` in Parquet format at the specified path.\n\n :param path: the path in any Hadoop supported file system\n :param mode: specifies the behavior of the save operation when data already exists.\n\n * ``append``: Append contents of this :class:`DataFrame` to existing data.\n * ``overwrite``: Overwrite existing data.\n * ``ignore``: Silently ignore this operation if data already exists.\n * ``error`` or ``errorifexists`` (default case): Throw an exception if data already \\\n exists.\n :param partitionBy: names of partitioning columns\n :param compression: compression codec to use when saving to file. This can be one of the\n known case-insensitive shorten names (none, uncompressed, snappy, gzip,\n lzo, brotli, lz4, and zstd). This will override\n ``spark.sql.parquet.compression.codec``. If None is set, it uses the\n value specified in ``spark.sql.parquet.compression.codec``.\n\n >>> df.write.parquet(os.path.join(tempfile.mkdtemp(), 'data'))", "output": "def parquet(self, path, mode=None, partitionBy=None, compression=None):\n \"\"\"Saves the content of the :class:`DataFrame` in Parquet format at the specified path.\n\n :param path: the path in any Hadoop supported file system\n :param mode: specifies the behavior of the save operation when data already exists.\n\n * ``append``: Append contents of this :class:`DataFrame` to existing data.\n * ``overwrite``: Overwrite existing data.\n * ``ignore``: Silently ignore this operation if data already exists.\n * ``error`` or ``errorifexists`` (default case): Throw an exception if data already \\\n exists.\n :param partitionBy: names of partitioning columns\n :param compression: compression codec to use when saving to file. This can be one of the\n known case-insensitive shorten names (none, uncompressed, snappy, gzip,\n lzo, brotli, lz4, and zstd). This will override\n ``spark.sql.parquet.compression.codec``. If None is set, it uses the\n value specified in ``spark.sql.parquet.compression.codec``.\n\n >>> df.write.parquet(os.path.join(tempfile.mkdtemp(), 'data'))\n \"\"\"\n self.mode(mode)\n if partitionBy is not None:\n self.partitionBy(partitionBy)\n self._set_opts(compression=compression)\n self._jwrite.parquet(path)" }, { "instruction": "Write or improve a Python function based on this description:\n\nSaves the content of the DataFrame in a text file at the specified path.\n The text files will be encoded as UTF-8.\n\n :param path: the path in any Hadoop supported file system\n :param compression: compression codec to use when saving to file. This can be one of the\n known case-insensitive shorten names (none, bzip2, gzip, lz4,\n snappy and deflate).\n :param lineSep: defines the line separator that should be used for writing. If None is\n set, it uses the default value, ``\\\\n``.\n\n The DataFrame must have only one column that is of string type.\n Each row becomes a new line in the output file.", "output": "def text(self, path, compression=None, lineSep=None):\n \"\"\"Saves the content of the DataFrame in a text file at the specified path.\n The text files will be encoded as UTF-8.\n\n :param path: the path in any Hadoop supported file system\n :param compression: compression codec to use when saving to file. This can be one of the\n known case-insensitive shorten names (none, bzip2, gzip, lz4,\n snappy and deflate).\n :param lineSep: defines the line separator that should be used for writing. If None is\n set, it uses the default value, ``\\\\n``.\n\n The DataFrame must have only one column that is of string type.\n Each row becomes a new line in the output file.\n \"\"\"\n self._set_opts(compression=compression, lineSep=lineSep)\n self._jwrite.text(path)" }, { "instruction": "Write or improve a Python function based on this description:\n\nr\"\"\"Saves the content of the :class:`DataFrame` in CSV format at the specified path.\n\n :param path: the path in any Hadoop supported file system\n :param mode: specifies the behavior of the save operation when data already exists.\n\n * ``append``: Append contents of this :class:`DataFrame` to existing data.\n * ``overwrite``: Overwrite existing data.\n * ``ignore``: Silently ignore this operation if data already exists.\n * ``error`` or ``errorifexists`` (default case): Throw an exception if data already \\\n exists.\n\n :param compression: compression codec to use when saving to file. This can be one of the\n known case-insensitive shorten names (none, bzip2, gzip, lz4,\n snappy and deflate).\n :param sep: sets a single character as a separator for each field and value. If None is\n set, it uses the default value, ``,``.\n :param quote: sets a single character used for escaping quoted values where the\n separator can be part of the value. If None is set, it uses the default\n value, ``\"``. If an empty string is set, it uses ``u0000`` (null character).\n :param escape: sets a single character used for escaping quotes inside an already\n quoted value. If None is set, it uses the default value, ``\\``\n :param escapeQuotes: a flag indicating whether values containing quotes should always\n be enclosed in quotes. If None is set, it uses the default value\n ``true``, escaping all values containing a quote character.\n :param quoteAll: a flag indicating whether all values should always be enclosed in\n quotes. If None is set, it uses the default value ``false``,\n only escaping values containing a quote character.\n :param header: writes the names of columns as the first line. If None is set, it uses\n the default value, ``false``.\n :param nullValue: sets the string representation of a null value. If None is set, it uses\n the default value, empty string.\n :param dateFormat: sets the string that indicates a date format. Custom date formats\n follow the formats at ``java.time.format.DateTimeFormatter``. This\n applies to date type. If None is set, it uses the\n default value, ``yyyy-MM-dd``.\n :param timestampFormat: sets the string that indicates a timestamp format.\n Custom date formats follow the formats at\n ``java.time.format.DateTimeFormatter``.\n This applies to timestamp type. If None is set, it uses the\n default value, ``yyyy-MM-dd'T'HH:mm:ss.SSSXXX``.\n :param ignoreLeadingWhiteSpace: a flag indicating whether or not leading whitespaces from\n values being written should be skipped. If None is set, it\n uses the default value, ``true``.\n :param ignoreTrailingWhiteSpace: a flag indicating whether or not trailing whitespaces from\n values being written should be skipped. If None is set, it\n uses the default value, ``true``.\n :param charToEscapeQuoteEscaping: sets a single character used for escaping the escape for\n the quote character. If None is set, the default value is\n escape character when escape and quote characters are\n different, ``\\0`` otherwise..\n :param encoding: sets the encoding (charset) of saved csv files. If None is set,\n the default UTF-8 charset will be used.\n :param emptyValue: sets the string representation of an empty value. If None is set, it uses\n the default value, ``\"\"``.\n :param lineSep: defines the line separator that should be used for writing. If None is\n set, it uses the default value, ``\\\\n``. Maximum length is 1 character.\n\n >>> df.write.csv(os.path.join(tempfile.mkdtemp(), 'data'))", "output": "def csv(self, path, mode=None, compression=None, sep=None, quote=None, escape=None,\n header=None, nullValue=None, escapeQuotes=None, quoteAll=None, dateFormat=None,\n timestampFormat=None, ignoreLeadingWhiteSpace=None, ignoreTrailingWhiteSpace=None,\n charToEscapeQuoteEscaping=None, encoding=None, emptyValue=None, lineSep=None):\n r\"\"\"Saves the content of the :class:`DataFrame` in CSV format at the specified path.\n\n :param path: the path in any Hadoop supported file system\n :param mode: specifies the behavior of the save operation when data already exists.\n\n * ``append``: Append contents of this :class:`DataFrame` to existing data.\n * ``overwrite``: Overwrite existing data.\n * ``ignore``: Silently ignore this operation if data already exists.\n * ``error`` or ``errorifexists`` (default case): Throw an exception if data already \\\n exists.\n\n :param compression: compression codec to use when saving to file. This can be one of the\n known case-insensitive shorten names (none, bzip2, gzip, lz4,\n snappy and deflate).\n :param sep: sets a single character as a separator for each field and value. If None is\n set, it uses the default value, ``,``.\n :param quote: sets a single character used for escaping quoted values where the\n separator can be part of the value. If None is set, it uses the default\n value, ``\"``. If an empty string is set, it uses ``u0000`` (null character).\n :param escape: sets a single character used for escaping quotes inside an already\n quoted value. If None is set, it uses the default value, ``\\``\n :param escapeQuotes: a flag indicating whether values containing quotes should always\n be enclosed in quotes. If None is set, it uses the default value\n ``true``, escaping all values containing a quote character.\n :param quoteAll: a flag indicating whether all values should always be enclosed in\n quotes. If None is set, it uses the default value ``false``,\n only escaping values containing a quote character.\n :param header: writes the names of columns as the first line. If None is set, it uses\n the default value, ``false``.\n :param nullValue: sets the string representation of a null value. If None is set, it uses\n the default value, empty string.\n :param dateFormat: sets the string that indicates a date format. Custom date formats\n follow the formats at ``java.time.format.DateTimeFormatter``. This\n applies to date type. If None is set, it uses the\n default value, ``yyyy-MM-dd``.\n :param timestampFormat: sets the string that indicates a timestamp format.\n Custom date formats follow the formats at\n ``java.time.format.DateTimeFormatter``.\n This applies to timestamp type. If None is set, it uses the\n default value, ``yyyy-MM-dd'T'HH:mm:ss.SSSXXX``.\n :param ignoreLeadingWhiteSpace: a flag indicating whether or not leading whitespaces from\n values being written should be skipped. If None is set, it\n uses the default value, ``true``.\n :param ignoreTrailingWhiteSpace: a flag indicating whether or not trailing whitespaces from\n values being written should be skipped. If None is set, it\n uses the default value, ``true``.\n :param charToEscapeQuoteEscaping: sets a single character used for escaping the escape for\n the quote character. If None is set, the default value is\n escape character when escape and quote characters are\n different, ``\\0`` otherwise..\n :param encoding: sets the encoding (charset) of saved csv files. If None is set,\n the default UTF-8 charset will be used.\n :param emptyValue: sets the string representation of an empty value. If None is set, it uses\n the default value, ``\"\"``.\n :param lineSep: defines the line separator that should be used for writing. If None is\n set, it uses the default value, ``\\\\n``. Maximum length is 1 character.\n\n >>> df.write.csv(os.path.join(tempfile.mkdtemp(), 'data'))\n \"\"\"\n self.mode(mode)\n self._set_opts(compression=compression, sep=sep, quote=quote, escape=escape, header=header,\n nullValue=nullValue, escapeQuotes=escapeQuotes, quoteAll=quoteAll,\n dateFormat=dateFormat, timestampFormat=timestampFormat,\n ignoreLeadingWhiteSpace=ignoreLeadingWhiteSpace,\n ignoreTrailingWhiteSpace=ignoreTrailingWhiteSpace,\n charToEscapeQuoteEscaping=charToEscapeQuoteEscaping,\n encoding=encoding, emptyValue=emptyValue, lineSep=lineSep)\n self._jwrite.csv(path)" }, { "instruction": "Write or improve a Python function based on this description:\n\nSaves the content of the :class:`DataFrame` in ORC format at the specified path.\n\n :param path: the path in any Hadoop supported file system\n :param mode: specifies the behavior of the save operation when data already exists.\n\n * ``append``: Append contents of this :class:`DataFrame` to existing data.\n * ``overwrite``: Overwrite existing data.\n * ``ignore``: Silently ignore this operation if data already exists.\n * ``error`` or ``errorifexists`` (default case): Throw an exception if data already \\\n exists.\n :param partitionBy: names of partitioning columns\n :param compression: compression codec to use when saving to file. This can be one of the\n known case-insensitive shorten names (none, snappy, zlib, and lzo).\n This will override ``orc.compress`` and\n ``spark.sql.orc.compression.codec``. If None is set, it uses the value\n specified in ``spark.sql.orc.compression.codec``.\n\n >>> orc_df = spark.read.orc('python/test_support/sql/orc_partitioned')\n >>> orc_df.write.orc(os.path.join(tempfile.mkdtemp(), 'data'))", "output": "def orc(self, path, mode=None, partitionBy=None, compression=None):\n \"\"\"Saves the content of the :class:`DataFrame` in ORC format at the specified path.\n\n :param path: the path in any Hadoop supported file system\n :param mode: specifies the behavior of the save operation when data already exists.\n\n * ``append``: Append contents of this :class:`DataFrame` to existing data.\n * ``overwrite``: Overwrite existing data.\n * ``ignore``: Silently ignore this operation if data already exists.\n * ``error`` or ``errorifexists`` (default case): Throw an exception if data already \\\n exists.\n :param partitionBy: names of partitioning columns\n :param compression: compression codec to use when saving to file. This can be one of the\n known case-insensitive shorten names (none, snappy, zlib, and lzo).\n This will override ``orc.compress`` and\n ``spark.sql.orc.compression.codec``. If None is set, it uses the value\n specified in ``spark.sql.orc.compression.codec``.\n\n >>> orc_df = spark.read.orc('python/test_support/sql/orc_partitioned')\n >>> orc_df.write.orc(os.path.join(tempfile.mkdtemp(), 'data'))\n \"\"\"\n self.mode(mode)\n if partitionBy is not None:\n self.partitionBy(partitionBy)\n self._set_opts(compression=compression)\n self._jwrite.orc(path)" }, { "instruction": "Write or improve a Python function based on this description:\n\nSaves the content of the :class:`DataFrame` to an external database table via JDBC.\n\n .. note:: Don't create too many partitions in parallel on a large cluster;\n otherwise Spark might crash your external database systems.\n\n :param url: a JDBC URL of the form ``jdbc:subprotocol:subname``\n :param table: Name of the table in the external database.\n :param mode: specifies the behavior of the save operation when data already exists.\n\n * ``append``: Append contents of this :class:`DataFrame` to existing data.\n * ``overwrite``: Overwrite existing data.\n * ``ignore``: Silently ignore this operation if data already exists.\n * ``error`` or ``errorifexists`` (default case): Throw an exception if data already \\\n exists.\n :param properties: a dictionary of JDBC database connection arguments. Normally at\n least properties \"user\" and \"password\" with their corresponding values.\n For example { 'user' : 'SYSTEM', 'password' : 'mypassword' }", "output": "def jdbc(self, url, table, mode=None, properties=None):\n \"\"\"Saves the content of the :class:`DataFrame` to an external database table via JDBC.\n\n .. note:: Don't create too many partitions in parallel on a large cluster;\n otherwise Spark might crash your external database systems.\n\n :param url: a JDBC URL of the form ``jdbc:subprotocol:subname``\n :param table: Name of the table in the external database.\n :param mode: specifies the behavior of the save operation when data already exists.\n\n * ``append``: Append contents of this :class:`DataFrame` to existing data.\n * ``overwrite``: Overwrite existing data.\n * ``ignore``: Silently ignore this operation if data already exists.\n * ``error`` or ``errorifexists`` (default case): Throw an exception if data already \\\n exists.\n :param properties: a dictionary of JDBC database connection arguments. Normally at\n least properties \"user\" and \"password\" with their corresponding values.\n For example { 'user' : 'SYSTEM', 'password' : 'mypassword' }\n \"\"\"\n if properties is None:\n properties = dict()\n jprop = JavaClass(\"java.util.Properties\", self._spark._sc._gateway._gateway_client)()\n for k in properties:\n jprop.setProperty(k, properties[k])\n self.mode(mode)._jwrite.jdbc(url, table, jprop)" }, { "instruction": "Write or improve a Python function based on this description:\n\nCreate an input stream that pulls messages from a Kinesis stream. This uses the\n Kinesis Client Library (KCL) to pull messages from Kinesis.\n\n .. note:: The given AWS credentials will get saved in DStream checkpoints if checkpointing\n is enabled. Make sure that your checkpoint directory is secure.\n\n :param ssc: StreamingContext object\n :param kinesisAppName: Kinesis application name used by the Kinesis Client Library (KCL) to\n update DynamoDB\n :param streamName: Kinesis stream name\n :param endpointUrl: Url of Kinesis service (e.g., https://kinesis.us-east-1.amazonaws.com)\n :param regionName: Name of region used by the Kinesis Client Library (KCL) to update\n DynamoDB (lease coordination and checkpointing) and CloudWatch (metrics)\n :param initialPositionInStream: In the absence of Kinesis checkpoint info, this is the\n worker's initial starting position in the stream. The\n values are either the beginning of the stream per Kinesis'\n limit of 24 hours (InitialPositionInStream.TRIM_HORIZON) or\n the tip of the stream (InitialPositionInStream.LATEST).\n :param checkpointInterval: Checkpoint interval for Kinesis checkpointing. See the Kinesis\n Spark Streaming documentation for more details on the different\n types of checkpoints.\n :param storageLevel: Storage level to use for storing the received objects (default is\n StorageLevel.MEMORY_AND_DISK_2)\n :param awsAccessKeyId: AWS AccessKeyId (default is None. If None, will use\n DefaultAWSCredentialsProviderChain)\n :param awsSecretKey: AWS SecretKey (default is None. If None, will use\n DefaultAWSCredentialsProviderChain)\n :param decoder: A function used to decode value (default is utf8_decoder)\n :param stsAssumeRoleArn: ARN of IAM role to assume when using STS sessions to read from\n the Kinesis stream (default is None).\n :param stsSessionName: Name to uniquely identify STS sessions used to read from Kinesis\n stream, if STS is being used (default is None).\n :param stsExternalId: External ID that can be used to validate against the assumed IAM\n role's trust policy, if STS is being used (default is None).\n :return: A DStream object", "output": "def createStream(ssc, kinesisAppName, streamName, endpointUrl, regionName,\n initialPositionInStream, checkpointInterval,\n storageLevel=StorageLevel.MEMORY_AND_DISK_2,\n awsAccessKeyId=None, awsSecretKey=None, decoder=utf8_decoder,\n stsAssumeRoleArn=None, stsSessionName=None, stsExternalId=None):\n \"\"\"\n Create an input stream that pulls messages from a Kinesis stream. This uses the\n Kinesis Client Library (KCL) to pull messages from Kinesis.\n\n .. note:: The given AWS credentials will get saved in DStream checkpoints if checkpointing\n is enabled. Make sure that your checkpoint directory is secure.\n\n :param ssc: StreamingContext object\n :param kinesisAppName: Kinesis application name used by the Kinesis Client Library (KCL) to\n update DynamoDB\n :param streamName: Kinesis stream name\n :param endpointUrl: Url of Kinesis service (e.g., https://kinesis.us-east-1.amazonaws.com)\n :param regionName: Name of region used by the Kinesis Client Library (KCL) to update\n DynamoDB (lease coordination and checkpointing) and CloudWatch (metrics)\n :param initialPositionInStream: In the absence of Kinesis checkpoint info, this is the\n worker's initial starting position in the stream. The\n values are either the beginning of the stream per Kinesis'\n limit of 24 hours (InitialPositionInStream.TRIM_HORIZON) or\n the tip of the stream (InitialPositionInStream.LATEST).\n :param checkpointInterval: Checkpoint interval for Kinesis checkpointing. See the Kinesis\n Spark Streaming documentation for more details on the different\n types of checkpoints.\n :param storageLevel: Storage level to use for storing the received objects (default is\n StorageLevel.MEMORY_AND_DISK_2)\n :param awsAccessKeyId: AWS AccessKeyId (default is None. If None, will use\n DefaultAWSCredentialsProviderChain)\n :param awsSecretKey: AWS SecretKey (default is None. If None, will use\n DefaultAWSCredentialsProviderChain)\n :param decoder: A function used to decode value (default is utf8_decoder)\n :param stsAssumeRoleArn: ARN of IAM role to assume when using STS sessions to read from\n the Kinesis stream (default is None).\n :param stsSessionName: Name to uniquely identify STS sessions used to read from Kinesis\n stream, if STS is being used (default is None).\n :param stsExternalId: External ID that can be used to validate against the assumed IAM\n role's trust policy, if STS is being used (default is None).\n :return: A DStream object\n \"\"\"\n jlevel = ssc._sc._getJavaStorageLevel(storageLevel)\n jduration = ssc._jduration(checkpointInterval)\n\n try:\n # Use KinesisUtilsPythonHelper to access Scala's KinesisUtils\n helper = ssc._jvm.org.apache.spark.streaming.kinesis.KinesisUtilsPythonHelper()\n except TypeError as e:\n if str(e) == \"'JavaPackage' object is not callable\":\n _print_missing_jar(\n \"Streaming's Kinesis\",\n \"streaming-kinesis-asl\",\n \"streaming-kinesis-asl-assembly\",\n ssc.sparkContext.version)\n raise\n jstream = helper.createStream(ssc._jssc, kinesisAppName, streamName, endpointUrl,\n regionName, initialPositionInStream, jduration, jlevel,\n awsAccessKeyId, awsSecretKey, stsAssumeRoleArn,\n stsSessionName, stsExternalId)\n stream = DStream(jstream, ssc, NoOpSerializer())\n return stream.map(lambda v: decoder(v))" }, { "instruction": "Write or improve a Python function based on this description:\n\nPrompt the user to choose who to assign the issue to in jira, given a list of candidates,\n including the original reporter and all commentors", "output": "def choose_jira_assignee(issue, asf_jira):\n \"\"\"\n Prompt the user to choose who to assign the issue to in jira, given a list of candidates,\n including the original reporter and all commentors\n \"\"\"\n while True:\n try:\n reporter = issue.fields.reporter\n commentors = map(lambda x: x.author, issue.fields.comment.comments)\n candidates = set(commentors)\n candidates.add(reporter)\n candidates = list(candidates)\n print(\"JIRA is unassigned, choose assignee\")\n for idx, author in enumerate(candidates):\n if author.key == \"apachespark\":\n continue\n annotations = [\"Reporter\"] if author == reporter else []\n if author in commentors:\n annotations.append(\"Commentor\")\n print(\"[%d] %s (%s)\" % (idx, author.displayName, \",\".join(annotations)))\n raw_assignee = input(\n \"Enter number of user, or userid, to assign to (blank to leave unassigned):\")\n if raw_assignee == \"\":\n return None\n else:\n try:\n id = int(raw_assignee)\n assignee = candidates[id]\n except:\n # assume it's a user id, and try to assign (might fail, we just prompt again)\n assignee = asf_jira.user(raw_assignee)\n asf_jira.assign_issue(issue.key, assignee.key)\n return assignee\n except KeyboardInterrupt:\n raise\n except:\n traceback.print_exc()\n print(\"Error assigning JIRA, try again (or leave blank and fix manually)\")" }, { "instruction": "Write or improve a Python function based on this description:\n\nStandardize the [SPARK-XXXXX] [MODULE] prefix\n Converts \"[SPARK-XXX][mllib] Issue\", \"[MLLib] SPARK-XXX. Issue\" or \"SPARK XXX [MLLIB]: Issue\" to\n \"[SPARK-XXX][MLLIB] Issue\"\n\n >>> standardize_jira_ref(\n ... \"[SPARK-5821] [SQL] ParquetRelation2 CTAS should check if delete is successful\")\n '[SPARK-5821][SQL] ParquetRelation2 CTAS should check if delete is successful'\n >>> standardize_jira_ref(\n ... \"[SPARK-4123][Project Infra][WIP]: Show new dependencies added in pull requests\")\n '[SPARK-4123][PROJECT INFRA][WIP] Show new dependencies added in pull requests'\n >>> standardize_jira_ref(\"[MLlib] Spark 5954: Top by key\")\n '[SPARK-5954][MLLIB] Top by key'\n >>> standardize_jira_ref(\"[SPARK-979] a LRU scheduler for load balancing in TaskSchedulerImpl\")\n '[SPARK-979] a LRU scheduler for load balancing in TaskSchedulerImpl'\n >>> standardize_jira_ref(\n ... \"SPARK-1094 Support MiMa for reporting binary compatibility across versions.\")\n '[SPARK-1094] Support MiMa for reporting binary compatibility across versions.'\n >>> standardize_jira_ref(\"[WIP] [SPARK-1146] Vagrant support for Spark\")\n '[SPARK-1146][WIP] Vagrant support for Spark'\n >>> standardize_jira_ref(\n ... \"SPARK-1032. If Yarn app fails before registering, app master stays aroun...\")\n '[SPARK-1032] If Yarn app fails before registering, app master stays aroun...'\n >>> standardize_jira_ref(\n ... \"[SPARK-6250][SPARK-6146][SPARK-5911][SQL] Types are now reserved words in DDL parser.\")\n '[SPARK-6250][SPARK-6146][SPARK-5911][SQL] Types are now reserved words in DDL parser.'\n >>> standardize_jira_ref(\"Additional information for users building from source code\")\n 'Additional information for users building from source code'", "output": "def standardize_jira_ref(text):\n \"\"\"\n Standardize the [SPARK-XXXXX] [MODULE] prefix\n Converts \"[SPARK-XXX][mllib] Issue\", \"[MLLib] SPARK-XXX. Issue\" or \"SPARK XXX [MLLIB]: Issue\" to\n \"[SPARK-XXX][MLLIB] Issue\"\n\n >>> standardize_jira_ref(\n ... \"[SPARK-5821] [SQL] ParquetRelation2 CTAS should check if delete is successful\")\n '[SPARK-5821][SQL] ParquetRelation2 CTAS should check if delete is successful'\n >>> standardize_jira_ref(\n ... \"[SPARK-4123][Project Infra][WIP]: Show new dependencies added in pull requests\")\n '[SPARK-4123][PROJECT INFRA][WIP] Show new dependencies added in pull requests'\n >>> standardize_jira_ref(\"[MLlib] Spark 5954: Top by key\")\n '[SPARK-5954][MLLIB] Top by key'\n >>> standardize_jira_ref(\"[SPARK-979] a LRU scheduler for load balancing in TaskSchedulerImpl\")\n '[SPARK-979] a LRU scheduler for load balancing in TaskSchedulerImpl'\n >>> standardize_jira_ref(\n ... \"SPARK-1094 Support MiMa for reporting binary compatibility across versions.\")\n '[SPARK-1094] Support MiMa for reporting binary compatibility across versions.'\n >>> standardize_jira_ref(\"[WIP] [SPARK-1146] Vagrant support for Spark\")\n '[SPARK-1146][WIP] Vagrant support for Spark'\n >>> standardize_jira_ref(\n ... \"SPARK-1032. If Yarn app fails before registering, app master stays aroun...\")\n '[SPARK-1032] If Yarn app fails before registering, app master stays aroun...'\n >>> standardize_jira_ref(\n ... \"[SPARK-6250][SPARK-6146][SPARK-5911][SQL] Types are now reserved words in DDL parser.\")\n '[SPARK-6250][SPARK-6146][SPARK-5911][SQL] Types are now reserved words in DDL parser.'\n >>> standardize_jira_ref(\"Additional information for users building from source code\")\n 'Additional information for users building from source code'\n \"\"\"\n jira_refs = []\n components = []\n\n # If the string is compliant, no need to process any further\n if (re.search(r'^\\[SPARK-[0-9]{3,6}\\](\\[[A-Z0-9_\\s,]+\\] )+\\S+', text)):\n return text\n\n # Extract JIRA ref(s):\n pattern = re.compile(r'(SPARK[-\\s]*[0-9]{3,6})+', re.IGNORECASE)\n for ref in pattern.findall(text):\n # Add brackets, replace spaces with a dash, & convert to uppercase\n jira_refs.append('[' + re.sub(r'\\s+', '-', ref.upper()) + ']')\n text = text.replace(ref, '')\n\n # Extract spark component(s):\n # Look for alphanumeric chars, spaces, dashes, periods, and/or commas\n pattern = re.compile(r'(\\[[\\w\\s,.-]+\\])', re.IGNORECASE)\n for component in pattern.findall(text):\n components.append(component.upper())\n text = text.replace(component, '')\n\n # Cleanup any remaining symbols:\n pattern = re.compile(r'^\\W+(.*)', re.IGNORECASE)\n if (pattern.search(text) is not None):\n text = pattern.search(text).groups()[0]\n\n # Assemble full text (JIRA ref(s), module(s), remaining text)\n clean_text = ''.join(jira_refs).strip() + ''.join(components).strip() + \" \" + text.strip()\n\n # Replace multiple spaces with a single space, e.g. if no jira refs and/or components were\n # included\n clean_text = re.sub(r'\\s+', ' ', clean_text.strip())\n\n return clean_text" }, { "instruction": "Write or improve a Python function based on this description:\n\nParses a line in LIBSVM format into (label, indices, values).", "output": "def _parse_libsvm_line(line):\n \"\"\"\n Parses a line in LIBSVM format into (label, indices, values).\n \"\"\"\n items = line.split(None)\n label = float(items[0])\n nnz = len(items) - 1\n indices = np.zeros(nnz, dtype=np.int32)\n values = np.zeros(nnz)\n for i in xrange(nnz):\n index, value = items[1 + i].split(\":\")\n indices[i] = int(index) - 1\n values[i] = float(value)\n return label, indices, values" }, { "instruction": "Write or improve a Python function based on this description:\n\nConverts a LabeledPoint to a string in LIBSVM format.", "output": "def _convert_labeled_point_to_libsvm(p):\n \"\"\"Converts a LabeledPoint to a string in LIBSVM format.\"\"\"\n from pyspark.mllib.regression import LabeledPoint\n assert isinstance(p, LabeledPoint)\n items = [str(p.label)]\n v = _convert_to_vector(p.features)\n if isinstance(v, SparseVector):\n nnz = len(v.indices)\n for i in xrange(nnz):\n items.append(str(v.indices[i] + 1) + \":\" + str(v.values[i]))\n else:\n for i in xrange(len(v)):\n items.append(str(i + 1) + \":\" + str(v[i]))\n return \" \".join(items)" }, { "instruction": "Write or improve a Python function based on this description:\n\nLoads labeled data in the LIBSVM format into an RDD of\n LabeledPoint. The LIBSVM format is a text-based format used by\n LIBSVM and LIBLINEAR. Each line represents a labeled sparse\n feature vector using the following format:\n\n label index1:value1 index2:value2 ...\n\n where the indices are one-based and in ascending order. This\n method parses each line into a LabeledPoint, where the feature\n indices are converted to zero-based.\n\n :param sc: Spark context\n :param path: file or directory path in any Hadoop-supported file\n system URI\n :param numFeatures: number of features, which will be determined\n from the input data if a nonpositive value\n is given. This is useful when the dataset is\n already split into multiple files and you\n want to load them separately, because some\n features may not present in certain files,\n which leads to inconsistent feature\n dimensions.\n :param minPartitions: min number of partitions\n @return: labeled data stored as an RDD of LabeledPoint\n\n >>> from tempfile import NamedTemporaryFile\n >>> from pyspark.mllib.util import MLUtils\n >>> from pyspark.mllib.regression import LabeledPoint\n >>> tempFile = NamedTemporaryFile(delete=True)\n >>> _ = tempFile.write(b\"+1 1:1.0 3:2.0 5:3.0\\\\n-1\\\\n-1 2:4.0 4:5.0 6:6.0\")\n >>> tempFile.flush()\n >>> examples = MLUtils.loadLibSVMFile(sc, tempFile.name).collect()\n >>> tempFile.close()\n >>> examples[0]\n LabeledPoint(1.0, (6,[0,2,4],[1.0,2.0,3.0]))\n >>> examples[1]\n LabeledPoint(-1.0, (6,[],[]))\n >>> examples[2]\n LabeledPoint(-1.0, (6,[1,3,5],[4.0,5.0,6.0]))", "output": "def loadLibSVMFile(sc, path, numFeatures=-1, minPartitions=None):\n \"\"\"\n Loads labeled data in the LIBSVM format into an RDD of\n LabeledPoint. The LIBSVM format is a text-based format used by\n LIBSVM and LIBLINEAR. Each line represents a labeled sparse\n feature vector using the following format:\n\n label index1:value1 index2:value2 ...\n\n where the indices are one-based and in ascending order. This\n method parses each line into a LabeledPoint, where the feature\n indices are converted to zero-based.\n\n :param sc: Spark context\n :param path: file or directory path in any Hadoop-supported file\n system URI\n :param numFeatures: number of features, which will be determined\n from the input data if a nonpositive value\n is given. This is useful when the dataset is\n already split into multiple files and you\n want to load them separately, because some\n features may not present in certain files,\n which leads to inconsistent feature\n dimensions.\n :param minPartitions: min number of partitions\n @return: labeled data stored as an RDD of LabeledPoint\n\n >>> from tempfile import NamedTemporaryFile\n >>> from pyspark.mllib.util import MLUtils\n >>> from pyspark.mllib.regression import LabeledPoint\n >>> tempFile = NamedTemporaryFile(delete=True)\n >>> _ = tempFile.write(b\"+1 1:1.0 3:2.0 5:3.0\\\\n-1\\\\n-1 2:4.0 4:5.0 6:6.0\")\n >>> tempFile.flush()\n >>> examples = MLUtils.loadLibSVMFile(sc, tempFile.name).collect()\n >>> tempFile.close()\n >>> examples[0]\n LabeledPoint(1.0, (6,[0,2,4],[1.0,2.0,3.0]))\n >>> examples[1]\n LabeledPoint(-1.0, (6,[],[]))\n >>> examples[2]\n LabeledPoint(-1.0, (6,[1,3,5],[4.0,5.0,6.0]))\n \"\"\"\n from pyspark.mllib.regression import LabeledPoint\n\n lines = sc.textFile(path, minPartitions)\n parsed = lines.map(lambda l: MLUtils._parse_libsvm_line(l))\n if numFeatures <= 0:\n parsed.cache()\n numFeatures = parsed.map(lambda x: -1 if x[1].size == 0 else x[1][-1]).reduce(max) + 1\n return parsed.map(lambda x: LabeledPoint(x[0], Vectors.sparse(numFeatures, x[1], x[2])))" }, { "instruction": "Write or improve a Python function based on this description:\n\nSave labeled data in LIBSVM format.\n\n :param data: an RDD of LabeledPoint to be saved\n :param dir: directory to save the data\n\n >>> from tempfile import NamedTemporaryFile\n >>> from fileinput import input\n >>> from pyspark.mllib.regression import LabeledPoint\n >>> from glob import glob\n >>> from pyspark.mllib.util import MLUtils\n >>> examples = [LabeledPoint(1.1, Vectors.sparse(3, [(0, 1.23), (2, 4.56)])),\n ... LabeledPoint(0.0, Vectors.dense([1.01, 2.02, 3.03]))]\n >>> tempFile = NamedTemporaryFile(delete=True)\n >>> tempFile.close()\n >>> MLUtils.saveAsLibSVMFile(sc.parallelize(examples), tempFile.name)\n >>> ''.join(sorted(input(glob(tempFile.name + \"/part-0000*\"))))\n '0.0 1:1.01 2:2.02 3:3.03\\\\n1.1 1:1.23 3:4.56\\\\n'", "output": "def saveAsLibSVMFile(data, dir):\n \"\"\"\n Save labeled data in LIBSVM format.\n\n :param data: an RDD of LabeledPoint to be saved\n :param dir: directory to save the data\n\n >>> from tempfile import NamedTemporaryFile\n >>> from fileinput import input\n >>> from pyspark.mllib.regression import LabeledPoint\n >>> from glob import glob\n >>> from pyspark.mllib.util import MLUtils\n >>> examples = [LabeledPoint(1.1, Vectors.sparse(3, [(0, 1.23), (2, 4.56)])),\n ... LabeledPoint(0.0, Vectors.dense([1.01, 2.02, 3.03]))]\n >>> tempFile = NamedTemporaryFile(delete=True)\n >>> tempFile.close()\n >>> MLUtils.saveAsLibSVMFile(sc.parallelize(examples), tempFile.name)\n >>> ''.join(sorted(input(glob(tempFile.name + \"/part-0000*\"))))\n '0.0 1:1.01 2:2.02 3:3.03\\\\n1.1 1:1.23 3:4.56\\\\n'\n \"\"\"\n lines = data.map(lambda p: MLUtils._convert_labeled_point_to_libsvm(p))\n lines.saveAsTextFile(dir)" }, { "instruction": "Write or improve a Python function based on this description:\n\nLoad labeled points saved using RDD.saveAsTextFile.\n\n :param sc: Spark context\n :param path: file or directory path in any Hadoop-supported file\n system URI\n :param minPartitions: min number of partitions\n @return: labeled data stored as an RDD of LabeledPoint\n\n >>> from tempfile import NamedTemporaryFile\n >>> from pyspark.mllib.util import MLUtils\n >>> from pyspark.mllib.regression import LabeledPoint\n >>> examples = [LabeledPoint(1.1, Vectors.sparse(3, [(0, -1.23), (2, 4.56e-7)])),\n ... LabeledPoint(0.0, Vectors.dense([1.01, 2.02, 3.03]))]\n >>> tempFile = NamedTemporaryFile(delete=True)\n >>> tempFile.close()\n >>> sc.parallelize(examples, 1).saveAsTextFile(tempFile.name)\n >>> MLUtils.loadLabeledPoints(sc, tempFile.name).collect()\n [LabeledPoint(1.1, (3,[0,2],[-1.23,4.56e-07])), LabeledPoint(0.0, [1.01,2.02,3.03])]", "output": "def loadLabeledPoints(sc, path, minPartitions=None):\n \"\"\"\n Load labeled points saved using RDD.saveAsTextFile.\n\n :param sc: Spark context\n :param path: file or directory path in any Hadoop-supported file\n system URI\n :param minPartitions: min number of partitions\n @return: labeled data stored as an RDD of LabeledPoint\n\n >>> from tempfile import NamedTemporaryFile\n >>> from pyspark.mllib.util import MLUtils\n >>> from pyspark.mllib.regression import LabeledPoint\n >>> examples = [LabeledPoint(1.1, Vectors.sparse(3, [(0, -1.23), (2, 4.56e-7)])),\n ... LabeledPoint(0.0, Vectors.dense([1.01, 2.02, 3.03]))]\n >>> tempFile = NamedTemporaryFile(delete=True)\n >>> tempFile.close()\n >>> sc.parallelize(examples, 1).saveAsTextFile(tempFile.name)\n >>> MLUtils.loadLabeledPoints(sc, tempFile.name).collect()\n [LabeledPoint(1.1, (3,[0,2],[-1.23,4.56e-07])), LabeledPoint(0.0, [1.01,2.02,3.03])]\n \"\"\"\n minPartitions = minPartitions or min(sc.defaultParallelism, 2)\n return callMLlibFunc(\"loadLabeledPoints\", sc, path, minPartitions)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns a new vector with `1.0` (bias) appended to\n the end of the input vector.", "output": "def appendBias(data):\n \"\"\"\n Returns a new vector with `1.0` (bias) appended to\n the end of the input vector.\n \"\"\"\n vec = _convert_to_vector(data)\n if isinstance(vec, SparseVector):\n newIndices = np.append(vec.indices, len(vec))\n newValues = np.append(vec.values, 1.0)\n return SparseVector(len(vec) + 1, newIndices, newValues)\n else:\n return _convert_to_vector(np.append(vec.toArray(), 1.0))" }, { "instruction": "Write or improve a Python function based on this description:\n\nConverts vector columns in an input DataFrame from the\n :py:class:`pyspark.mllib.linalg.Vector` type to the new\n :py:class:`pyspark.ml.linalg.Vector` type under the `spark.ml`\n package.\n\n :param dataset:\n input dataset\n :param cols:\n a list of vector columns to be converted.\n New vector columns will be ignored. If unspecified, all old\n vector columns will be converted excepted nested ones.\n :return:\n the input dataset with old vector columns converted to the\n new vector type\n\n >>> import pyspark\n >>> from pyspark.mllib.linalg import Vectors\n >>> from pyspark.mllib.util import MLUtils\n >>> df = spark.createDataFrame(\n ... [(0, Vectors.sparse(2, [1], [1.0]), Vectors.dense(2.0, 3.0))],\n ... [\"id\", \"x\", \"y\"])\n >>> r1 = MLUtils.convertVectorColumnsToML(df).first()\n >>> isinstance(r1.x, pyspark.ml.linalg.SparseVector)\n True\n >>> isinstance(r1.y, pyspark.ml.linalg.DenseVector)\n True\n >>> r2 = MLUtils.convertVectorColumnsToML(df, \"x\").first()\n >>> isinstance(r2.x, pyspark.ml.linalg.SparseVector)\n True\n >>> isinstance(r2.y, pyspark.mllib.linalg.DenseVector)\n True", "output": "def convertVectorColumnsToML(dataset, *cols):\n \"\"\"\n Converts vector columns in an input DataFrame from the\n :py:class:`pyspark.mllib.linalg.Vector` type to the new\n :py:class:`pyspark.ml.linalg.Vector` type under the `spark.ml`\n package.\n\n :param dataset:\n input dataset\n :param cols:\n a list of vector columns to be converted.\n New vector columns will be ignored. If unspecified, all old\n vector columns will be converted excepted nested ones.\n :return:\n the input dataset with old vector columns converted to the\n new vector type\n\n >>> import pyspark\n >>> from pyspark.mllib.linalg import Vectors\n >>> from pyspark.mllib.util import MLUtils\n >>> df = spark.createDataFrame(\n ... [(0, Vectors.sparse(2, [1], [1.0]), Vectors.dense(2.0, 3.0))],\n ... [\"id\", \"x\", \"y\"])\n >>> r1 = MLUtils.convertVectorColumnsToML(df).first()\n >>> isinstance(r1.x, pyspark.ml.linalg.SparseVector)\n True\n >>> isinstance(r1.y, pyspark.ml.linalg.DenseVector)\n True\n >>> r2 = MLUtils.convertVectorColumnsToML(df, \"x\").first()\n >>> isinstance(r2.x, pyspark.ml.linalg.SparseVector)\n True\n >>> isinstance(r2.y, pyspark.mllib.linalg.DenseVector)\n True\n \"\"\"\n if not isinstance(dataset, DataFrame):\n raise TypeError(\"Input dataset must be a DataFrame but got {}.\".format(type(dataset)))\n return callMLlibFunc(\"convertVectorColumnsToML\", dataset, list(cols))" }, { "instruction": "Write or improve a Python function based on this description:\n\n:param: intercept bias factor, the term c in X'w + c\n :param: weights feature vector, the term w in X'w + c\n :param: xMean Point around which the data X is centered.\n :param: xVariance Variance of the given data\n :param: nPoints Number of points to be generated\n :param: seed Random Seed\n :param: eps Used to scale the noise. If eps is set high,\n the amount of gaussian noise added is more.\n\n Returns a list of LabeledPoints of length nPoints", "output": "def generateLinearInput(intercept, weights, xMean, xVariance,\n nPoints, seed, eps):\n \"\"\"\n :param: intercept bias factor, the term c in X'w + c\n :param: weights feature vector, the term w in X'w + c\n :param: xMean Point around which the data X is centered.\n :param: xVariance Variance of the given data\n :param: nPoints Number of points to be generated\n :param: seed Random Seed\n :param: eps Used to scale the noise. If eps is set high,\n the amount of gaussian noise added is more.\n\n Returns a list of LabeledPoints of length nPoints\n \"\"\"\n weights = [float(weight) for weight in weights]\n xMean = [float(mean) for mean in xMean]\n xVariance = [float(var) for var in xVariance]\n return list(callMLlibFunc(\n \"generateLinearInputWrapper\", float(intercept), weights, xMean,\n xVariance, int(nPoints), int(seed), float(eps)))" }, { "instruction": "Write or improve a Python function based on this description:\n\nGenerate an RDD of LabeledPoints.", "output": "def generateLinearRDD(sc, nexamples, nfeatures, eps,\n nParts=2, intercept=0.0):\n \"\"\"\n Generate an RDD of LabeledPoints.\n \"\"\"\n return callMLlibFunc(\n \"generateLinearRDDWrapper\", sc, int(nexamples), int(nfeatures),\n float(eps), int(nParts), float(intercept))" }, { "instruction": "Write or improve a Python function based on this description:\n\nTrain a linear regression model using Stochastic Gradient\n Descent (SGD). This solves the least squares regression\n formulation\n\n f(weights) = 1/(2n) ||A weights - y||^2\n\n which is the mean squared error. Here the data matrix has n rows,\n and the input RDD holds the set of rows of A, each with its\n corresponding right hand side label y.\n See also the documentation for the precise formulation.\n\n :param data:\n The training data, an RDD of LabeledPoint.\n :param iterations:\n The number of iterations.\n (default: 100)\n :param step:\n The step parameter used in SGD.\n (default: 1.0)\n :param miniBatchFraction:\n Fraction of data to be used for each SGD iteration.\n (default: 1.0)\n :param initialWeights:\n The initial weights.\n (default: None)\n :param regParam:\n The regularizer parameter.\n (default: 0.0)\n :param regType:\n The type of regularizer used for training our model.\n Supported values:\n\n - \"l1\" for using L1 regularization\n - \"l2\" for using L2 regularization\n - None for no regularization (default)\n :param intercept:\n Boolean parameter which indicates the use or not of the\n augmented representation for training data (i.e., whether bias\n features are activated or not).\n (default: False)\n :param validateData:\n Boolean parameter which indicates if the algorithm should\n validate data before training.\n (default: True)\n :param convergenceTol:\n A condition which decides iteration termination.\n (default: 0.001)", "output": "def train(cls, data, iterations=100, step=1.0, miniBatchFraction=1.0,\n initialWeights=None, regParam=0.0, regType=None, intercept=False,\n validateData=True, convergenceTol=0.001):\n \"\"\"\n Train a linear regression model using Stochastic Gradient\n Descent (SGD). This solves the least squares regression\n formulation\n\n f(weights) = 1/(2n) ||A weights - y||^2\n\n which is the mean squared error. Here the data matrix has n rows,\n and the input RDD holds the set of rows of A, each with its\n corresponding right hand side label y.\n See also the documentation for the precise formulation.\n\n :param data:\n The training data, an RDD of LabeledPoint.\n :param iterations:\n The number of iterations.\n (default: 100)\n :param step:\n The step parameter used in SGD.\n (default: 1.0)\n :param miniBatchFraction:\n Fraction of data to be used for each SGD iteration.\n (default: 1.0)\n :param initialWeights:\n The initial weights.\n (default: None)\n :param regParam:\n The regularizer parameter.\n (default: 0.0)\n :param regType:\n The type of regularizer used for training our model.\n Supported values:\n\n - \"l1\" for using L1 regularization\n - \"l2\" for using L2 regularization\n - None for no regularization (default)\n :param intercept:\n Boolean parameter which indicates the use or not of the\n augmented representation for training data (i.e., whether bias\n features are activated or not).\n (default: False)\n :param validateData:\n Boolean parameter which indicates if the algorithm should\n validate data before training.\n (default: True)\n :param convergenceTol:\n A condition which decides iteration termination.\n (default: 0.001)\n \"\"\"\n warnings.warn(\n \"Deprecated in 2.0.0. Use ml.regression.LinearRegression.\", DeprecationWarning)\n\n def train(rdd, i):\n return callMLlibFunc(\"trainLinearRegressionModelWithSGD\", rdd, int(iterations),\n float(step), float(miniBatchFraction), i, float(regParam),\n regType, bool(intercept), bool(validateData),\n float(convergenceTol))\n\n return _regression_train_wrapper(train, LinearRegressionModel, data, initialWeights)" }, { "instruction": "Write or improve a Python function based on this description:\n\nPredict labels for provided features.\n Using a piecewise linear function.\n 1) If x exactly matches a boundary then associated prediction\n is returned. In case there are multiple predictions with the\n same boundary then one of them is returned. Which one is\n undefined (same as java.util.Arrays.binarySearch).\n 2) If x is lower or higher than all boundaries then first or\n last prediction is returned respectively. In case there are\n multiple predictions with the same boundary then the lowest\n or highest is returned respectively.\n 3) If x falls between two values in boundary array then\n prediction is treated as piecewise linear function and\n interpolated value is returned. In case there are multiple\n values with the same boundary then the same rules as in 2)\n are used.\n\n :param x:\n Feature or RDD of Features to be labeled.", "output": "def predict(self, x):\n \"\"\"\n Predict labels for provided features.\n Using a piecewise linear function.\n 1) If x exactly matches a boundary then associated prediction\n is returned. In case there are multiple predictions with the\n same boundary then one of them is returned. Which one is\n undefined (same as java.util.Arrays.binarySearch).\n 2) If x is lower or higher than all boundaries then first or\n last prediction is returned respectively. In case there are\n multiple predictions with the same boundary then the lowest\n or highest is returned respectively.\n 3) If x falls between two values in boundary array then\n prediction is treated as piecewise linear function and\n interpolated value is returned. In case there are multiple\n values with the same boundary then the same rules as in 2)\n are used.\n\n :param x:\n Feature or RDD of Features to be labeled.\n \"\"\"\n if isinstance(x, RDD):\n return x.map(lambda v: self.predict(v))\n return np.interp(x, self.boundaries, self.predictions)" }, { "instruction": "Write or improve a Python function based on this description:\n\nSave an IsotonicRegressionModel.", "output": "def save(self, sc, path):\n \"\"\"Save an IsotonicRegressionModel.\"\"\"\n java_boundaries = _py2java(sc, self.boundaries.tolist())\n java_predictions = _py2java(sc, self.predictions.tolist())\n java_model = sc._jvm.org.apache.spark.mllib.regression.IsotonicRegressionModel(\n java_boundaries, java_predictions, self.isotonic)\n java_model.save(sc._jsc.sc(), path)" }, { "instruction": "Write or improve a Python function based on this description:\n\nLoad an IsotonicRegressionModel.", "output": "def load(cls, sc, path):\n \"\"\"Load an IsotonicRegressionModel.\"\"\"\n java_model = sc._jvm.org.apache.spark.mllib.regression.IsotonicRegressionModel.load(\n sc._jsc.sc(), path)\n py_boundaries = _java2py(sc, java_model.boundaryVector()).toArray()\n py_predictions = _java2py(sc, java_model.predictionVector()).toArray()\n return IsotonicRegressionModel(py_boundaries, py_predictions, java_model.isotonic)" }, { "instruction": "Write or improve a Python function based on this description:\n\nTrain an isotonic regression model on the given data.\n\n :param data:\n RDD of (label, feature, weight) tuples.\n :param isotonic:\n Whether this is isotonic (which is default) or antitonic.\n (default: True)", "output": "def train(cls, data, isotonic=True):\n \"\"\"\n Train an isotonic regression model on the given data.\n\n :param data:\n RDD of (label, feature, weight) tuples.\n :param isotonic:\n Whether this is isotonic (which is default) or antitonic.\n (default: True)\n \"\"\"\n boundaries, predictions = callMLlibFunc(\"trainIsotonicRegressionModel\",\n data.map(_convert_to_vector), bool(isotonic))\n return IsotonicRegressionModel(boundaries.toArray(), predictions.toArray(), isotonic)" }, { "instruction": "Write or improve a Python function based on this description:\n\nCompute similarities between columns of this matrix.\n\n The threshold parameter is a trade-off knob between estimate\n quality and computational cost.\n\n The default threshold setting of 0 guarantees deterministically\n correct results, but uses the brute-force approach of computing\n normalized dot products.\n\n Setting the threshold to positive values uses a sampling\n approach and incurs strictly less computational cost than the\n brute-force approach. However the similarities computed will\n be estimates.\n\n The sampling guarantees relative-error correctness for those\n pairs of columns that have similarity greater than the given\n similarity threshold.\n\n To describe the guarantee, we set some notation:\n * Let A be the smallest in magnitude non-zero element of\n this matrix.\n * Let B be the largest in magnitude non-zero element of\n this matrix.\n * Let L be the maximum number of non-zeros per row.\n\n For example, for {0,1} matrices: A=B=1.\n Another example, for the Netflix matrix: A=1, B=5\n\n For those column pairs that are above the threshold, the\n computed similarity is correct to within 20% relative error\n with probability at least 1 - (0.981)^10/B^\n\n The shuffle size is bounded by the *smaller* of the following\n two expressions:\n\n * O(n log(n) L / (threshold * A))\n * O(m L^2^)\n\n The latter is the cost of the brute-force approach, so for\n non-zero thresholds, the cost is always cheaper than the\n brute-force approach.\n\n :param: threshold: Set to 0 for deterministic guaranteed\n correctness. Similarities above this\n threshold are estimated with the cost vs\n estimate quality trade-off described above.\n :return: An n x n sparse upper-triangular CoordinateMatrix of\n cosine similarities between columns of this matrix.\n\n >>> rows = sc.parallelize([[1, 2], [1, 5]])\n >>> mat = RowMatrix(rows)\n\n >>> sims = mat.columnSimilarities()\n >>> sims.entries.first().value\n 0.91914503...", "output": "def columnSimilarities(self, threshold=0.0):\n \"\"\"\n Compute similarities between columns of this matrix.\n\n The threshold parameter is a trade-off knob between estimate\n quality and computational cost.\n\n The default threshold setting of 0 guarantees deterministically\n correct results, but uses the brute-force approach of computing\n normalized dot products.\n\n Setting the threshold to positive values uses a sampling\n approach and incurs strictly less computational cost than the\n brute-force approach. However the similarities computed will\n be estimates.\n\n The sampling guarantees relative-error correctness for those\n pairs of columns that have similarity greater than the given\n similarity threshold.\n\n To describe the guarantee, we set some notation:\n * Let A be the smallest in magnitude non-zero element of\n this matrix.\n * Let B be the largest in magnitude non-zero element of\n this matrix.\n * Let L be the maximum number of non-zeros per row.\n\n For example, for {0,1} matrices: A=B=1.\n Another example, for the Netflix matrix: A=1, B=5\n\n For those column pairs that are above the threshold, the\n computed similarity is correct to within 20% relative error\n with probability at least 1 - (0.981)^10/B^\n\n The shuffle size is bounded by the *smaller* of the following\n two expressions:\n\n * O(n log(n) L / (threshold * A))\n * O(m L^2^)\n\n The latter is the cost of the brute-force approach, so for\n non-zero thresholds, the cost is always cheaper than the\n brute-force approach.\n\n :param: threshold: Set to 0 for deterministic guaranteed\n correctness. Similarities above this\n threshold are estimated with the cost vs\n estimate quality trade-off described above.\n :return: An n x n sparse upper-triangular CoordinateMatrix of\n cosine similarities between columns of this matrix.\n\n >>> rows = sc.parallelize([[1, 2], [1, 5]])\n >>> mat = RowMatrix(rows)\n\n >>> sims = mat.columnSimilarities()\n >>> sims.entries.first().value\n 0.91914503...\n \"\"\"\n java_sims_mat = self._java_matrix_wrapper.call(\"columnSimilarities\", float(threshold))\n return CoordinateMatrix(java_sims_mat)" }, { "instruction": "Write or improve a Python function based on this description:\n\nCompute the QR decomposition of this RowMatrix.\n\n The implementation is designed to optimize the QR decomposition\n (factorization) for the RowMatrix of a tall and skinny shape.\n\n Reference:\n Paul G. Constantine, David F. Gleich. \"Tall and skinny QR\n factorizations in MapReduce architectures\"\n ([[https://doi.org/10.1145/1996092.1996103]])\n\n :param: computeQ: whether to computeQ\n :return: QRDecomposition(Q: RowMatrix, R: Matrix), where\n Q = None if computeQ = false.\n\n >>> rows = sc.parallelize([[3, -6], [4, -8], [0, 1]])\n >>> mat = RowMatrix(rows)\n >>> decomp = mat.tallSkinnyQR(True)\n >>> Q = decomp.Q\n >>> R = decomp.R\n\n >>> # Test with absolute values\n >>> absQRows = Q.rows.map(lambda row: abs(row.toArray()).tolist())\n >>> absQRows.collect()\n [[0.6..., 0.0], [0.8..., 0.0], [0.0, 1.0]]\n\n >>> # Test with absolute values\n >>> abs(R.toArray()).tolist()\n [[5.0, 10.0], [0.0, 1.0]]", "output": "def tallSkinnyQR(self, computeQ=False):\n \"\"\"\n Compute the QR decomposition of this RowMatrix.\n\n The implementation is designed to optimize the QR decomposition\n (factorization) for the RowMatrix of a tall and skinny shape.\n\n Reference:\n Paul G. Constantine, David F. Gleich. \"Tall and skinny QR\n factorizations in MapReduce architectures\"\n ([[https://doi.org/10.1145/1996092.1996103]])\n\n :param: computeQ: whether to computeQ\n :return: QRDecomposition(Q: RowMatrix, R: Matrix), where\n Q = None if computeQ = false.\n\n >>> rows = sc.parallelize([[3, -6], [4, -8], [0, 1]])\n >>> mat = RowMatrix(rows)\n >>> decomp = mat.tallSkinnyQR(True)\n >>> Q = decomp.Q\n >>> R = decomp.R\n\n >>> # Test with absolute values\n >>> absQRows = Q.rows.map(lambda row: abs(row.toArray()).tolist())\n >>> absQRows.collect()\n [[0.6..., 0.0], [0.8..., 0.0], [0.0, 1.0]]\n\n >>> # Test with absolute values\n >>> abs(R.toArray()).tolist()\n [[5.0, 10.0], [0.0, 1.0]]\n \"\"\"\n decomp = JavaModelWrapper(self._java_matrix_wrapper.call(\"tallSkinnyQR\", computeQ))\n if computeQ:\n java_Q = decomp.call(\"Q\")\n Q = RowMatrix(java_Q)\n else:\n Q = None\n R = decomp.call(\"R\")\n return QRDecomposition(Q, R)" }, { "instruction": "Write or improve a Python function based on this description:\n\nComputes the singular value decomposition of the RowMatrix.\n\n The given row matrix A of dimension (m X n) is decomposed into\n U * s * V'T where\n\n * U: (m X k) (left singular vectors) is a RowMatrix whose\n columns are the eigenvectors of (A X A')\n * s: DenseVector consisting of square root of the eigenvalues\n (singular values) in descending order.\n * v: (n X k) (right singular vectors) is a Matrix whose columns\n are the eigenvectors of (A' X A)\n\n For more specific details on implementation, please refer\n the Scala documentation.\n\n :param k: Number of leading singular values to keep (`0 < k <= n`).\n It might return less than k if there are numerically zero singular values\n or there are not enough Ritz values converged before the maximum number of\n Arnoldi update iterations is reached (in case that matrix A is ill-conditioned).\n :param computeU: Whether or not to compute U. If set to be\n True, then U is computed by A * V * s^-1\n :param rCond: Reciprocal condition number. All singular values\n smaller than rCond * s[0] are treated as zero\n where s[0] is the largest singular value.\n :returns: :py:class:`SingularValueDecomposition`\n\n >>> rows = sc.parallelize([[3, 1, 1], [-1, 3, 1]])\n >>> rm = RowMatrix(rows)\n\n >>> svd_model = rm.computeSVD(2, True)\n >>> svd_model.U.rows.collect()\n [DenseVector([-0.7071, 0.7071]), DenseVector([-0.7071, -0.7071])]\n >>> svd_model.s\n DenseVector([3.4641, 3.1623])\n >>> svd_model.V\n DenseMatrix(3, 2, [-0.4082, -0.8165, -0.4082, 0.8944, -0.4472, 0.0], 0)", "output": "def computeSVD(self, k, computeU=False, rCond=1e-9):\n \"\"\"\n Computes the singular value decomposition of the RowMatrix.\n\n The given row matrix A of dimension (m X n) is decomposed into\n U * s * V'T where\n\n * U: (m X k) (left singular vectors) is a RowMatrix whose\n columns are the eigenvectors of (A X A')\n * s: DenseVector consisting of square root of the eigenvalues\n (singular values) in descending order.\n * v: (n X k) (right singular vectors) is a Matrix whose columns\n are the eigenvectors of (A' X A)\n\n For more specific details on implementation, please refer\n the Scala documentation.\n\n :param k: Number of leading singular values to keep (`0 < k <= n`).\n It might return less than k if there are numerically zero singular values\n or there are not enough Ritz values converged before the maximum number of\n Arnoldi update iterations is reached (in case that matrix A is ill-conditioned).\n :param computeU: Whether or not to compute U. If set to be\n True, then U is computed by A * V * s^-1\n :param rCond: Reciprocal condition number. All singular values\n smaller than rCond * s[0] are treated as zero\n where s[0] is the largest singular value.\n :returns: :py:class:`SingularValueDecomposition`\n\n >>> rows = sc.parallelize([[3, 1, 1], [-1, 3, 1]])\n >>> rm = RowMatrix(rows)\n\n >>> svd_model = rm.computeSVD(2, True)\n >>> svd_model.U.rows.collect()\n [DenseVector([-0.7071, 0.7071]), DenseVector([-0.7071, -0.7071])]\n >>> svd_model.s\n DenseVector([3.4641, 3.1623])\n >>> svd_model.V\n DenseMatrix(3, 2, [-0.4082, -0.8165, -0.4082, 0.8944, -0.4472, 0.0], 0)\n \"\"\"\n j_model = self._java_matrix_wrapper.call(\n \"computeSVD\", int(k), bool(computeU), float(rCond))\n return SingularValueDecomposition(j_model)" }, { "instruction": "Write or improve a Python function based on this description:\n\nMultiply this matrix by a local dense matrix on the right.\n\n :param matrix: a local dense matrix whose number of rows must match the number of columns\n of this matrix\n :returns: :py:class:`RowMatrix`\n\n >>> rm = RowMatrix(sc.parallelize([[0, 1], [2, 3]]))\n >>> rm.multiply(DenseMatrix(2, 2, [0, 2, 1, 3])).rows.collect()\n [DenseVector([2.0, 3.0]), DenseVector([6.0, 11.0])]", "output": "def multiply(self, matrix):\n \"\"\"\n Multiply this matrix by a local dense matrix on the right.\n\n :param matrix: a local dense matrix whose number of rows must match the number of columns\n of this matrix\n :returns: :py:class:`RowMatrix`\n\n >>> rm = RowMatrix(sc.parallelize([[0, 1], [2, 3]]))\n >>> rm.multiply(DenseMatrix(2, 2, [0, 2, 1, 3])).rows.collect()\n [DenseVector([2.0, 3.0]), DenseVector([6.0, 11.0])]\n \"\"\"\n if not isinstance(matrix, DenseMatrix):\n raise ValueError(\"Only multiplication with DenseMatrix \"\n \"is supported.\")\n j_model = self._java_matrix_wrapper.call(\"multiply\", matrix)\n return RowMatrix(j_model)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns a distributed matrix whose columns are the left\n singular vectors of the SingularValueDecomposition if computeU was set to be True.", "output": "def U(self):\n \"\"\"\n Returns a distributed matrix whose columns are the left\n singular vectors of the SingularValueDecomposition if computeU was set to be True.\n \"\"\"\n u = self.call(\"U\")\n if u is not None:\n mat_name = u.getClass().getSimpleName()\n if mat_name == \"RowMatrix\":\n return RowMatrix(u)\n elif mat_name == \"IndexedRowMatrix\":\n return IndexedRowMatrix(u)\n else:\n raise TypeError(\"Expected RowMatrix/IndexedRowMatrix got %s\" % mat_name)" }, { "instruction": "Write or improve a Python function based on this description:\n\nRows of the IndexedRowMatrix stored as an RDD of IndexedRows.\n\n >>> mat = IndexedRowMatrix(sc.parallelize([IndexedRow(0, [1, 2, 3]),\n ... IndexedRow(1, [4, 5, 6])]))\n >>> rows = mat.rows\n >>> rows.first()\n IndexedRow(0, [1.0,2.0,3.0])", "output": "def rows(self):\n \"\"\"\n Rows of the IndexedRowMatrix stored as an RDD of IndexedRows.\n\n >>> mat = IndexedRowMatrix(sc.parallelize([IndexedRow(0, [1, 2, 3]),\n ... IndexedRow(1, [4, 5, 6])]))\n >>> rows = mat.rows\n >>> rows.first()\n IndexedRow(0, [1.0,2.0,3.0])\n \"\"\"\n # We use DataFrames for serialization of IndexedRows from\n # Java, so we first convert the RDD of rows to a DataFrame\n # on the Scala/Java side. Then we map each Row in the\n # DataFrame back to an IndexedRow on this side.\n rows_df = callMLlibFunc(\"getIndexedRows\", self._java_matrix_wrapper._java_model)\n rows = rows_df.rdd.map(lambda row: IndexedRow(row[0], row[1]))\n return rows" }, { "instruction": "Write or improve a Python function based on this description:\n\nConvert this matrix to a BlockMatrix.\n\n :param rowsPerBlock: Number of rows that make up each block.\n The blocks forming the final rows are not\n required to have the given number of rows.\n :param colsPerBlock: Number of columns that make up each block.\n The blocks forming the final columns are not\n required to have the given number of columns.\n\n >>> rows = sc.parallelize([IndexedRow(0, [1, 2, 3]),\n ... IndexedRow(6, [4, 5, 6])])\n >>> mat = IndexedRowMatrix(rows).toBlockMatrix()\n\n >>> # This IndexedRowMatrix will have 7 effective rows, due to\n >>> # the highest row index being 6, and the ensuing\n >>> # BlockMatrix will have 7 rows as well.\n >>> print(mat.numRows())\n 7\n\n >>> print(mat.numCols())\n 3", "output": "def toBlockMatrix(self, rowsPerBlock=1024, colsPerBlock=1024):\n \"\"\"\n Convert this matrix to a BlockMatrix.\n\n :param rowsPerBlock: Number of rows that make up each block.\n The blocks forming the final rows are not\n required to have the given number of rows.\n :param colsPerBlock: Number of columns that make up each block.\n The blocks forming the final columns are not\n required to have the given number of columns.\n\n >>> rows = sc.parallelize([IndexedRow(0, [1, 2, 3]),\n ... IndexedRow(6, [4, 5, 6])])\n >>> mat = IndexedRowMatrix(rows).toBlockMatrix()\n\n >>> # This IndexedRowMatrix will have 7 effective rows, due to\n >>> # the highest row index being 6, and the ensuing\n >>> # BlockMatrix will have 7 rows as well.\n >>> print(mat.numRows())\n 7\n\n >>> print(mat.numCols())\n 3\n \"\"\"\n java_block_matrix = self._java_matrix_wrapper.call(\"toBlockMatrix\",\n rowsPerBlock,\n colsPerBlock)\n return BlockMatrix(java_block_matrix, rowsPerBlock, colsPerBlock)" }, { "instruction": "Write or improve a Python function based on this description:\n\nMultiply this matrix by a local dense matrix on the right.\n\n :param matrix: a local dense matrix whose number of rows must match the number of columns\n of this matrix\n :returns: :py:class:`IndexedRowMatrix`\n\n >>> mat = IndexedRowMatrix(sc.parallelize([(0, (0, 1)), (1, (2, 3))]))\n >>> mat.multiply(DenseMatrix(2, 2, [0, 2, 1, 3])).rows.collect()\n [IndexedRow(0, [2.0,3.0]), IndexedRow(1, [6.0,11.0])]", "output": "def multiply(self, matrix):\n \"\"\"\n Multiply this matrix by a local dense matrix on the right.\n\n :param matrix: a local dense matrix whose number of rows must match the number of columns\n of this matrix\n :returns: :py:class:`IndexedRowMatrix`\n\n >>> mat = IndexedRowMatrix(sc.parallelize([(0, (0, 1)), (1, (2, 3))]))\n >>> mat.multiply(DenseMatrix(2, 2, [0, 2, 1, 3])).rows.collect()\n [IndexedRow(0, [2.0,3.0]), IndexedRow(1, [6.0,11.0])]\n \"\"\"\n if not isinstance(matrix, DenseMatrix):\n raise ValueError(\"Only multiplication with DenseMatrix \"\n \"is supported.\")\n return IndexedRowMatrix(self._java_matrix_wrapper.call(\"multiply\", matrix))" }, { "instruction": "Write or improve a Python function based on this description:\n\nEntries of the CoordinateMatrix stored as an RDD of\n MatrixEntries.\n\n >>> mat = CoordinateMatrix(sc.parallelize([MatrixEntry(0, 0, 1.2),\n ... MatrixEntry(6, 4, 2.1)]))\n >>> entries = mat.entries\n >>> entries.first()\n MatrixEntry(0, 0, 1.2)", "output": "def entries(self):\n \"\"\"\n Entries of the CoordinateMatrix stored as an RDD of\n MatrixEntries.\n\n >>> mat = CoordinateMatrix(sc.parallelize([MatrixEntry(0, 0, 1.2),\n ... MatrixEntry(6, 4, 2.1)]))\n >>> entries = mat.entries\n >>> entries.first()\n MatrixEntry(0, 0, 1.2)\n \"\"\"\n # We use DataFrames for serialization of MatrixEntry entries\n # from Java, so we first convert the RDD of entries to a\n # DataFrame on the Scala/Java side. Then we map each Row in\n # the DataFrame back to a MatrixEntry on this side.\n entries_df = callMLlibFunc(\"getMatrixEntries\", self._java_matrix_wrapper._java_model)\n entries = entries_df.rdd.map(lambda row: MatrixEntry(row[0], row[1], row[2]))\n return entries" }, { "instruction": "Write or improve a Python function based on this description:\n\nThe RDD of sub-matrix blocks\n ((blockRowIndex, blockColIndex), sub-matrix) that form this\n distributed matrix.\n\n >>> mat = BlockMatrix(\n ... sc.parallelize([((0, 0), Matrices.dense(3, 2, [1, 2, 3, 4, 5, 6])),\n ... ((1, 0), Matrices.dense(3, 2, [7, 8, 9, 10, 11, 12]))]), 3, 2)\n >>> blocks = mat.blocks\n >>> blocks.first()\n ((0, 0), DenseMatrix(3, 2, [1.0, 2.0, 3.0, 4.0, 5.0, 6.0], 0))", "output": "def blocks(self):\n \"\"\"\n The RDD of sub-matrix blocks\n ((blockRowIndex, blockColIndex), sub-matrix) that form this\n distributed matrix.\n\n >>> mat = BlockMatrix(\n ... sc.parallelize([((0, 0), Matrices.dense(3, 2, [1, 2, 3, 4, 5, 6])),\n ... ((1, 0), Matrices.dense(3, 2, [7, 8, 9, 10, 11, 12]))]), 3, 2)\n >>> blocks = mat.blocks\n >>> blocks.first()\n ((0, 0), DenseMatrix(3, 2, [1.0, 2.0, 3.0, 4.0, 5.0, 6.0], 0))\n\n \"\"\"\n # We use DataFrames for serialization of sub-matrix blocks\n # from Java, so we first convert the RDD of blocks to a\n # DataFrame on the Scala/Java side. Then we map each Row in\n # the DataFrame back to a sub-matrix block on this side.\n blocks_df = callMLlibFunc(\"getMatrixBlocks\", self._java_matrix_wrapper._java_model)\n blocks = blocks_df.rdd.map(lambda row: ((row[0][0], row[0][1]), row[1]))\n return blocks" }, { "instruction": "Write or improve a Python function based on this description:\n\nPersists the underlying RDD with the specified storage level.", "output": "def persist(self, storageLevel):\n \"\"\"\n Persists the underlying RDD with the specified storage level.\n \"\"\"\n if not isinstance(storageLevel, StorageLevel):\n raise TypeError(\"`storageLevel` should be a StorageLevel, got %s\" % type(storageLevel))\n javaStorageLevel = self._java_matrix_wrapper._sc._getJavaStorageLevel(storageLevel)\n self._java_matrix_wrapper.call(\"persist\", javaStorageLevel)\n return self" }, { "instruction": "Write or improve a Python function based on this description:\n\nAdds two block matrices together. The matrices must have the\n same size and matching `rowsPerBlock` and `colsPerBlock` values.\n If one of the sub matrix blocks that are being added is a\n SparseMatrix, the resulting sub matrix block will also be a\n SparseMatrix, even if it is being added to a DenseMatrix. If\n two dense sub matrix blocks are added, the output block will\n also be a DenseMatrix.\n\n >>> dm1 = Matrices.dense(3, 2, [1, 2, 3, 4, 5, 6])\n >>> dm2 = Matrices.dense(3, 2, [7, 8, 9, 10, 11, 12])\n >>> sm = Matrices.sparse(3, 2, [0, 1, 3], [0, 1, 2], [7, 11, 12])\n >>> blocks1 = sc.parallelize([((0, 0), dm1), ((1, 0), dm2)])\n >>> blocks2 = sc.parallelize([((0, 0), dm1), ((1, 0), dm2)])\n >>> blocks3 = sc.parallelize([((0, 0), sm), ((1, 0), dm2)])\n >>> mat1 = BlockMatrix(blocks1, 3, 2)\n >>> mat2 = BlockMatrix(blocks2, 3, 2)\n >>> mat3 = BlockMatrix(blocks3, 3, 2)\n\n >>> mat1.add(mat2).toLocalMatrix()\n DenseMatrix(6, 2, [2.0, 4.0, 6.0, 14.0, 16.0, 18.0, 8.0, 10.0, 12.0, 20.0, 22.0, 24.0], 0)\n\n >>> mat1.add(mat3).toLocalMatrix()\n DenseMatrix(6, 2, [8.0, 2.0, 3.0, 14.0, 16.0, 18.0, 4.0, 16.0, 18.0, 20.0, 22.0, 24.0], 0)", "output": "def add(self, other):\n \"\"\"\n Adds two block matrices together. The matrices must have the\n same size and matching `rowsPerBlock` and `colsPerBlock` values.\n If one of the sub matrix blocks that are being added is a\n SparseMatrix, the resulting sub matrix block will also be a\n SparseMatrix, even if it is being added to a DenseMatrix. If\n two dense sub matrix blocks are added, the output block will\n also be a DenseMatrix.\n\n >>> dm1 = Matrices.dense(3, 2, [1, 2, 3, 4, 5, 6])\n >>> dm2 = Matrices.dense(3, 2, [7, 8, 9, 10, 11, 12])\n >>> sm = Matrices.sparse(3, 2, [0, 1, 3], [0, 1, 2], [7, 11, 12])\n >>> blocks1 = sc.parallelize([((0, 0), dm1), ((1, 0), dm2)])\n >>> blocks2 = sc.parallelize([((0, 0), dm1), ((1, 0), dm2)])\n >>> blocks3 = sc.parallelize([((0, 0), sm), ((1, 0), dm2)])\n >>> mat1 = BlockMatrix(blocks1, 3, 2)\n >>> mat2 = BlockMatrix(blocks2, 3, 2)\n >>> mat3 = BlockMatrix(blocks3, 3, 2)\n\n >>> mat1.add(mat2).toLocalMatrix()\n DenseMatrix(6, 2, [2.0, 4.0, 6.0, 14.0, 16.0, 18.0, 8.0, 10.0, 12.0, 20.0, 22.0, 24.0], 0)\n\n >>> mat1.add(mat3).toLocalMatrix()\n DenseMatrix(6, 2, [8.0, 2.0, 3.0, 14.0, 16.0, 18.0, 4.0, 16.0, 18.0, 20.0, 22.0, 24.0], 0)\n \"\"\"\n if not isinstance(other, BlockMatrix):\n raise TypeError(\"Other should be a BlockMatrix, got %s\" % type(other))\n\n other_java_block_matrix = other._java_matrix_wrapper._java_model\n java_block_matrix = self._java_matrix_wrapper.call(\"add\", other_java_block_matrix)\n return BlockMatrix(java_block_matrix, self.rowsPerBlock, self.colsPerBlock)" }, { "instruction": "Write or improve a Python function based on this description:\n\nTranspose this BlockMatrix. Returns a new BlockMatrix\n instance sharing the same underlying data. Is a lazy operation.\n\n >>> blocks = sc.parallelize([((0, 0), Matrices.dense(3, 2, [1, 2, 3, 4, 5, 6])),\n ... ((1, 0), Matrices.dense(3, 2, [7, 8, 9, 10, 11, 12]))])\n >>> mat = BlockMatrix(blocks, 3, 2)\n\n >>> mat_transposed = mat.transpose()\n >>> mat_transposed.toLocalMatrix()\n DenseMatrix(2, 6, [1.0, 4.0, 2.0, 5.0, 3.0, 6.0, 7.0, 10.0, 8.0, 11.0, 9.0, 12.0], 0)", "output": "def transpose(self):\n \"\"\"\n Transpose this BlockMatrix. Returns a new BlockMatrix\n instance sharing the same underlying data. Is a lazy operation.\n\n >>> blocks = sc.parallelize([((0, 0), Matrices.dense(3, 2, [1, 2, 3, 4, 5, 6])),\n ... ((1, 0), Matrices.dense(3, 2, [7, 8, 9, 10, 11, 12]))])\n >>> mat = BlockMatrix(blocks, 3, 2)\n\n >>> mat_transposed = mat.transpose()\n >>> mat_transposed.toLocalMatrix()\n DenseMatrix(2, 6, [1.0, 4.0, 2.0, 5.0, 3.0, 6.0, 7.0, 10.0, 8.0, 11.0, 9.0, 12.0], 0)\n \"\"\"\n java_transposed_matrix = self._java_matrix_wrapper.call(\"transpose\")\n return BlockMatrix(java_transposed_matrix, self.colsPerBlock, self.rowsPerBlock)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns the size of the vector.\n\n >>> _vector_size([1., 2., 3.])\n 3\n >>> _vector_size((1., 2., 3.))\n 3\n >>> _vector_size(array.array('d', [1., 2., 3.]))\n 3\n >>> _vector_size(np.zeros(3))\n 3\n >>> _vector_size(np.zeros((3, 1)))\n 3\n >>> _vector_size(np.zeros((1, 3)))\n Traceback (most recent call last):\n ...\n ValueError: Cannot treat an ndarray of shape (1, 3) as a vector", "output": "def _vector_size(v):\n \"\"\"\n Returns the size of the vector.\n\n >>> _vector_size([1., 2., 3.])\n 3\n >>> _vector_size((1., 2., 3.))\n 3\n >>> _vector_size(array.array('d', [1., 2., 3.]))\n 3\n >>> _vector_size(np.zeros(3))\n 3\n >>> _vector_size(np.zeros((3, 1)))\n 3\n >>> _vector_size(np.zeros((1, 3)))\n Traceback (most recent call last):\n ...\n ValueError: Cannot treat an ndarray of shape (1, 3) as a vector\n \"\"\"\n if isinstance(v, Vector):\n return len(v)\n elif type(v) in (array.array, list, tuple, xrange):\n return len(v)\n elif type(v) == np.ndarray:\n if v.ndim == 1 or (v.ndim == 2 and v.shape[1] == 1):\n return len(v)\n else:\n raise ValueError(\"Cannot treat an ndarray of shape %s as a vector\" % str(v.shape))\n elif _have_scipy and scipy.sparse.issparse(v):\n assert v.shape[1] == 1, \"Expected column vector\"\n return v.shape[0]\n else:\n raise TypeError(\"Cannot treat type %s as a vector\" % type(v))" }, { "instruction": "Write or improve a Python function based on this description:\n\nParse string representation back into the DenseVector.\n\n >>> DenseVector.parse(' [ 0.0,1.0,2.0, 3.0]')\n DenseVector([0.0, 1.0, 2.0, 3.0])", "output": "def parse(s):\n \"\"\"\n Parse string representation back into the DenseVector.\n\n >>> DenseVector.parse(' [ 0.0,1.0,2.0, 3.0]')\n DenseVector([0.0, 1.0, 2.0, 3.0])\n \"\"\"\n start = s.find('[')\n if start == -1:\n raise ValueError(\"Array should start with '['.\")\n end = s.find(']')\n if end == -1:\n raise ValueError(\"Array should end with ']'.\")\n s = s[start + 1: end]\n\n try:\n values = [float(val) for val in s.split(',') if val]\n except ValueError:\n raise ValueError(\"Unable to parse values from %s\" % s)\n return DenseVector(values)" }, { "instruction": "Write or improve a Python function based on this description:\n\nCompute the dot product of two Vectors. We support\n (Numpy array, list, SparseVector, or SciPy sparse)\n and a target NumPy array that is either 1- or 2-dimensional.\n Equivalent to calling numpy.dot of the two vectors.\n\n >>> dense = DenseVector(array.array('d', [1., 2.]))\n >>> dense.dot(dense)\n 5.0\n >>> dense.dot(SparseVector(2, [0, 1], [2., 1.]))\n 4.0\n >>> dense.dot(range(1, 3))\n 5.0\n >>> dense.dot(np.array(range(1, 3)))\n 5.0\n >>> dense.dot([1.,])\n Traceback (most recent call last):\n ...\n AssertionError: dimension mismatch\n >>> dense.dot(np.reshape([1., 2., 3., 4.], (2, 2), order='F'))\n array([ 5., 11.])\n >>> dense.dot(np.reshape([1., 2., 3.], (3, 1), order='F'))\n Traceback (most recent call last):\n ...\n AssertionError: dimension mismatch", "output": "def dot(self, other):\n \"\"\"\n Compute the dot product of two Vectors. We support\n (Numpy array, list, SparseVector, or SciPy sparse)\n and a target NumPy array that is either 1- or 2-dimensional.\n Equivalent to calling numpy.dot of the two vectors.\n\n >>> dense = DenseVector(array.array('d', [1., 2.]))\n >>> dense.dot(dense)\n 5.0\n >>> dense.dot(SparseVector(2, [0, 1], [2., 1.]))\n 4.0\n >>> dense.dot(range(1, 3))\n 5.0\n >>> dense.dot(np.array(range(1, 3)))\n 5.0\n >>> dense.dot([1.,])\n Traceback (most recent call last):\n ...\n AssertionError: dimension mismatch\n >>> dense.dot(np.reshape([1., 2., 3., 4.], (2, 2), order='F'))\n array([ 5., 11.])\n >>> dense.dot(np.reshape([1., 2., 3.], (3, 1), order='F'))\n Traceback (most recent call last):\n ...\n AssertionError: dimension mismatch\n \"\"\"\n if type(other) == np.ndarray:\n if other.ndim > 1:\n assert len(self) == other.shape[0], \"dimension mismatch\"\n return np.dot(self.array, other)\n elif _have_scipy and scipy.sparse.issparse(other):\n assert len(self) == other.shape[0], \"dimension mismatch\"\n return other.transpose().dot(self.toArray())\n else:\n assert len(self) == _vector_size(other), \"dimension mismatch\"\n if isinstance(other, SparseVector):\n return other.dot(self)\n elif isinstance(other, Vector):\n return np.dot(self.toArray(), other.toArray())\n else:\n return np.dot(self.toArray(), other)" }, { "instruction": "Write or improve a Python function based on this description:\n\nSquared distance of two Vectors.\n\n >>> dense1 = DenseVector(array.array('d', [1., 2.]))\n >>> dense1.squared_distance(dense1)\n 0.0\n >>> dense2 = np.array([2., 1.])\n >>> dense1.squared_distance(dense2)\n 2.0\n >>> dense3 = [2., 1.]\n >>> dense1.squared_distance(dense3)\n 2.0\n >>> sparse1 = SparseVector(2, [0, 1], [2., 1.])\n >>> dense1.squared_distance(sparse1)\n 2.0\n >>> dense1.squared_distance([1.,])\n Traceback (most recent call last):\n ...\n AssertionError: dimension mismatch\n >>> dense1.squared_distance(SparseVector(1, [0,], [1.,]))\n Traceback (most recent call last):\n ...\n AssertionError: dimension mismatch", "output": "def squared_distance(self, other):\n \"\"\"\n Squared distance of two Vectors.\n\n >>> dense1 = DenseVector(array.array('d', [1., 2.]))\n >>> dense1.squared_distance(dense1)\n 0.0\n >>> dense2 = np.array([2., 1.])\n >>> dense1.squared_distance(dense2)\n 2.0\n >>> dense3 = [2., 1.]\n >>> dense1.squared_distance(dense3)\n 2.0\n >>> sparse1 = SparseVector(2, [0, 1], [2., 1.])\n >>> dense1.squared_distance(sparse1)\n 2.0\n >>> dense1.squared_distance([1.,])\n Traceback (most recent call last):\n ...\n AssertionError: dimension mismatch\n >>> dense1.squared_distance(SparseVector(1, [0,], [1.,]))\n Traceback (most recent call last):\n ...\n AssertionError: dimension mismatch\n \"\"\"\n assert len(self) == _vector_size(other), \"dimension mismatch\"\n if isinstance(other, SparseVector):\n return other.squared_distance(self)\n elif _have_scipy and scipy.sparse.issparse(other):\n return _convert_to_vector(other).squared_distance(self)\n\n if isinstance(other, Vector):\n other = other.toArray()\n elif not isinstance(other, np.ndarray):\n other = np.array(other)\n diff = self.toArray() - other\n return np.dot(diff, diff)" }, { "instruction": "Write or improve a Python function based on this description:\n\nParse string representation back into the SparseVector.\n\n >>> SparseVector.parse(' (4, [0,1 ],[ 4.0,5.0] )')\n SparseVector(4, {0: 4.0, 1: 5.0})", "output": "def parse(s):\n \"\"\"\n Parse string representation back into the SparseVector.\n\n >>> SparseVector.parse(' (4, [0,1 ],[ 4.0,5.0] )')\n SparseVector(4, {0: 4.0, 1: 5.0})\n \"\"\"\n start = s.find('(')\n if start == -1:\n raise ValueError(\"Tuple should start with '('\")\n end = s.find(')')\n if end == -1:\n raise ValueError(\"Tuple should end with ')'\")\n s = s[start + 1: end].strip()\n\n size = s[: s.find(',')]\n try:\n size = int(size)\n except ValueError:\n raise ValueError(\"Cannot parse size %s.\" % size)\n\n ind_start = s.find('[')\n if ind_start == -1:\n raise ValueError(\"Indices array should start with '['.\")\n ind_end = s.find(']')\n if ind_end == -1:\n raise ValueError(\"Indices array should end with ']'\")\n new_s = s[ind_start + 1: ind_end]\n ind_list = new_s.split(',')\n try:\n indices = [int(ind) for ind in ind_list if ind]\n except ValueError:\n raise ValueError(\"Unable to parse indices from %s.\" % new_s)\n s = s[ind_end + 1:].strip()\n\n val_start = s.find('[')\n if val_start == -1:\n raise ValueError(\"Values array should start with '['.\")\n val_end = s.find(']')\n if val_end == -1:\n raise ValueError(\"Values array should end with ']'.\")\n val_list = s[val_start + 1: val_end].split(',')\n try:\n values = [float(val) for val in val_list if val]\n except ValueError:\n raise ValueError(\"Unable to parse values from %s.\" % s)\n return SparseVector(size, indices, values)" }, { "instruction": "Write or improve a Python function based on this description:\n\nDot product with a SparseVector or 1- or 2-dimensional Numpy array.\n\n >>> a = SparseVector(4, [1, 3], [3.0, 4.0])\n >>> a.dot(a)\n 25.0\n >>> a.dot(array.array('d', [1., 2., 3., 4.]))\n 22.0\n >>> b = SparseVector(4, [2], [1.0])\n >>> a.dot(b)\n 0.0\n >>> a.dot(np.array([[1, 1], [2, 2], [3, 3], [4, 4]]))\n array([ 22., 22.])\n >>> a.dot([1., 2., 3.])\n Traceback (most recent call last):\n ...\n AssertionError: dimension mismatch\n >>> a.dot(np.array([1., 2.]))\n Traceback (most recent call last):\n ...\n AssertionError: dimension mismatch\n >>> a.dot(DenseVector([1., 2.]))\n Traceback (most recent call last):\n ...\n AssertionError: dimension mismatch\n >>> a.dot(np.zeros((3, 2)))\n Traceback (most recent call last):\n ...\n AssertionError: dimension mismatch", "output": "def dot(self, other):\n \"\"\"\n Dot product with a SparseVector or 1- or 2-dimensional Numpy array.\n\n >>> a = SparseVector(4, [1, 3], [3.0, 4.0])\n >>> a.dot(a)\n 25.0\n >>> a.dot(array.array('d', [1., 2., 3., 4.]))\n 22.0\n >>> b = SparseVector(4, [2], [1.0])\n >>> a.dot(b)\n 0.0\n >>> a.dot(np.array([[1, 1], [2, 2], [3, 3], [4, 4]]))\n array([ 22., 22.])\n >>> a.dot([1., 2., 3.])\n Traceback (most recent call last):\n ...\n AssertionError: dimension mismatch\n >>> a.dot(np.array([1., 2.]))\n Traceback (most recent call last):\n ...\n AssertionError: dimension mismatch\n >>> a.dot(DenseVector([1., 2.]))\n Traceback (most recent call last):\n ...\n AssertionError: dimension mismatch\n >>> a.dot(np.zeros((3, 2)))\n Traceback (most recent call last):\n ...\n AssertionError: dimension mismatch\n \"\"\"\n\n if isinstance(other, np.ndarray):\n if other.ndim not in [2, 1]:\n raise ValueError(\"Cannot call dot with %d-dimensional array\" % other.ndim)\n assert len(self) == other.shape[0], \"dimension mismatch\"\n return np.dot(self.values, other[self.indices])\n\n assert len(self) == _vector_size(other), \"dimension mismatch\"\n\n if isinstance(other, DenseVector):\n return np.dot(other.array[self.indices], self.values)\n\n elif isinstance(other, SparseVector):\n # Find out common indices.\n self_cmind = np.in1d(self.indices, other.indices, assume_unique=True)\n self_values = self.values[self_cmind]\n if self_values.size == 0:\n return 0.0\n else:\n other_cmind = np.in1d(other.indices, self.indices, assume_unique=True)\n return np.dot(self_values, other.values[other_cmind])\n\n else:\n return self.dot(_convert_to_vector(other))" }, { "instruction": "Write or improve a Python function based on this description:\n\nSquared distance from a SparseVector or 1-dimensional NumPy array.\n\n >>> a = SparseVector(4, [1, 3], [3.0, 4.0])\n >>> a.squared_distance(a)\n 0.0\n >>> a.squared_distance(array.array('d', [1., 2., 3., 4.]))\n 11.0\n >>> a.squared_distance(np.array([1., 2., 3., 4.]))\n 11.0\n >>> b = SparseVector(4, [2], [1.0])\n >>> a.squared_distance(b)\n 26.0\n >>> b.squared_distance(a)\n 26.0\n >>> b.squared_distance([1., 2.])\n Traceback (most recent call last):\n ...\n AssertionError: dimension mismatch\n >>> b.squared_distance(SparseVector(3, [1,], [1.0,]))\n Traceback (most recent call last):\n ...\n AssertionError: dimension mismatch", "output": "def squared_distance(self, other):\n \"\"\"\n Squared distance from a SparseVector or 1-dimensional NumPy array.\n\n >>> a = SparseVector(4, [1, 3], [3.0, 4.0])\n >>> a.squared_distance(a)\n 0.0\n >>> a.squared_distance(array.array('d', [1., 2., 3., 4.]))\n 11.0\n >>> a.squared_distance(np.array([1., 2., 3., 4.]))\n 11.0\n >>> b = SparseVector(4, [2], [1.0])\n >>> a.squared_distance(b)\n 26.0\n >>> b.squared_distance(a)\n 26.0\n >>> b.squared_distance([1., 2.])\n Traceback (most recent call last):\n ...\n AssertionError: dimension mismatch\n >>> b.squared_distance(SparseVector(3, [1,], [1.0,]))\n Traceback (most recent call last):\n ...\n AssertionError: dimension mismatch\n \"\"\"\n assert len(self) == _vector_size(other), \"dimension mismatch\"\n\n if isinstance(other, np.ndarray) or isinstance(other, DenseVector):\n if isinstance(other, np.ndarray) and other.ndim != 1:\n raise Exception(\"Cannot call squared_distance with %d-dimensional array\" %\n other.ndim)\n if isinstance(other, DenseVector):\n other = other.array\n sparse_ind = np.zeros(other.size, dtype=bool)\n sparse_ind[self.indices] = True\n dist = other[sparse_ind] - self.values\n result = np.dot(dist, dist)\n\n other_ind = other[~sparse_ind]\n result += np.dot(other_ind, other_ind)\n return result\n\n elif isinstance(other, SparseVector):\n result = 0.0\n i, j = 0, 0\n while i < len(self.indices) and j < len(other.indices):\n if self.indices[i] == other.indices[j]:\n diff = self.values[i] - other.values[j]\n result += diff * diff\n i += 1\n j += 1\n elif self.indices[i] < other.indices[j]:\n result += self.values[i] * self.values[i]\n i += 1\n else:\n result += other.values[j] * other.values[j]\n j += 1\n while i < len(self.indices):\n result += self.values[i] * self.values[i]\n i += 1\n while j < len(other.indices):\n result += other.values[j] * other.values[j]\n j += 1\n return result\n else:\n return self.squared_distance(_convert_to_vector(other))" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns a copy of this SparseVector as a 1-dimensional NumPy array.", "output": "def toArray(self):\n \"\"\"\n Returns a copy of this SparseVector as a 1-dimensional NumPy array.\n \"\"\"\n arr = np.zeros((self.size,), dtype=np.float64)\n arr[self.indices] = self.values\n return arr" }, { "instruction": "Write or improve a Python function based on this description:\n\nConvert this vector to the new mllib-local representation.\n This does NOT copy the data; it copies references.\n\n :return: :py:class:`pyspark.ml.linalg.SparseVector`\n\n .. versionadded:: 2.0.0", "output": "def asML(self):\n \"\"\"\n Convert this vector to the new mllib-local representation.\n This does NOT copy the data; it copies references.\n\n :return: :py:class:`pyspark.ml.linalg.SparseVector`\n\n .. versionadded:: 2.0.0\n \"\"\"\n return newlinalg.SparseVector(self.size, self.indices, self.values)" }, { "instruction": "Write or improve a Python function based on this description:\n\nCreate a dense vector of 64-bit floats from a Python list or numbers.\n\n >>> Vectors.dense([1, 2, 3])\n DenseVector([1.0, 2.0, 3.0])\n >>> Vectors.dense(1.0, 2.0)\n DenseVector([1.0, 2.0])", "output": "def dense(*elements):\n \"\"\"\n Create a dense vector of 64-bit floats from a Python list or numbers.\n\n >>> Vectors.dense([1, 2, 3])\n DenseVector([1.0, 2.0, 3.0])\n >>> Vectors.dense(1.0, 2.0)\n DenseVector([1.0, 2.0])\n \"\"\"\n if len(elements) == 1 and not isinstance(elements[0], (float, int, long)):\n # it's list, numpy.array or other iterable object.\n elements = elements[0]\n return DenseVector(elements)" }, { "instruction": "Write or improve a Python function based on this description:\n\nConvert a vector from the new mllib-local representation.\n This does NOT copy the data; it copies references.\n\n :param vec: a :py:class:`pyspark.ml.linalg.Vector`\n :return: a :py:class:`pyspark.mllib.linalg.Vector`\n\n .. versionadded:: 2.0.0", "output": "def fromML(vec):\n \"\"\"\n Convert a vector from the new mllib-local representation.\n This does NOT copy the data; it copies references.\n\n :param vec: a :py:class:`pyspark.ml.linalg.Vector`\n :return: a :py:class:`pyspark.mllib.linalg.Vector`\n\n .. versionadded:: 2.0.0\n \"\"\"\n if isinstance(vec, newlinalg.DenseVector):\n return DenseVector(vec.array)\n elif isinstance(vec, newlinalg.SparseVector):\n return SparseVector(vec.size, vec.indices, vec.values)\n else:\n raise TypeError(\"Unsupported vector type %s\" % type(vec))" }, { "instruction": "Write or improve a Python function based on this description:\n\nSquared distance between two vectors.\n a and b can be of type SparseVector, DenseVector, np.ndarray\n or array.array.\n\n >>> a = Vectors.sparse(4, [(0, 1), (3, 4)])\n >>> b = Vectors.dense([2, 5, 4, 1])\n >>> a.squared_distance(b)\n 51.0", "output": "def squared_distance(v1, v2):\n \"\"\"\n Squared distance between two vectors.\n a and b can be of type SparseVector, DenseVector, np.ndarray\n or array.array.\n\n >>> a = Vectors.sparse(4, [(0, 1), (3, 4)])\n >>> b = Vectors.dense([2, 5, 4, 1])\n >>> a.squared_distance(b)\n 51.0\n \"\"\"\n v1, v2 = _convert_to_vector(v1), _convert_to_vector(v2)\n return v1.squared_distance(v2)" }, { "instruction": "Write or improve a Python function based on this description:\n\nParse a string representation back into the Vector.\n\n >>> Vectors.parse('[2,1,2 ]')\n DenseVector([2.0, 1.0, 2.0])\n >>> Vectors.parse(' ( 100, [0], [2])')\n SparseVector(100, {0: 2.0})", "output": "def parse(s):\n \"\"\"Parse a string representation back into the Vector.\n\n >>> Vectors.parse('[2,1,2 ]')\n DenseVector([2.0, 1.0, 2.0])\n >>> Vectors.parse(' ( 100, [0], [2])')\n SparseVector(100, {0: 2.0})\n \"\"\"\n if s.find('(') == -1 and s.find('[') != -1:\n return DenseVector.parse(s)\n elif s.find('(') != -1:\n return SparseVector.parse(s)\n else:\n raise ValueError(\n \"Cannot find tokens '[' or '(' from the input string.\")" }, { "instruction": "Write or improve a Python function based on this description:\n\nCheck equality between sparse/dense vectors,\n v1_indices and v2_indices assume to be strictly increasing.", "output": "def _equals(v1_indices, v1_values, v2_indices, v2_values):\n \"\"\"\n Check equality between sparse/dense vectors,\n v1_indices and v2_indices assume to be strictly increasing.\n \"\"\"\n v1_size = len(v1_values)\n v2_size = len(v2_values)\n k1 = 0\n k2 = 0\n all_equal = True\n while all_equal:\n while k1 < v1_size and v1_values[k1] == 0:\n k1 += 1\n while k2 < v2_size and v2_values[k2] == 0:\n k2 += 1\n\n if k1 >= v1_size or k2 >= v2_size:\n return k1 >= v1_size and k2 >= v2_size\n\n all_equal = v1_indices[k1] == v2_indices[k2] and v1_values[k1] == v2_values[k2]\n k1 += 1\n k2 += 1\n return all_equal" }, { "instruction": "Write or improve a Python function based on this description:\n\nConvert Matrix attributes which are array-like or buffer to array.", "output": "def _convert_to_array(array_like, dtype):\n \"\"\"\n Convert Matrix attributes which are array-like or buffer to array.\n \"\"\"\n if isinstance(array_like, bytes):\n return np.frombuffer(array_like, dtype=dtype)\n return np.asarray(array_like, dtype=dtype)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn an numpy.ndarray\n\n >>> m = DenseMatrix(2, 2, range(4))\n >>> m.toArray()\n array([[ 0., 2.],\n [ 1., 3.]])", "output": "def toArray(self):\n \"\"\"\n Return an numpy.ndarray\n\n >>> m = DenseMatrix(2, 2, range(4))\n >>> m.toArray()\n array([[ 0., 2.],\n [ 1., 3.]])\n \"\"\"\n if self.isTransposed:\n return np.asfortranarray(\n self.values.reshape((self.numRows, self.numCols)))\n else:\n return self.values.reshape((self.numRows, self.numCols), order='F')" }, { "instruction": "Write or improve a Python function based on this description:\n\nConvert to SparseMatrix", "output": "def toSparse(self):\n \"\"\"Convert to SparseMatrix\"\"\"\n if self.isTransposed:\n values = np.ravel(self.toArray(), order='F')\n else:\n values = self.values\n indices = np.nonzero(values)[0]\n colCounts = np.bincount(indices // self.numRows)\n colPtrs = np.cumsum(np.hstack(\n (0, colCounts, np.zeros(self.numCols - colCounts.size))))\n values = values[indices]\n rowIndices = indices % self.numRows\n\n return SparseMatrix(self.numRows, self.numCols, colPtrs, rowIndices, values)" }, { "instruction": "Write or improve a Python function based on this description:\n\nConvert this matrix to the new mllib-local representation.\n This does NOT copy the data; it copies references.\n\n :return: :py:class:`pyspark.ml.linalg.DenseMatrix`\n\n .. versionadded:: 2.0.0", "output": "def asML(self):\n \"\"\"\n Convert this matrix to the new mllib-local representation.\n This does NOT copy the data; it copies references.\n\n :return: :py:class:`pyspark.ml.linalg.DenseMatrix`\n\n .. versionadded:: 2.0.0\n \"\"\"\n return newlinalg.DenseMatrix(self.numRows, self.numCols, self.values, self.isTransposed)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn an numpy.ndarray", "output": "def toArray(self):\n \"\"\"\n Return an numpy.ndarray\n \"\"\"\n A = np.zeros((self.numRows, self.numCols), dtype=np.float64, order='F')\n for k in xrange(self.colPtrs.size - 1):\n startptr = self.colPtrs[k]\n endptr = self.colPtrs[k + 1]\n if self.isTransposed:\n A[k, self.rowIndices[startptr:endptr]] = self.values[startptr:endptr]\n else:\n A[self.rowIndices[startptr:endptr], k] = self.values[startptr:endptr]\n return A" }, { "instruction": "Write or improve a Python function based on this description:\n\nConvert this matrix to the new mllib-local representation.\n This does NOT copy the data; it copies references.\n\n :return: :py:class:`pyspark.ml.linalg.SparseMatrix`\n\n .. versionadded:: 2.0.0", "output": "def asML(self):\n \"\"\"\n Convert this matrix to the new mllib-local representation.\n This does NOT copy the data; it copies references.\n\n :return: :py:class:`pyspark.ml.linalg.SparseMatrix`\n\n .. versionadded:: 2.0.0\n \"\"\"\n return newlinalg.SparseMatrix(self.numRows, self.numCols, self.colPtrs, self.rowIndices,\n self.values, self.isTransposed)" }, { "instruction": "Write or improve a Python function based on this description:\n\nCreate a SparseMatrix", "output": "def sparse(numRows, numCols, colPtrs, rowIndices, values):\n \"\"\"\n Create a SparseMatrix\n \"\"\"\n return SparseMatrix(numRows, numCols, colPtrs, rowIndices, values)" }, { "instruction": "Write or improve a Python function based on this description:\n\nConvert a matrix from the new mllib-local representation.\n This does NOT copy the data; it copies references.\n\n :param mat: a :py:class:`pyspark.ml.linalg.Matrix`\n :return: a :py:class:`pyspark.mllib.linalg.Matrix`\n\n .. versionadded:: 2.0.0", "output": "def fromML(mat):\n \"\"\"\n Convert a matrix from the new mllib-local representation.\n This does NOT copy the data; it copies references.\n\n :param mat: a :py:class:`pyspark.ml.linalg.Matrix`\n :return: a :py:class:`pyspark.mllib.linalg.Matrix`\n\n .. versionadded:: 2.0.0\n \"\"\"\n if isinstance(mat, newlinalg.DenseMatrix):\n return DenseMatrix(mat.numRows, mat.numCols, mat.values, mat.isTransposed)\n elif isinstance(mat, newlinalg.SparseMatrix):\n return SparseMatrix(mat.numRows, mat.numCols, mat.colPtrs, mat.rowIndices,\n mat.values, mat.isTransposed)\n else:\n raise TypeError(\"Unsupported matrix type %s\" % type(mat))" }, { "instruction": "Write or improve a Python function based on this description:\n\nGiven a large dataset and an item, approximately find at most k items which have the\n closest distance to the item. If the :py:attr:`outputCol` is missing, the method will\n transform the data; if the :py:attr:`outputCol` exists, it will use that. This allows\n caching of the transformed data when necessary.\n\n .. note:: This method is experimental and will likely change behavior in the next release.\n\n :param dataset: The dataset to search for nearest neighbors of the key.\n :param key: Feature vector representing the item to search for.\n :param numNearestNeighbors: The maximum number of nearest neighbors.\n :param distCol: Output column for storing the distance between each result row and the key.\n Use \"distCol\" as default value if it's not specified.\n :return: A dataset containing at most k items closest to the key. A column \"distCol\" is\n added to show the distance between each row and the key.", "output": "def approxNearestNeighbors(self, dataset, key, numNearestNeighbors, distCol=\"distCol\"):\n \"\"\"\n Given a large dataset and an item, approximately find at most k items which have the\n closest distance to the item. If the :py:attr:`outputCol` is missing, the method will\n transform the data; if the :py:attr:`outputCol` exists, it will use that. This allows\n caching of the transformed data when necessary.\n\n .. note:: This method is experimental and will likely change behavior in the next release.\n\n :param dataset: The dataset to search for nearest neighbors of the key.\n :param key: Feature vector representing the item to search for.\n :param numNearestNeighbors: The maximum number of nearest neighbors.\n :param distCol: Output column for storing the distance between each result row and the key.\n Use \"distCol\" as default value if it's not specified.\n :return: A dataset containing at most k items closest to the key. A column \"distCol\" is\n added to show the distance between each row and the key.\n \"\"\"\n return self._call_java(\"approxNearestNeighbors\", dataset, key, numNearestNeighbors,\n distCol)" }, { "instruction": "Write or improve a Python function based on this description:\n\nJoin two datasets to approximately find all pairs of rows whose distance are smaller than\n the threshold. If the :py:attr:`outputCol` is missing, the method will transform the data;\n if the :py:attr:`outputCol` exists, it will use that. This allows caching of the\n transformed data when necessary.\n\n :param datasetA: One of the datasets to join.\n :param datasetB: Another dataset to join.\n :param threshold: The threshold for the distance of row pairs.\n :param distCol: Output column for storing the distance between each pair of rows. Use\n \"distCol\" as default value if it's not specified.\n :return: A joined dataset containing pairs of rows. The original rows are in columns\n \"datasetA\" and \"datasetB\", and a column \"distCol\" is added to show the distance\n between each pair.", "output": "def approxSimilarityJoin(self, datasetA, datasetB, threshold, distCol=\"distCol\"):\n \"\"\"\n Join two datasets to approximately find all pairs of rows whose distance are smaller than\n the threshold. If the :py:attr:`outputCol` is missing, the method will transform the data;\n if the :py:attr:`outputCol` exists, it will use that. This allows caching of the\n transformed data when necessary.\n\n :param datasetA: One of the datasets to join.\n :param datasetB: Another dataset to join.\n :param threshold: The threshold for the distance of row pairs.\n :param distCol: Output column for storing the distance between each pair of rows. Use\n \"distCol\" as default value if it's not specified.\n :return: A joined dataset containing pairs of rows. The original rows are in columns\n \"datasetA\" and \"datasetB\", and a column \"distCol\" is added to show the distance\n between each pair.\n \"\"\"\n threshold = TypeConverters.toFloat(threshold)\n return self._call_java(\"approxSimilarityJoin\", datasetA, datasetB, threshold, distCol)" }, { "instruction": "Write or improve a Python function based on this description:\n\nConstruct the model directly from an array of label strings,\n requires an active SparkContext.", "output": "def from_labels(cls, labels, inputCol, outputCol=None, handleInvalid=None):\n \"\"\"\n Construct the model directly from an array of label strings,\n requires an active SparkContext.\n \"\"\"\n sc = SparkContext._active_spark_context\n java_class = sc._gateway.jvm.java.lang.String\n jlabels = StringIndexerModel._new_java_array(labels, java_class)\n model = StringIndexerModel._create_from_java_class(\n \"org.apache.spark.ml.feature.StringIndexerModel\", jlabels)\n model.setInputCol(inputCol)\n if outputCol is not None:\n model.setOutputCol(outputCol)\n if handleInvalid is not None:\n model.setHandleInvalid(handleInvalid)\n return model" }, { "instruction": "Write or improve a Python function based on this description:\n\nConstruct the model directly from an array of array of label strings,\n requires an active SparkContext.", "output": "def from_arrays_of_labels(cls, arrayOfLabels, inputCols, outputCols=None,\n handleInvalid=None):\n \"\"\"\n Construct the model directly from an array of array of label strings,\n requires an active SparkContext.\n \"\"\"\n sc = SparkContext._active_spark_context\n java_class = sc._gateway.jvm.java.lang.String\n jlabels = StringIndexerModel._new_java_array(arrayOfLabels, java_class)\n model = StringIndexerModel._create_from_java_class(\n \"org.apache.spark.ml.feature.StringIndexerModel\", jlabels)\n model.setInputCols(inputCols)\n if outputCols is not None:\n model.setOutputCols(outputCols)\n if handleInvalid is not None:\n model.setHandleInvalid(handleInvalid)\n return model" }, { "instruction": "Write or improve a Python function based on this description:\n\nsetParams(self, inputCol=None, outputCol=None, stopWords=None, caseSensitive=false, \\\n locale=None)\n Sets params for this StopWordRemover.", "output": "def setParams(self, inputCol=None, outputCol=None, stopWords=None, caseSensitive=False,\n locale=None):\n \"\"\"\n setParams(self, inputCol=None, outputCol=None, stopWords=None, caseSensitive=false, \\\n locale=None)\n Sets params for this StopWordRemover.\n \"\"\"\n kwargs = self._input_kwargs\n return self._set(**kwargs)" }, { "instruction": "Write or improve a Python function based on this description:\n\nLoads the default stop words for the given language.\n Supported languages: danish, dutch, english, finnish, french, german, hungarian,\n italian, norwegian, portuguese, russian, spanish, swedish, turkish", "output": "def loadDefaultStopWords(language):\n \"\"\"\n Loads the default stop words for the given language.\n Supported languages: danish, dutch, english, finnish, french, german, hungarian,\n italian, norwegian, portuguese, russian, spanish, swedish, turkish\n \"\"\"\n stopWordsObj = _jvm().org.apache.spark.ml.feature.StopWordsRemover\n return list(stopWordsObj.loadDefaultStopWords(language))" }, { "instruction": "Write or improve a Python function based on this description:\n\nFind \"num\" number of words closest in similarity to \"word\".\n word can be a string or vector representation.\n Returns a dataframe with two fields word and similarity (which\n gives the cosine similarity).", "output": "def findSynonyms(self, word, num):\n \"\"\"\n Find \"num\" number of words closest in similarity to \"word\".\n word can be a string or vector representation.\n Returns a dataframe with two fields word and similarity (which\n gives the cosine similarity).\n \"\"\"\n if not isinstance(word, basestring):\n word = _convert_to_vector(word)\n return self._call_java(\"findSynonyms\", word, num)" }, { "instruction": "Write or improve a Python function based on this description:\n\nFind \"num\" number of words closest in similarity to \"word\".\n word can be a string or vector representation.\n Returns an array with two fields word and similarity (which\n gives the cosine similarity).", "output": "def findSynonymsArray(self, word, num):\n \"\"\"\n Find \"num\" number of words closest in similarity to \"word\".\n word can be a string or vector representation.\n Returns an array with two fields word and similarity (which\n gives the cosine similarity).\n \"\"\"\n if not isinstance(word, basestring):\n word = _convert_to_vector(word)\n tuples = self._java_obj.findSynonymsArray(word, num)\n return list(map(lambda st: (st._1(), st._2()), list(tuples)))" }, { "instruction": "Write or improve a Python function based on this description:\n\nHook an exception handler into Py4j, which could capture some SQL exceptions in Java.\n\n When calling Java API, it will call `get_return_value` to parse the returned object.\n If any exception happened in JVM, the result will be Java exception object, it raise\n py4j.protocol.Py4JJavaError. We replace the original `get_return_value` with one that\n could capture the Java exception and throw a Python one (with the same error message).\n\n It's idempotent, could be called multiple times.", "output": "def install_exception_handler():\n \"\"\"\n Hook an exception handler into Py4j, which could capture some SQL exceptions in Java.\n\n When calling Java API, it will call `get_return_value` to parse the returned object.\n If any exception happened in JVM, the result will be Java exception object, it raise\n py4j.protocol.Py4JJavaError. We replace the original `get_return_value` with one that\n could capture the Java exception and throw a Python one (with the same error message).\n\n It's idempotent, could be called multiple times.\n \"\"\"\n original = py4j.protocol.get_return_value\n # The original `get_return_value` is not patched, it's idempotent.\n patched = capture_sql_exception(original)\n # only patch the one used in py4j.java_gateway (call Java API)\n py4j.java_gateway.get_return_value = patched" }, { "instruction": "Write or improve a Python function based on this description:\n\nConvert python list to java type array\n :param gateway: Py4j Gateway\n :param jtype: java type of element in array\n :param arr: python type list", "output": "def toJArray(gateway, jtype, arr):\n \"\"\"\n Convert python list to java type array\n :param gateway: Py4j Gateway\n :param jtype: java type of element in array\n :param arr: python type list\n \"\"\"\n jarr = gateway.new_array(jtype, len(arr))\n for i in range(0, len(arr)):\n jarr[i] = arr[i]\n return jarr" }, { "instruction": "Write or improve a Python function based on this description:\n\nRaise ImportError if minimum version of Pandas is not installed", "output": "def require_minimum_pandas_version():\n \"\"\" Raise ImportError if minimum version of Pandas is not installed\n \"\"\"\n # TODO(HyukjinKwon): Relocate and deduplicate the version specification.\n minimum_pandas_version = \"0.19.2\"\n\n from distutils.version import LooseVersion\n try:\n import pandas\n have_pandas = True\n except ImportError:\n have_pandas = False\n if not have_pandas:\n raise ImportError(\"Pandas >= %s must be installed; however, \"\n \"it was not found.\" % minimum_pandas_version)\n if LooseVersion(pandas.__version__) < LooseVersion(minimum_pandas_version):\n raise ImportError(\"Pandas >= %s must be installed; however, \"\n \"your version was %s.\" % (minimum_pandas_version, pandas.__version__))" }, { "instruction": "Write or improve a Python function based on this description:\n\nRaise ImportError if minimum version of pyarrow is not installed", "output": "def require_minimum_pyarrow_version():\n \"\"\" Raise ImportError if minimum version of pyarrow is not installed\n \"\"\"\n # TODO(HyukjinKwon): Relocate and deduplicate the version specification.\n minimum_pyarrow_version = \"0.12.1\"\n\n from distutils.version import LooseVersion\n try:\n import pyarrow\n have_arrow = True\n except ImportError:\n have_arrow = False\n if not have_arrow:\n raise ImportError(\"PyArrow >= %s must be installed; however, \"\n \"it was not found.\" % minimum_pyarrow_version)\n if LooseVersion(pyarrow.__version__) < LooseVersion(minimum_pyarrow_version):\n raise ImportError(\"PyArrow >= %s must be installed; however, \"\n \"your version was %s.\" % (minimum_pyarrow_version, pyarrow.__version__))" }, { "instruction": "Write or improve a Python function based on this description:\n\nlaunch jvm gateway\n :param conf: spark configuration passed to spark-submit\n :param popen_kwargs: Dictionary of kwargs to pass to Popen when spawning\n the py4j JVM. This is a developer feature intended for use in\n customizing how pyspark interacts with the py4j JVM (e.g., capturing\n stdout/stderr).\n :return:", "output": "def launch_gateway(conf=None, popen_kwargs=None):\n \"\"\"\n launch jvm gateway\n :param conf: spark configuration passed to spark-submit\n :param popen_kwargs: Dictionary of kwargs to pass to Popen when spawning\n the py4j JVM. This is a developer feature intended for use in\n customizing how pyspark interacts with the py4j JVM (e.g., capturing\n stdout/stderr).\n :return:\n \"\"\"\n if \"PYSPARK_GATEWAY_PORT\" in os.environ:\n gateway_port = int(os.environ[\"PYSPARK_GATEWAY_PORT\"])\n gateway_secret = os.environ[\"PYSPARK_GATEWAY_SECRET\"]\n # Process already exists\n proc = None\n else:\n SPARK_HOME = _find_spark_home()\n # Launch the Py4j gateway using Spark's run command so that we pick up the\n # proper classpath and settings from spark-env.sh\n on_windows = platform.system() == \"Windows\"\n script = \"./bin/spark-submit.cmd\" if on_windows else \"./bin/spark-submit\"\n command = [os.path.join(SPARK_HOME, script)]\n if conf:\n for k, v in conf.getAll():\n command += ['--conf', '%s=%s' % (k, v)]\n submit_args = os.environ.get(\"PYSPARK_SUBMIT_ARGS\", \"pyspark-shell\")\n if os.environ.get(\"SPARK_TESTING\"):\n submit_args = ' '.join([\n \"--conf spark.ui.enabled=false\",\n submit_args\n ])\n command = command + shlex.split(submit_args)\n\n # Create a temporary directory where the gateway server should write the connection\n # information.\n conn_info_dir = tempfile.mkdtemp()\n try:\n fd, conn_info_file = tempfile.mkstemp(dir=conn_info_dir)\n os.close(fd)\n os.unlink(conn_info_file)\n\n env = dict(os.environ)\n env[\"_PYSPARK_DRIVER_CONN_INFO_PATH\"] = conn_info_file\n\n # Launch the Java gateway.\n popen_kwargs = {} if popen_kwargs is None else popen_kwargs\n # We open a pipe to stdin so that the Java gateway can die when the pipe is broken\n popen_kwargs['stdin'] = PIPE\n # We always set the necessary environment variables.\n popen_kwargs['env'] = env\n if not on_windows:\n # Don't send ctrl-c / SIGINT to the Java gateway:\n def preexec_func():\n signal.signal(signal.SIGINT, signal.SIG_IGN)\n popen_kwargs['preexec_fn'] = preexec_func\n proc = Popen(command, **popen_kwargs)\n else:\n # preexec_fn not supported on Windows\n proc = Popen(command, **popen_kwargs)\n\n # Wait for the file to appear, or for the process to exit, whichever happens first.\n while not proc.poll() and not os.path.isfile(conn_info_file):\n time.sleep(0.1)\n\n if not os.path.isfile(conn_info_file):\n raise Exception(\"Java gateway process exited before sending its port number\")\n\n with open(conn_info_file, \"rb\") as info:\n gateway_port = read_int(info)\n gateway_secret = UTF8Deserializer().loads(info)\n finally:\n shutil.rmtree(conn_info_dir)\n\n # In Windows, ensure the Java child processes do not linger after Python has exited.\n # In UNIX-based systems, the child process can kill itself on broken pipe (i.e. when\n # the parent process' stdin sends an EOF). In Windows, however, this is not possible\n # because java.lang.Process reads directly from the parent process' stdin, contending\n # with any opportunity to read an EOF from the parent. Note that this is only best\n # effort and will not take effect if the python process is violently terminated.\n if on_windows:\n # In Windows, the child process here is \"spark-submit.cmd\", not the JVM itself\n # (because the UNIX \"exec\" command is not available). This means we cannot simply\n # call proc.kill(), which kills only the \"spark-submit.cmd\" process but not the\n # JVMs. Instead, we use \"taskkill\" with the tree-kill option \"/t\" to terminate all\n # child processes in the tree (http://technet.microsoft.com/en-us/library/bb491009.aspx)\n def killChild():\n Popen([\"cmd\", \"/c\", \"taskkill\", \"/f\", \"/t\", \"/pid\", str(proc.pid)])\n atexit.register(killChild)\n\n # Connect to the gateway\n gateway = JavaGateway(\n gateway_parameters=GatewayParameters(port=gateway_port, auth_token=gateway_secret,\n auto_convert=True))\n # Store a reference to the Popen object for use by the caller (e.g., in reading stdout/stderr)\n gateway.proc = proc\n\n # Import the classes used by PySpark\n java_import(gateway.jvm, \"org.apache.spark.SparkConf\")\n java_import(gateway.jvm, \"org.apache.spark.api.java.*\")\n java_import(gateway.jvm, \"org.apache.spark.api.python.*\")\n java_import(gateway.jvm, \"org.apache.spark.ml.python.*\")\n java_import(gateway.jvm, \"org.apache.spark.mllib.api.python.*\")\n # TODO(davies): move into sql\n java_import(gateway.jvm, \"org.apache.spark.sql.*\")\n java_import(gateway.jvm, \"org.apache.spark.sql.api.python.*\")\n java_import(gateway.jvm, \"org.apache.spark.sql.hive.*\")\n java_import(gateway.jvm, \"scala.Tuple2\")\n\n return gateway" }, { "instruction": "Write or improve a Python function based on this description:\n\nPerforms the authentication protocol defined by the SocketAuthHelper class on the given\n file-like object 'conn'.", "output": "def _do_server_auth(conn, auth_secret):\n \"\"\"\n Performs the authentication protocol defined by the SocketAuthHelper class on the given\n file-like object 'conn'.\n \"\"\"\n write_with_length(auth_secret.encode(\"utf-8\"), conn)\n conn.flush()\n reply = UTF8Deserializer().loads(conn)\n if reply != \"ok\":\n conn.close()\n raise Exception(\"Unexpected reply from iterator server.\")" }, { "instruction": "Write or improve a Python function based on this description:\n\nConnect to local host, authenticate with it, and return a (sockfile,sock) for that connection.\n Handles IPV4 & IPV6, does some error handling.\n :param port\n :param auth_secret\n :return: a tuple with (sockfile, sock)", "output": "def local_connect_and_auth(port, auth_secret):\n \"\"\"\n Connect to local host, authenticate with it, and return a (sockfile,sock) for that connection.\n Handles IPV4 & IPV6, does some error handling.\n :param port\n :param auth_secret\n :return: a tuple with (sockfile, sock)\n \"\"\"\n sock = None\n errors = []\n # Support for both IPv4 and IPv6.\n # On most of IPv6-ready systems, IPv6 will take precedence.\n for res in socket.getaddrinfo(\"127.0.0.1\", port, socket.AF_UNSPEC, socket.SOCK_STREAM):\n af, socktype, proto, _, sa = res\n try:\n sock = socket.socket(af, socktype, proto)\n sock.settimeout(15)\n sock.connect(sa)\n sockfile = sock.makefile(\"rwb\", 65536)\n _do_server_auth(sockfile, auth_secret)\n return (sockfile, sock)\n except socket.error as e:\n emsg = _exception_message(e)\n errors.append(\"tried to connect to %s, but an error occured: %s\" % (sa, emsg))\n sock.close()\n sock = None\n raise Exception(\"could not open socket: %s\" % errors)" }, { "instruction": "Write or improve a Python function based on this description:\n\nStart callback server if not already started. The callback server is needed if the Java\n driver process needs to callback into the Python driver process to execute Python code.", "output": "def ensure_callback_server_started(gw):\n \"\"\"\n Start callback server if not already started. The callback server is needed if the Java\n driver process needs to callback into the Python driver process to execute Python code.\n \"\"\"\n\n # getattr will fallback to JVM, so we cannot test by hasattr()\n if \"_callback_server\" not in gw.__dict__ or gw._callback_server is None:\n gw.callback_server_parameters.eager_load = True\n gw.callback_server_parameters.daemonize = True\n gw.callback_server_parameters.daemonize_connections = True\n gw.callback_server_parameters.port = 0\n gw.start_callback_server(gw.callback_server_parameters)\n cbport = gw._callback_server.server_socket.getsockname()[1]\n gw._callback_server.port = cbport\n # gateway with real port\n gw._python_proxy_port = gw._callback_server.port\n # get the GatewayServer object in JVM by ID\n jgws = JavaObject(\"GATEWAY_SERVER\", gw._gateway_client)\n # update the port of CallbackClient with real port\n jgws.resetCallbackClient(jgws.getCallbackClient().getAddress(), gw._python_proxy_port)" }, { "instruction": "Write or improve a Python function based on this description:\n\nFind the SPARK_HOME.", "output": "def _find_spark_home():\n \"\"\"Find the SPARK_HOME.\"\"\"\n # If the environment has SPARK_HOME set trust it.\n if \"SPARK_HOME\" in os.environ:\n return os.environ[\"SPARK_HOME\"]\n\n def is_spark_home(path):\n \"\"\"Takes a path and returns true if the provided path could be a reasonable SPARK_HOME\"\"\"\n return (os.path.isfile(os.path.join(path, \"bin/spark-submit\")) and\n (os.path.isdir(os.path.join(path, \"jars\")) or\n os.path.isdir(os.path.join(path, \"assembly\"))))\n\n paths = [\"../\", os.path.dirname(os.path.realpath(__file__))]\n\n # Add the path of the PySpark module if it exists\n if sys.version < \"3\":\n import imp\n try:\n module_home = imp.find_module(\"pyspark\")[1]\n paths.append(module_home)\n # If we are installed in edit mode also look two dirs up\n paths.append(os.path.join(module_home, \"../../\"))\n except ImportError:\n # Not pip installed no worries\n pass\n else:\n from importlib.util import find_spec\n try:\n module_home = os.path.dirname(find_spec(\"pyspark\").origin)\n paths.append(module_home)\n # If we are installed in edit mode also look two dirs up\n paths.append(os.path.join(module_home, \"../../\"))\n except ImportError:\n # Not pip installed no worries\n pass\n\n # Normalize the paths\n paths = [os.path.abspath(p) for p in paths]\n\n try:\n return next(path for path in paths if is_spark_home(path))\n except StopIteration:\n print(\"Could not find valid SPARK_HOME while searching {0}\".format(paths), file=sys.stderr)\n sys.exit(-1)" }, { "instruction": "Write or improve a Python function based on this description:\n\nCalculates URL contributions to the rank of other URLs.", "output": "def computeContribs(urls, rank):\n \"\"\"Calculates URL contributions to the rank of other URLs.\"\"\"\n num_urls = len(urls)\n for url in urls:\n yield (url, rank / num_urls)" }, { "instruction": "Write or improve a Python function based on this description:\n\nGets summary (e.g. cluster assignments, cluster sizes) of the model trained on the\n training set. An exception is thrown if no summary exists.", "output": "def summary(self):\n \"\"\"\n Gets summary (e.g. cluster assignments, cluster sizes) of the model trained on the\n training set. An exception is thrown if no summary exists.\n \"\"\"\n if self.hasSummary:\n return GaussianMixtureSummary(super(GaussianMixtureModel, self).summary)\n else:\n raise RuntimeError(\"No training summary available for this %s\" %\n self.__class__.__name__)" }, { "instruction": "Write or improve a Python function based on this description:\n\nGets summary (e.g. cluster assignments, cluster sizes) of the model trained on the\n training set. An exception is thrown if no summary exists.", "output": "def summary(self):\n \"\"\"\n Gets summary (e.g. cluster assignments, cluster sizes) of the model trained on the\n training set. An exception is thrown if no summary exists.\n \"\"\"\n if self.hasSummary:\n return KMeansSummary(super(KMeansModel, self).summary)\n else:\n raise RuntimeError(\"No training summary available for this %s\" %\n self.__class__.__name__)" }, { "instruction": "Write or improve a Python function based on this description:\n\nGets summary (e.g. cluster assignments, cluster sizes) of the model trained on the\n training set. An exception is thrown if no summary exists.", "output": "def summary(self):\n \"\"\"\n Gets summary (e.g. cluster assignments, cluster sizes) of the model trained on the\n training set. An exception is thrown if no summary exists.\n \"\"\"\n if self.hasSummary:\n return BisectingKMeansSummary(super(BisectingKMeansModel, self).summary)\n else:\n raise RuntimeError(\"No training summary available for this %s\" %\n self.__class__.__name__)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns the image schema.\n\n :return: a :class:`StructType` with a single column of images\n named \"image\" (nullable) and having the same type returned by :meth:`columnSchema`.\n\n .. versionadded:: 2.3.0", "output": "def imageSchema(self):\n \"\"\"\n Returns the image schema.\n\n :return: a :class:`StructType` with a single column of images\n named \"image\" (nullable) and having the same type returned by :meth:`columnSchema`.\n\n .. versionadded:: 2.3.0\n \"\"\"\n\n if self._imageSchema is None:\n ctx = SparkContext._active_spark_context\n jschema = ctx._jvm.org.apache.spark.ml.image.ImageSchema.imageSchema()\n self._imageSchema = _parse_datatype_json_string(jschema.json())\n return self._imageSchema" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns the OpenCV type mapping supported.\n\n :return: a dictionary containing the OpenCV type mapping supported.\n\n .. versionadded:: 2.3.0", "output": "def ocvTypes(self):\n \"\"\"\n Returns the OpenCV type mapping supported.\n\n :return: a dictionary containing the OpenCV type mapping supported.\n\n .. versionadded:: 2.3.0\n \"\"\"\n\n if self._ocvTypes is None:\n ctx = SparkContext._active_spark_context\n self._ocvTypes = dict(ctx._jvm.org.apache.spark.ml.image.ImageSchema.javaOcvTypes())\n return self._ocvTypes" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns the schema for the image column.\n\n :return: a :class:`StructType` for image column,\n ``struct``.\n\n .. versionadded:: 2.4.0", "output": "def columnSchema(self):\n \"\"\"\n Returns the schema for the image column.\n\n :return: a :class:`StructType` for image column,\n ``struct``.\n\n .. versionadded:: 2.4.0\n \"\"\"\n\n if self._columnSchema is None:\n ctx = SparkContext._active_spark_context\n jschema = ctx._jvm.org.apache.spark.ml.image.ImageSchema.columnSchema()\n self._columnSchema = _parse_datatype_json_string(jschema.json())\n return self._columnSchema" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns field names of image columns.\n\n :return: a list of field names.\n\n .. versionadded:: 2.3.0", "output": "def imageFields(self):\n \"\"\"\n Returns field names of image columns.\n\n :return: a list of field names.\n\n .. versionadded:: 2.3.0\n \"\"\"\n\n if self._imageFields is None:\n ctx = SparkContext._active_spark_context\n self._imageFields = list(ctx._jvm.org.apache.spark.ml.image.ImageSchema.imageFields())\n return self._imageFields" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns the name of undefined image type for the invalid image.\n\n .. versionadded:: 2.3.0", "output": "def undefinedImageType(self):\n \"\"\"\n Returns the name of undefined image type for the invalid image.\n\n .. versionadded:: 2.3.0\n \"\"\"\n\n if self._undefinedImageType is None:\n ctx = SparkContext._active_spark_context\n self._undefinedImageType = \\\n ctx._jvm.org.apache.spark.ml.image.ImageSchema.undefinedImageType()\n return self._undefinedImageType" }, { "instruction": "Write or improve a Python function based on this description:\n\nConverts an image to an array with metadata.\n\n :param `Row` image: A row that contains the image to be converted. It should\n have the attributes specified in `ImageSchema.imageSchema`.\n :return: a `numpy.ndarray` that is an image.\n\n .. versionadded:: 2.3.0", "output": "def toNDArray(self, image):\n \"\"\"\n Converts an image to an array with metadata.\n\n :param `Row` image: A row that contains the image to be converted. It should\n have the attributes specified in `ImageSchema.imageSchema`.\n :return: a `numpy.ndarray` that is an image.\n\n .. versionadded:: 2.3.0\n \"\"\"\n\n if not isinstance(image, Row):\n raise TypeError(\n \"image argument should be pyspark.sql.types.Row; however, \"\n \"it got [%s].\" % type(image))\n\n if any(not hasattr(image, f) for f in self.imageFields):\n raise ValueError(\n \"image argument should have attributes specified in \"\n \"ImageSchema.imageSchema [%s].\" % \", \".join(self.imageFields))\n\n height = image.height\n width = image.width\n nChannels = image.nChannels\n return np.ndarray(\n shape=(height, width, nChannels),\n dtype=np.uint8,\n buffer=image.data,\n strides=(width * nChannels, nChannels, 1))" }, { "instruction": "Write or improve a Python function based on this description:\n\nConverts an array with metadata to a two-dimensional image.\n\n :param `numpy.ndarray` array: The array to convert to image.\n :param str origin: Path to the image, optional.\n :return: a :class:`Row` that is a two dimensional image.\n\n .. versionadded:: 2.3.0", "output": "def toImage(self, array, origin=\"\"):\n \"\"\"\n Converts an array with metadata to a two-dimensional image.\n\n :param `numpy.ndarray` array: The array to convert to image.\n :param str origin: Path to the image, optional.\n :return: a :class:`Row` that is a two dimensional image.\n\n .. versionadded:: 2.3.0\n \"\"\"\n\n if not isinstance(array, np.ndarray):\n raise TypeError(\n \"array argument should be numpy.ndarray; however, it got [%s].\" % type(array))\n\n if array.ndim != 3:\n raise ValueError(\"Invalid array shape\")\n\n height, width, nChannels = array.shape\n ocvTypes = ImageSchema.ocvTypes\n if nChannels == 1:\n mode = ocvTypes[\"CV_8UC1\"]\n elif nChannels == 3:\n mode = ocvTypes[\"CV_8UC3\"]\n elif nChannels == 4:\n mode = ocvTypes[\"CV_8UC4\"]\n else:\n raise ValueError(\"Invalid number of channels\")\n\n # Running `bytearray(numpy.array([1]))` fails in specific Python versions\n # with a specific Numpy version, for example in Python 3.6.0 and NumPy 1.13.3.\n # Here, it avoids it by converting it to bytes.\n if LooseVersion(np.__version__) >= LooseVersion('1.9'):\n data = bytearray(array.astype(dtype=np.uint8).ravel().tobytes())\n else:\n # Numpy prior to 1.9 don't have `tobytes` method.\n data = bytearray(array.astype(dtype=np.uint8).ravel())\n\n # Creating new Row with _create_row(), because Row(name = value, ... )\n # orders fields by name, which conflicts with expected schema order\n # when the new DataFrame is created by UDF\n return _create_row(self.imageFields,\n [origin, height, width, nChannels, mode, data])" }, { "instruction": "Write or improve a Python function based on this description:\n\nReads the directory of images from the local or remote source.\n\n .. note:: If multiple jobs are run in parallel with different sampleRatio or recursive flag,\n there may be a race condition where one job overwrites the hadoop configs of another.\n\n .. note:: If sample ratio is less than 1, sampling uses a PathFilter that is efficient but\n potentially non-deterministic.\n\n .. note:: Deprecated in 2.4.0. Use `spark.read.format(\"image\").load(path)` instead and\n this `readImages` will be removed in 3.0.0.\n\n :param str path: Path to the image directory.\n :param bool recursive: Recursive search flag.\n :param int numPartitions: Number of DataFrame partitions.\n :param bool dropImageFailures: Drop the files that are not valid images.\n :param float sampleRatio: Fraction of the images loaded.\n :param int seed: Random number seed.\n :return: a :class:`DataFrame` with a single column of \"images\",\n see ImageSchema for details.\n\n >>> df = ImageSchema.readImages('data/mllib/images/origin/kittens', recursive=True)\n >>> df.count()\n 5\n\n .. versionadded:: 2.3.0", "output": "def readImages(self, path, recursive=False, numPartitions=-1,\n dropImageFailures=False, sampleRatio=1.0, seed=0):\n \"\"\"\n Reads the directory of images from the local or remote source.\n\n .. note:: If multiple jobs are run in parallel with different sampleRatio or recursive flag,\n there may be a race condition where one job overwrites the hadoop configs of another.\n\n .. note:: If sample ratio is less than 1, sampling uses a PathFilter that is efficient but\n potentially non-deterministic.\n\n .. note:: Deprecated in 2.4.0. Use `spark.read.format(\"image\").load(path)` instead and\n this `readImages` will be removed in 3.0.0.\n\n :param str path: Path to the image directory.\n :param bool recursive: Recursive search flag.\n :param int numPartitions: Number of DataFrame partitions.\n :param bool dropImageFailures: Drop the files that are not valid images.\n :param float sampleRatio: Fraction of the images loaded.\n :param int seed: Random number seed.\n :return: a :class:`DataFrame` with a single column of \"images\",\n see ImageSchema for details.\n\n >>> df = ImageSchema.readImages('data/mllib/images/origin/kittens', recursive=True)\n >>> df.count()\n 5\n\n .. versionadded:: 2.3.0\n \"\"\"\n warnings.warn(\"`ImageSchema.readImage` is deprecated. \" +\n \"Use `spark.read.format(\\\"image\\\").load(path)` instead.\", DeprecationWarning)\n spark = SparkSession.builder.getOrCreate()\n image_schema = spark._jvm.org.apache.spark.ml.image.ImageSchema\n jsession = spark._jsparkSession\n jresult = image_schema.readImages(path, jsession, recursive, numPartitions,\n dropImageFailures, float(sampleRatio), seed)\n return DataFrame(jresult, spark._wrapped)" }, { "instruction": "Write or improve a Python function based on this description:\n\nConstruct this object from given Java classname and arguments", "output": "def _create_from_java_class(cls, java_class, *args):\n \"\"\"\n Construct this object from given Java classname and arguments\n \"\"\"\n java_obj = JavaWrapper._new_java_obj(java_class, *args)\n return cls(java_obj)" }, { "instruction": "Write or improve a Python function based on this description:\n\nCreate a Java array of given java_class type. Useful for\n calling a method with a Scala Array from Python with Py4J.\n If the param pylist is a 2D array, then a 2D java array will be returned.\n The returned 2D java array is a square, non-jagged 2D array that is big\n enough for all elements. The empty slots in the inner Java arrays will\n be filled with null to make the non-jagged 2D array.\n\n :param pylist:\n Python list to convert to a Java Array.\n :param java_class:\n Java class to specify the type of Array. Should be in the\n form of sc._gateway.jvm.* (sc is a valid Spark Context).\n :return:\n Java Array of converted pylist.\n\n Example primitive Java classes:\n - basestring -> sc._gateway.jvm.java.lang.String\n - int -> sc._gateway.jvm.java.lang.Integer\n - float -> sc._gateway.jvm.java.lang.Double\n - bool -> sc._gateway.jvm.java.lang.Boolean", "output": "def _new_java_array(pylist, java_class):\n \"\"\"\n Create a Java array of given java_class type. Useful for\n calling a method with a Scala Array from Python with Py4J.\n If the param pylist is a 2D array, then a 2D java array will be returned.\n The returned 2D java array is a square, non-jagged 2D array that is big\n enough for all elements. The empty slots in the inner Java arrays will\n be filled with null to make the non-jagged 2D array.\n\n :param pylist:\n Python list to convert to a Java Array.\n :param java_class:\n Java class to specify the type of Array. Should be in the\n form of sc._gateway.jvm.* (sc is a valid Spark Context).\n :return:\n Java Array of converted pylist.\n\n Example primitive Java classes:\n - basestring -> sc._gateway.jvm.java.lang.String\n - int -> sc._gateway.jvm.java.lang.Integer\n - float -> sc._gateway.jvm.java.lang.Double\n - bool -> sc._gateway.jvm.java.lang.Boolean\n \"\"\"\n sc = SparkContext._active_spark_context\n java_array = None\n if len(pylist) > 0 and isinstance(pylist[0], list):\n # If pylist is a 2D array, then a 2D java array will be created.\n # The 2D array is a square, non-jagged 2D array that is big enough for all elements.\n inner_array_length = 0\n for i in xrange(len(pylist)):\n inner_array_length = max(inner_array_length, len(pylist[i]))\n java_array = sc._gateway.new_array(java_class, len(pylist), inner_array_length)\n for i in xrange(len(pylist)):\n for j in xrange(len(pylist[i])):\n java_array[i][j] = pylist[i][j]\n else:\n java_array = sc._gateway.new_array(java_class, len(pylist))\n for i in xrange(len(pylist)):\n java_array[i] = pylist[i]\n return java_array" }, { "instruction": "Write or improve a Python function based on this description:\n\n>>> _convert_epytext(\"L{A}\")\n :class:`A`", "output": "def _convert_epytext(line):\n \"\"\"\n >>> _convert_epytext(\"L{A}\")\n :class:`A`\n \"\"\"\n line = line.replace('@', ':')\n for p, sub in RULES:\n line = re.sub(p, sub, line)\n return line" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn string prefix-time(.suffix)\n\n >>> rddToFileName(\"spark\", None, 12345678910)\n 'spark-12345678910'\n >>> rddToFileName(\"spark\", \"tmp\", 12345678910)\n 'spark-12345678910.tmp'", "output": "def rddToFileName(prefix, suffix, timestamp):\n \"\"\"\n Return string prefix-time(.suffix)\n\n >>> rddToFileName(\"spark\", None, 12345678910)\n 'spark-12345678910'\n >>> rddToFileName(\"spark\", \"tmp\", 12345678910)\n 'spark-12345678910.tmp'\n \"\"\"\n if isinstance(timestamp, datetime):\n seconds = time.mktime(timestamp.timetuple())\n timestamp = int(seconds * 1000) + timestamp.microsecond // 1000\n if suffix is None:\n return prefix + \"-\" + str(timestamp)\n else:\n return prefix + \"-\" + str(timestamp) + \".\" + suffix" }, { "instruction": "Write or improve a Python function based on this description:\n\nAdd a profiler for RDD `id`", "output": "def add_profiler(self, id, profiler):\n \"\"\" Add a profiler for RDD `id` \"\"\"\n if not self.profilers:\n if self.profile_dump_path:\n atexit.register(self.dump_profiles, self.profile_dump_path)\n else:\n atexit.register(self.show_profiles)\n\n self.profilers.append([id, profiler, False])" }, { "instruction": "Write or improve a Python function based on this description:\n\nDump the profile stats into directory `path`", "output": "def dump_profiles(self, path):\n \"\"\" Dump the profile stats into directory `path` \"\"\"\n for id, profiler, _ in self.profilers:\n profiler.dump(id, path)\n self.profilers = []" }, { "instruction": "Write or improve a Python function based on this description:\n\nPrint the profile stats to stdout", "output": "def show_profiles(self):\n \"\"\" Print the profile stats to stdout \"\"\"\n for i, (id, profiler, showed) in enumerate(self.profilers):\n if not showed and profiler:\n profiler.show(id)\n # mark it as showed\n self.profilers[i][2] = True" }, { "instruction": "Write or improve a Python function based on this description:\n\nPrint the profile stats to stdout, id is the RDD id", "output": "def show(self, id):\n \"\"\" Print the profile stats to stdout, id is the RDD id \"\"\"\n stats = self.stats()\n if stats:\n print(\"=\" * 60)\n print(\"Profile of RDD\" % id)\n print(\"=\" * 60)\n stats.sort_stats(\"time\", \"cumulative\").print_stats()" }, { "instruction": "Write or improve a Python function based on this description:\n\nDump the profile into path, id is the RDD id", "output": "def dump(self, id, path):\n \"\"\" Dump the profile into path, id is the RDD id \"\"\"\n if not os.path.exists(path):\n os.makedirs(path)\n stats = self.stats()\n if stats:\n p = os.path.join(path, \"rdd_%d.pstats\" % id)\n stats.dump_stats(p)" }, { "instruction": "Write or improve a Python function based on this description:\n\nRuns and profiles the method to_profile passed in. A profile object is returned.", "output": "def profile(self, func):\n \"\"\" Runs and profiles the method to_profile passed in. A profile object is returned. \"\"\"\n pr = cProfile.Profile()\n pr.runcall(func)\n st = pstats.Stats(pr)\n st.stream = None # make it picklable\n st.strip_dirs()\n\n # Adds a new profile to the existing accumulated value\n self._accumulator.add(st)" }, { "instruction": "Write or improve a Python function based on this description:\n\nGet the existing SQLContext or create a new one with given SparkContext.\n\n :param sc: SparkContext", "output": "def getOrCreate(cls, sc):\n \"\"\"\n Get the existing SQLContext or create a new one with given SparkContext.\n\n :param sc: SparkContext\n \"\"\"\n if cls._instantiatedContext is None:\n jsqlContext = sc._jvm.SQLContext.getOrCreate(sc._jsc.sc())\n sparkSession = SparkSession(sc, jsqlContext.sparkSession())\n cls(sc, sparkSession, jsqlContext)\n return cls._instantiatedContext" }, { "instruction": "Write or improve a Python function based on this description:\n\nSets the given Spark SQL configuration property.", "output": "def setConf(self, key, value):\n \"\"\"Sets the given Spark SQL configuration property.\n \"\"\"\n self.sparkSession.conf.set(key, value)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns the value of Spark SQL configuration property for the given key.\n\n If the key is not set and defaultValue is set, return\n defaultValue. If the key is not set and defaultValue is not set, return\n the system default value.\n\n >>> sqlContext.getConf(\"spark.sql.shuffle.partitions\")\n u'200'\n >>> sqlContext.getConf(\"spark.sql.shuffle.partitions\", u\"10\")\n u'10'\n >>> sqlContext.setConf(\"spark.sql.shuffle.partitions\", u\"50\")\n >>> sqlContext.getConf(\"spark.sql.shuffle.partitions\", u\"10\")\n u'50'", "output": "def getConf(self, key, defaultValue=_NoValue):\n \"\"\"Returns the value of Spark SQL configuration property for the given key.\n\n If the key is not set and defaultValue is set, return\n defaultValue. If the key is not set and defaultValue is not set, return\n the system default value.\n\n >>> sqlContext.getConf(\"spark.sql.shuffle.partitions\")\n u'200'\n >>> sqlContext.getConf(\"spark.sql.shuffle.partitions\", u\"10\")\n u'10'\n >>> sqlContext.setConf(\"spark.sql.shuffle.partitions\", u\"50\")\n >>> sqlContext.getConf(\"spark.sql.shuffle.partitions\", u\"10\")\n u'50'\n \"\"\"\n return self.sparkSession.conf.get(key, defaultValue)" }, { "instruction": "Write or improve a Python function based on this description:\n\nCreate a :class:`DataFrame` with single :class:`pyspark.sql.types.LongType` column named\n ``id``, containing elements in a range from ``start`` to ``end`` (exclusive) with\n step value ``step``.\n\n :param start: the start value\n :param end: the end value (exclusive)\n :param step: the incremental step (default: 1)\n :param numPartitions: the number of partitions of the DataFrame\n :return: :class:`DataFrame`\n\n >>> sqlContext.range(1, 7, 2).collect()\n [Row(id=1), Row(id=3), Row(id=5)]\n\n If only one argument is specified, it will be used as the end value.\n\n >>> sqlContext.range(3).collect()\n [Row(id=0), Row(id=1), Row(id=2)]", "output": "def range(self, start, end=None, step=1, numPartitions=None):\n \"\"\"\n Create a :class:`DataFrame` with single :class:`pyspark.sql.types.LongType` column named\n ``id``, containing elements in a range from ``start`` to ``end`` (exclusive) with\n step value ``step``.\n\n :param start: the start value\n :param end: the end value (exclusive)\n :param step: the incremental step (default: 1)\n :param numPartitions: the number of partitions of the DataFrame\n :return: :class:`DataFrame`\n\n >>> sqlContext.range(1, 7, 2).collect()\n [Row(id=1), Row(id=3), Row(id=5)]\n\n If only one argument is specified, it will be used as the end value.\n\n >>> sqlContext.range(3).collect()\n [Row(id=0), Row(id=1), Row(id=2)]\n \"\"\"\n return self.sparkSession.range(start, end, step, numPartitions)" }, { "instruction": "Write or improve a Python function based on this description:\n\nAn alias for :func:`spark.udf.register`.\n See :meth:`pyspark.sql.UDFRegistration.register`.\n\n .. note:: Deprecated in 2.3.0. Use :func:`spark.udf.register` instead.", "output": "def registerFunction(self, name, f, returnType=None):\n \"\"\"An alias for :func:`spark.udf.register`.\n See :meth:`pyspark.sql.UDFRegistration.register`.\n\n .. note:: Deprecated in 2.3.0. Use :func:`spark.udf.register` instead.\n \"\"\"\n warnings.warn(\n \"Deprecated in 2.3.0. Use spark.udf.register instead.\",\n DeprecationWarning)\n return self.sparkSession.udf.register(name, f, returnType)" }, { "instruction": "Write or improve a Python function based on this description:\n\nAn alias for :func:`spark.udf.registerJavaFunction`.\n See :meth:`pyspark.sql.UDFRegistration.registerJavaFunction`.\n\n .. note:: Deprecated in 2.3.0. Use :func:`spark.udf.registerJavaFunction` instead.", "output": "def registerJavaFunction(self, name, javaClassName, returnType=None):\n \"\"\"An alias for :func:`spark.udf.registerJavaFunction`.\n See :meth:`pyspark.sql.UDFRegistration.registerJavaFunction`.\n\n .. note:: Deprecated in 2.3.0. Use :func:`spark.udf.registerJavaFunction` instead.\n \"\"\"\n warnings.warn(\n \"Deprecated in 2.3.0. Use spark.udf.registerJavaFunction instead.\",\n DeprecationWarning)\n return self.sparkSession.udf.registerJavaFunction(name, javaClassName, returnType)" }, { "instruction": "Write or improve a Python function based on this description:\n\nCreates a :class:`DataFrame` from an :class:`RDD`, a list or a :class:`pandas.DataFrame`.\n\n When ``schema`` is a list of column names, the type of each column\n will be inferred from ``data``.\n\n When ``schema`` is ``None``, it will try to infer the schema (column names and types)\n from ``data``, which should be an RDD of :class:`Row`,\n or :class:`namedtuple`, or :class:`dict`.\n\n When ``schema`` is :class:`pyspark.sql.types.DataType` or a datatype string it must match\n the real data, or an exception will be thrown at runtime. If the given schema is not\n :class:`pyspark.sql.types.StructType`, it will be wrapped into a\n :class:`pyspark.sql.types.StructType` as its only field, and the field name will be \"value\",\n each record will also be wrapped into a tuple, which can be converted to row later.\n\n If schema inference is needed, ``samplingRatio`` is used to determined the ratio of\n rows used for schema inference. The first row will be used if ``samplingRatio`` is ``None``.\n\n :param data: an RDD of any kind of SQL data representation(e.g. :class:`Row`,\n :class:`tuple`, ``int``, ``boolean``, etc.), or :class:`list`, or\n :class:`pandas.DataFrame`.\n :param schema: a :class:`pyspark.sql.types.DataType` or a datatype string or a list of\n column names, default is None. The data type string format equals to\n :class:`pyspark.sql.types.DataType.simpleString`, except that top level struct type can\n omit the ``struct<>`` and atomic types use ``typeName()`` as their format, e.g. use\n ``byte`` instead of ``tinyint`` for :class:`pyspark.sql.types.ByteType`.\n We can also use ``int`` as a short name for :class:`pyspark.sql.types.IntegerType`.\n :param samplingRatio: the sample ratio of rows used for inferring\n :param verifySchema: verify data types of every row against schema.\n :return: :class:`DataFrame`\n\n .. versionchanged:: 2.0\n The ``schema`` parameter can be a :class:`pyspark.sql.types.DataType` or a\n datatype string after 2.0.\n If it's not a :class:`pyspark.sql.types.StructType`, it will be wrapped into a\n :class:`pyspark.sql.types.StructType` and each record will also be wrapped into a tuple.\n\n .. versionchanged:: 2.1\n Added verifySchema.\n\n >>> l = [('Alice', 1)]\n >>> sqlContext.createDataFrame(l).collect()\n [Row(_1=u'Alice', _2=1)]\n >>> sqlContext.createDataFrame(l, ['name', 'age']).collect()\n [Row(name=u'Alice', age=1)]\n\n >>> d = [{'name': 'Alice', 'age': 1}]\n >>> sqlContext.createDataFrame(d).collect()\n [Row(age=1, name=u'Alice')]\n\n >>> rdd = sc.parallelize(l)\n >>> sqlContext.createDataFrame(rdd).collect()\n [Row(_1=u'Alice', _2=1)]\n >>> df = sqlContext.createDataFrame(rdd, ['name', 'age'])\n >>> df.collect()\n [Row(name=u'Alice', age=1)]\n\n >>> from pyspark.sql import Row\n >>> Person = Row('name', 'age')\n >>> person = rdd.map(lambda r: Person(*r))\n >>> df2 = sqlContext.createDataFrame(person)\n >>> df2.collect()\n [Row(name=u'Alice', age=1)]\n\n >>> from pyspark.sql.types import *\n >>> schema = StructType([\n ... StructField(\"name\", StringType(), True),\n ... StructField(\"age\", IntegerType(), True)])\n >>> df3 = sqlContext.createDataFrame(rdd, schema)\n >>> df3.collect()\n [Row(name=u'Alice', age=1)]\n\n >>> sqlContext.createDataFrame(df.toPandas()).collect() # doctest: +SKIP\n [Row(name=u'Alice', age=1)]\n >>> sqlContext.createDataFrame(pandas.DataFrame([[1, 2]])).collect() # doctest: +SKIP\n [Row(0=1, 1=2)]\n\n >>> sqlContext.createDataFrame(rdd, \"a: string, b: int\").collect()\n [Row(a=u'Alice', b=1)]\n >>> rdd = rdd.map(lambda row: row[1])\n >>> sqlContext.createDataFrame(rdd, \"int\").collect()\n [Row(value=1)]\n >>> sqlContext.createDataFrame(rdd, \"boolean\").collect() # doctest: +IGNORE_EXCEPTION_DETAIL\n Traceback (most recent call last):\n ...\n Py4JJavaError: ...", "output": "def createDataFrame(self, data, schema=None, samplingRatio=None, verifySchema=True):\n \"\"\"\n Creates a :class:`DataFrame` from an :class:`RDD`, a list or a :class:`pandas.DataFrame`.\n\n When ``schema`` is a list of column names, the type of each column\n will be inferred from ``data``.\n\n When ``schema`` is ``None``, it will try to infer the schema (column names and types)\n from ``data``, which should be an RDD of :class:`Row`,\n or :class:`namedtuple`, or :class:`dict`.\n\n When ``schema`` is :class:`pyspark.sql.types.DataType` or a datatype string it must match\n the real data, or an exception will be thrown at runtime. If the given schema is not\n :class:`pyspark.sql.types.StructType`, it will be wrapped into a\n :class:`pyspark.sql.types.StructType` as its only field, and the field name will be \"value\",\n each record will also be wrapped into a tuple, which can be converted to row later.\n\n If schema inference is needed, ``samplingRatio`` is used to determined the ratio of\n rows used for schema inference. The first row will be used if ``samplingRatio`` is ``None``.\n\n :param data: an RDD of any kind of SQL data representation(e.g. :class:`Row`,\n :class:`tuple`, ``int``, ``boolean``, etc.), or :class:`list`, or\n :class:`pandas.DataFrame`.\n :param schema: a :class:`pyspark.sql.types.DataType` or a datatype string or a list of\n column names, default is None. The data type string format equals to\n :class:`pyspark.sql.types.DataType.simpleString`, except that top level struct type can\n omit the ``struct<>`` and atomic types use ``typeName()`` as their format, e.g. use\n ``byte`` instead of ``tinyint`` for :class:`pyspark.sql.types.ByteType`.\n We can also use ``int`` as a short name for :class:`pyspark.sql.types.IntegerType`.\n :param samplingRatio: the sample ratio of rows used for inferring\n :param verifySchema: verify data types of every row against schema.\n :return: :class:`DataFrame`\n\n .. versionchanged:: 2.0\n The ``schema`` parameter can be a :class:`pyspark.sql.types.DataType` or a\n datatype string after 2.0.\n If it's not a :class:`pyspark.sql.types.StructType`, it will be wrapped into a\n :class:`pyspark.sql.types.StructType` and each record will also be wrapped into a tuple.\n\n .. versionchanged:: 2.1\n Added verifySchema.\n\n >>> l = [('Alice', 1)]\n >>> sqlContext.createDataFrame(l).collect()\n [Row(_1=u'Alice', _2=1)]\n >>> sqlContext.createDataFrame(l, ['name', 'age']).collect()\n [Row(name=u'Alice', age=1)]\n\n >>> d = [{'name': 'Alice', 'age': 1}]\n >>> sqlContext.createDataFrame(d).collect()\n [Row(age=1, name=u'Alice')]\n\n >>> rdd = sc.parallelize(l)\n >>> sqlContext.createDataFrame(rdd).collect()\n [Row(_1=u'Alice', _2=1)]\n >>> df = sqlContext.createDataFrame(rdd, ['name', 'age'])\n >>> df.collect()\n [Row(name=u'Alice', age=1)]\n\n >>> from pyspark.sql import Row\n >>> Person = Row('name', 'age')\n >>> person = rdd.map(lambda r: Person(*r))\n >>> df2 = sqlContext.createDataFrame(person)\n >>> df2.collect()\n [Row(name=u'Alice', age=1)]\n\n >>> from pyspark.sql.types import *\n >>> schema = StructType([\n ... StructField(\"name\", StringType(), True),\n ... StructField(\"age\", IntegerType(), True)])\n >>> df3 = sqlContext.createDataFrame(rdd, schema)\n >>> df3.collect()\n [Row(name=u'Alice', age=1)]\n\n >>> sqlContext.createDataFrame(df.toPandas()).collect() # doctest: +SKIP\n [Row(name=u'Alice', age=1)]\n >>> sqlContext.createDataFrame(pandas.DataFrame([[1, 2]])).collect() # doctest: +SKIP\n [Row(0=1, 1=2)]\n\n >>> sqlContext.createDataFrame(rdd, \"a: string, b: int\").collect()\n [Row(a=u'Alice', b=1)]\n >>> rdd = rdd.map(lambda row: row[1])\n >>> sqlContext.createDataFrame(rdd, \"int\").collect()\n [Row(value=1)]\n >>> sqlContext.createDataFrame(rdd, \"boolean\").collect() # doctest: +IGNORE_EXCEPTION_DETAIL\n Traceback (most recent call last):\n ...\n Py4JJavaError: ...\n \"\"\"\n return self.sparkSession.createDataFrame(data, schema, samplingRatio, verifySchema)" }, { "instruction": "Write or improve a Python function based on this description:\n\nCreates an external table based on the dataset in a data source.\n\n It returns the DataFrame associated with the external table.\n\n The data source is specified by the ``source`` and a set of ``options``.\n If ``source`` is not specified, the default data source configured by\n ``spark.sql.sources.default`` will be used.\n\n Optionally, a schema can be provided as the schema of the returned :class:`DataFrame` and\n created external table.\n\n :return: :class:`DataFrame`", "output": "def createExternalTable(self, tableName, path=None, source=None, schema=None, **options):\n \"\"\"Creates an external table based on the dataset in a data source.\n\n It returns the DataFrame associated with the external table.\n\n The data source is specified by the ``source`` and a set of ``options``.\n If ``source`` is not specified, the default data source configured by\n ``spark.sql.sources.default`` will be used.\n\n Optionally, a schema can be provided as the schema of the returned :class:`DataFrame` and\n created external table.\n\n :return: :class:`DataFrame`\n \"\"\"\n return self.sparkSession.catalog.createExternalTable(\n tableName, path, source, schema, **options)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns a :class:`DataFrame` containing names of tables in the given database.\n\n If ``dbName`` is not specified, the current database will be used.\n\n The returned DataFrame has two columns: ``tableName`` and ``isTemporary``\n (a column with :class:`BooleanType` indicating if a table is a temporary one or not).\n\n :param dbName: string, name of the database to use.\n :return: :class:`DataFrame`\n\n >>> sqlContext.registerDataFrameAsTable(df, \"table1\")\n >>> df2 = sqlContext.tables()\n >>> df2.filter(\"tableName = 'table1'\").first()\n Row(database=u'', tableName=u'table1', isTemporary=True)", "output": "def tables(self, dbName=None):\n \"\"\"Returns a :class:`DataFrame` containing names of tables in the given database.\n\n If ``dbName`` is not specified, the current database will be used.\n\n The returned DataFrame has two columns: ``tableName`` and ``isTemporary``\n (a column with :class:`BooleanType` indicating if a table is a temporary one or not).\n\n :param dbName: string, name of the database to use.\n :return: :class:`DataFrame`\n\n >>> sqlContext.registerDataFrameAsTable(df, \"table1\")\n >>> df2 = sqlContext.tables()\n >>> df2.filter(\"tableName = 'table1'\").first()\n Row(database=u'', tableName=u'table1', isTemporary=True)\n \"\"\"\n if dbName is None:\n return DataFrame(self._ssql_ctx.tables(), self)\n else:\n return DataFrame(self._ssql_ctx.tables(dbName), self)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns a list of names of tables in the database ``dbName``.\n\n :param dbName: string, name of the database to use. Default to the current database.\n :return: list of table names, in string\n\n >>> sqlContext.registerDataFrameAsTable(df, \"table1\")\n >>> \"table1\" in sqlContext.tableNames()\n True\n >>> \"table1\" in sqlContext.tableNames(\"default\")\n True", "output": "def tableNames(self, dbName=None):\n \"\"\"Returns a list of names of tables in the database ``dbName``.\n\n :param dbName: string, name of the database to use. Default to the current database.\n :return: list of table names, in string\n\n >>> sqlContext.registerDataFrameAsTable(df, \"table1\")\n >>> \"table1\" in sqlContext.tableNames()\n True\n >>> \"table1\" in sqlContext.tableNames(\"default\")\n True\n \"\"\"\n if dbName is None:\n return [name for name in self._ssql_ctx.tableNames()]\n else:\n return [name for name in self._ssql_ctx.tableNames(dbName)]" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns a :class:`StreamingQueryManager` that allows managing all the\n :class:`StreamingQuery` StreamingQueries active on `this` context.\n\n .. note:: Evolving.", "output": "def streams(self):\n \"\"\"Returns a :class:`StreamingQueryManager` that allows managing all the\n :class:`StreamingQuery` StreamingQueries active on `this` context.\n\n .. note:: Evolving.\n \"\"\"\n from pyspark.sql.streaming import StreamingQueryManager\n return StreamingQueryManager(self._ssql_ctx.streams())" }, { "instruction": "Write or improve a Python function based on this description:\n\nConverts a binary column of avro format into its corresponding catalyst value. The specified\n schema must match the read data, otherwise the behavior is undefined: it may fail or return\n arbitrary result.\n\n Note: Avro is built-in but external data source module since Spark 2.4. Please deploy the\n application as per the deployment section of \"Apache Avro Data Source Guide\".\n\n :param data: the binary column.\n :param jsonFormatSchema: the avro schema in JSON string format.\n :param options: options to control how the Avro record is parsed.\n\n >>> from pyspark.sql import Row\n >>> from pyspark.sql.avro.functions import from_avro, to_avro\n >>> data = [(1, Row(name='Alice', age=2))]\n >>> df = spark.createDataFrame(data, (\"key\", \"value\"))\n >>> avroDf = df.select(to_avro(df.value).alias(\"avro\"))\n >>> avroDf.collect()\n [Row(avro=bytearray(b'\\\\x00\\\\x00\\\\x04\\\\x00\\\\nAlice'))]\n >>> jsonFormatSchema = '''{\"type\":\"record\",\"name\":\"topLevelRecord\",\"fields\":\n ... [{\"name\":\"avro\",\"type\":[{\"type\":\"record\",\"name\":\"value\",\"namespace\":\"topLevelRecord\",\n ... \"fields\":[{\"name\":\"age\",\"type\":[\"long\",\"null\"]},\n ... {\"name\":\"name\",\"type\":[\"string\",\"null\"]}]},\"null\"]}]}'''\n >>> avroDf.select(from_avro(avroDf.avro, jsonFormatSchema).alias(\"value\")).collect()\n [Row(value=Row(avro=Row(age=2, name=u'Alice')))]", "output": "def from_avro(data, jsonFormatSchema, options={}):\n \"\"\"\n Converts a binary column of avro format into its corresponding catalyst value. The specified\n schema must match the read data, otherwise the behavior is undefined: it may fail or return\n arbitrary result.\n\n Note: Avro is built-in but external data source module since Spark 2.4. Please deploy the\n application as per the deployment section of \"Apache Avro Data Source Guide\".\n\n :param data: the binary column.\n :param jsonFormatSchema: the avro schema in JSON string format.\n :param options: options to control how the Avro record is parsed.\n\n >>> from pyspark.sql import Row\n >>> from pyspark.sql.avro.functions import from_avro, to_avro\n >>> data = [(1, Row(name='Alice', age=2))]\n >>> df = spark.createDataFrame(data, (\"key\", \"value\"))\n >>> avroDf = df.select(to_avro(df.value).alias(\"avro\"))\n >>> avroDf.collect()\n [Row(avro=bytearray(b'\\\\x00\\\\x00\\\\x04\\\\x00\\\\nAlice'))]\n >>> jsonFormatSchema = '''{\"type\":\"record\",\"name\":\"topLevelRecord\",\"fields\":\n ... [{\"name\":\"avro\",\"type\":[{\"type\":\"record\",\"name\":\"value\",\"namespace\":\"topLevelRecord\",\n ... \"fields\":[{\"name\":\"age\",\"type\":[\"long\",\"null\"]},\n ... {\"name\":\"name\",\"type\":[\"string\",\"null\"]}]},\"null\"]}]}'''\n >>> avroDf.select(from_avro(avroDf.avro, jsonFormatSchema).alias(\"value\")).collect()\n [Row(value=Row(avro=Row(age=2, name=u'Alice')))]\n \"\"\"\n\n sc = SparkContext._active_spark_context\n try:\n jc = sc._jvm.org.apache.spark.sql.avro.functions.from_avro(\n _to_java_column(data), jsonFormatSchema, options)\n except TypeError as e:\n if str(e) == \"'JavaPackage' object is not callable\":\n _print_missing_jar(\"Avro\", \"avro\", \"avro\", sc.version)\n raise\n return Column(jc)" }, { "instruction": "Write or improve a Python function based on this description:\n\nGet the absolute path of a file added through C{SparkContext.addFile()}.", "output": "def get(cls, filename):\n \"\"\"\n Get the absolute path of a file added through C{SparkContext.addFile()}.\n \"\"\"\n path = os.path.join(SparkFiles.getRootDirectory(), filename)\n return os.path.abspath(path)" }, { "instruction": "Write or improve a Python function based on this description:\n\nGet the root directory that contains files added through\n C{SparkContext.addFile()}.", "output": "def getRootDirectory(cls):\n \"\"\"\n Get the root directory that contains files added through\n C{SparkContext.addFile()}.\n \"\"\"\n if cls._is_running_on_worker:\n return cls._root_directory\n else:\n # This will have to change if we support multiple SparkContexts:\n return cls._sc._jvm.org.apache.spark.SparkFiles.getRootDirectory()" }, { "instruction": "Write or improve a Python function based on this description:\n\nGets summary (e.g. accuracy/precision/recall, objective history, total iterations) of model\n trained on the training set. An exception is thrown if `trainingSummary is None`.", "output": "def summary(self):\n \"\"\"\n Gets summary (e.g. accuracy/precision/recall, objective history, total iterations) of model\n trained on the training set. An exception is thrown if `trainingSummary is None`.\n \"\"\"\n if self.hasSummary:\n if self.numClasses <= 2:\n return BinaryLogisticRegressionTrainingSummary(super(LogisticRegressionModel,\n self).summary)\n else:\n return LogisticRegressionTrainingSummary(super(LogisticRegressionModel,\n self).summary)\n else:\n raise RuntimeError(\"No training summary available for this %s\" %\n self.__class__.__name__)" }, { "instruction": "Write or improve a Python function based on this description:\n\nEvaluates the model on a test dataset.\n\n :param dataset:\n Test dataset to evaluate model on, where dataset is an\n instance of :py:class:`pyspark.sql.DataFrame`", "output": "def evaluate(self, dataset):\n \"\"\"\n Evaluates the model on a test dataset.\n\n :param dataset:\n Test dataset to evaluate model on, where dataset is an\n instance of :py:class:`pyspark.sql.DataFrame`\n \"\"\"\n if not isinstance(dataset, DataFrame):\n raise ValueError(\"dataset must be a DataFrame but got %s.\" % type(dataset))\n java_blr_summary = self._call_java(\"evaluate\", dataset)\n return BinaryLogisticRegressionSummary(java_blr_summary)" }, { "instruction": "Write or improve a Python function based on this description:\n\nCreates a copy of this instance with a randomly generated uid\n and some extra params. This creates a deep copy of the embedded paramMap,\n and copies the embedded and extra parameters over.\n\n :param extra: Extra parameters to copy to the new instance\n :return: Copy of this instance", "output": "def copy(self, extra=None):\n \"\"\"\n Creates a copy of this instance with a randomly generated uid\n and some extra params. This creates a deep copy of the embedded paramMap,\n and copies the embedded and extra parameters over.\n\n :param extra: Extra parameters to copy to the new instance\n :return: Copy of this instance\n \"\"\"\n if extra is None:\n extra = dict()\n newModel = Params.copy(self, extra)\n newModel.models = [model.copy(extra) for model in self.models]\n return newModel" }, { "instruction": "Write or improve a Python function based on this description:\n\nGiven a Java OneVsRestModel, create and return a Python wrapper of it.\n Used for ML persistence.", "output": "def _from_java(cls, java_stage):\n \"\"\"\n Given a Java OneVsRestModel, create and return a Python wrapper of it.\n Used for ML persistence.\n \"\"\"\n featuresCol = java_stage.getFeaturesCol()\n labelCol = java_stage.getLabelCol()\n predictionCol = java_stage.getPredictionCol()\n classifier = JavaParams._from_java(java_stage.getClassifier())\n models = [JavaParams._from_java(model) for model in java_stage.models()]\n py_stage = cls(models=models).setPredictionCol(predictionCol).setLabelCol(labelCol)\\\n .setFeaturesCol(featuresCol).setClassifier(classifier)\n py_stage._resetUid(java_stage.uid())\n return py_stage" }, { "instruction": "Write or improve a Python function based on this description:\n\nTransfer this instance to a Java OneVsRestModel. Used for ML persistence.\n\n :return: Java object equivalent to this instance.", "output": "def _to_java(self):\n \"\"\"\n Transfer this instance to a Java OneVsRestModel. Used for ML persistence.\n\n :return: Java object equivalent to this instance.\n \"\"\"\n sc = SparkContext._active_spark_context\n java_models = [model._to_java() for model in self.models]\n java_models_array = JavaWrapper._new_java_array(\n java_models, sc._gateway.jvm.org.apache.spark.ml.classification.ClassificationModel)\n metadata = JavaParams._new_java_obj(\"org.apache.spark.sql.types.Metadata\")\n _java_obj = JavaParams._new_java_obj(\"org.apache.spark.ml.classification.OneVsRestModel\",\n self.uid, metadata.empty(), java_models_array)\n _java_obj.set(\"classifier\", self.getClassifier()._to_java())\n _java_obj.set(\"featuresCol\", self.getFeaturesCol())\n _java_obj.set(\"labelCol\", self.getLabelCol())\n _java_obj.set(\"predictionCol\", self.getPredictionCol())\n return _java_obj" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn the message from an exception as either a str or unicode object. Supports both\n Python 2 and Python 3.\n\n >>> msg = \"Exception message\"\n >>> excp = Exception(msg)\n >>> msg == _exception_message(excp)\n True\n\n >>> msg = u\"unicöde\"\n >>> excp = Exception(msg)\n >>> msg == _exception_message(excp)\n True", "output": "def _exception_message(excp):\n \"\"\"Return the message from an exception as either a str or unicode object. Supports both\n Python 2 and Python 3.\n\n >>> msg = \"Exception message\"\n >>> excp = Exception(msg)\n >>> msg == _exception_message(excp)\n True\n\n >>> msg = u\"unicöde\"\n >>> excp = Exception(msg)\n >>> msg == _exception_message(excp)\n True\n \"\"\"\n if isinstance(excp, Py4JJavaError):\n # 'Py4JJavaError' doesn't contain the stack trace available on the Java side in 'message'\n # attribute in Python 2. We should call 'str' function on this exception in general but\n # 'Py4JJavaError' has an issue about addressing non-ascii strings. So, here we work\n # around by the direct call, '__str__()'. Please see SPARK-23517.\n return excp.__str__()\n if hasattr(excp, \"message\"):\n return excp.message\n return str(excp)" }, { "instruction": "Write or improve a Python function based on this description:\n\nGet argspec of a function. Supports both Python 2 and Python 3.", "output": "def _get_argspec(f):\n \"\"\"\n Get argspec of a function. Supports both Python 2 and Python 3.\n \"\"\"\n if sys.version_info[0] < 3:\n argspec = inspect.getargspec(f)\n else:\n # `getargspec` is deprecated since python3.0 (incompatible with function annotations).\n # See SPARK-23569.\n argspec = inspect.getfullargspec(f)\n return argspec" }, { "instruction": "Write or improve a Python function based on this description:\n\nWraps the input function to fail on 'StopIteration' by raising a 'RuntimeError'\n prevents silent loss of data when 'f' is used in a for loop in Spark code", "output": "def fail_on_stopiteration(f):\n \"\"\"\n Wraps the input function to fail on 'StopIteration' by raising a 'RuntimeError'\n prevents silent loss of data when 'f' is used in a for loop in Spark code\n \"\"\"\n def wrapper(*args, **kwargs):\n try:\n return f(*args, **kwargs)\n except StopIteration as exc:\n raise RuntimeError(\n \"Caught StopIteration thrown from user's code; failing the task\",\n exc\n )\n\n return wrapper" }, { "instruction": "Write or improve a Python function based on this description:\n\nGiven a Spark version string, return the (major version number, minor version number).\n E.g., for 2.0.1-SNAPSHOT, return (2, 0).\n\n >>> sparkVersion = \"2.4.0\"\n >>> VersionUtils.majorMinorVersion(sparkVersion)\n (2, 4)\n >>> sparkVersion = \"2.3.0-SNAPSHOT\"\n >>> VersionUtils.majorMinorVersion(sparkVersion)\n (2, 3)", "output": "def majorMinorVersion(sparkVersion):\n \"\"\"\n Given a Spark version string, return the (major version number, minor version number).\n E.g., for 2.0.1-SNAPSHOT, return (2, 0).\n\n >>> sparkVersion = \"2.4.0\"\n >>> VersionUtils.majorMinorVersion(sparkVersion)\n (2, 4)\n >>> sparkVersion = \"2.3.0-SNAPSHOT\"\n >>> VersionUtils.majorMinorVersion(sparkVersion)\n (2, 3)\n\n \"\"\"\n m = re.search(r'^(\\d+)\\.(\\d+)(\\..*)?$', sparkVersion)\n if m is not None:\n return (int(m.group(1)), int(m.group(2)))\n else:\n raise ValueError(\"Spark tried to parse '%s' as a Spark\" % sparkVersion +\n \" version string, but it could not find the major and minor\" +\n \" version numbers.\")" }, { "instruction": "Write or improve a Python function based on this description:\n\nChecks whether a SparkContext is initialized or not.\n Throws error if a SparkContext is already running.", "output": "def _ensure_initialized(cls, instance=None, gateway=None, conf=None):\n \"\"\"\n Checks whether a SparkContext is initialized or not.\n Throws error if a SparkContext is already running.\n \"\"\"\n with SparkContext._lock:\n if not SparkContext._gateway:\n SparkContext._gateway = gateway or launch_gateway(conf)\n SparkContext._jvm = SparkContext._gateway.jvm\n\n if instance:\n if (SparkContext._active_spark_context and\n SparkContext._active_spark_context != instance):\n currentMaster = SparkContext._active_spark_context.master\n currentAppName = SparkContext._active_spark_context.appName\n callsite = SparkContext._active_spark_context._callsite\n\n # Raise error if there is already a running Spark context\n raise ValueError(\n \"Cannot run multiple SparkContexts at once; \"\n \"existing SparkContext(app=%s, master=%s)\"\n \" created by %s at %s:%s \"\n % (currentAppName, currentMaster,\n callsite.function, callsite.file, callsite.linenum))\n else:\n SparkContext._active_spark_context = instance" }, { "instruction": "Write or improve a Python function based on this description:\n\nGet or instantiate a SparkContext and register it as a singleton object.\n\n :param conf: SparkConf (optional)", "output": "def getOrCreate(cls, conf=None):\n \"\"\"\n Get or instantiate a SparkContext and register it as a singleton object.\n\n :param conf: SparkConf (optional)\n \"\"\"\n with SparkContext._lock:\n if SparkContext._active_spark_context is None:\n SparkContext(conf=conf or SparkConf())\n return SparkContext._active_spark_context" }, { "instruction": "Write or improve a Python function based on this description:\n\nSet a Java system property, such as spark.executor.memory. This must\n must be invoked before instantiating SparkContext.", "output": "def setSystemProperty(cls, key, value):\n \"\"\"\n Set a Java system property, such as spark.executor.memory. This must\n must be invoked before instantiating SparkContext.\n \"\"\"\n SparkContext._ensure_initialized()\n SparkContext._jvm.java.lang.System.setProperty(key, value)" }, { "instruction": "Write or improve a Python function based on this description:\n\nShut down the SparkContext.", "output": "def stop(self):\n \"\"\"\n Shut down the SparkContext.\n \"\"\"\n if getattr(self, \"_jsc\", None):\n try:\n self._jsc.stop()\n except Py4JError:\n # Case: SPARK-18523\n warnings.warn(\n 'Unable to cleanly shutdown Spark JVM process.'\n ' It is possible that the process has crashed,'\n ' been killed or may also be in a zombie state.',\n RuntimeWarning\n )\n finally:\n self._jsc = None\n if getattr(self, \"_accumulatorServer\", None):\n self._accumulatorServer.shutdown()\n self._accumulatorServer = None\n with SparkContext._lock:\n SparkContext._active_spark_context = None" }, { "instruction": "Write or improve a Python function based on this description:\n\nCreate a new RDD of int containing elements from `start` to `end`\n (exclusive), increased by `step` every element. Can be called the same\n way as python's built-in range() function. If called with a single argument,\n the argument is interpreted as `end`, and `start` is set to 0.\n\n :param start: the start value\n :param end: the end value (exclusive)\n :param step: the incremental step (default: 1)\n :param numSlices: the number of partitions of the new RDD\n :return: An RDD of int\n\n >>> sc.range(5).collect()\n [0, 1, 2, 3, 4]\n >>> sc.range(2, 4).collect()\n [2, 3]\n >>> sc.range(1, 7, 2).collect()\n [1, 3, 5]", "output": "def range(self, start, end=None, step=1, numSlices=None):\n \"\"\"\n Create a new RDD of int containing elements from `start` to `end`\n (exclusive), increased by `step` every element. Can be called the same\n way as python's built-in range() function. If called with a single argument,\n the argument is interpreted as `end`, and `start` is set to 0.\n\n :param start: the start value\n :param end: the end value (exclusive)\n :param step: the incremental step (default: 1)\n :param numSlices: the number of partitions of the new RDD\n :return: An RDD of int\n\n >>> sc.range(5).collect()\n [0, 1, 2, 3, 4]\n >>> sc.range(2, 4).collect()\n [2, 3]\n >>> sc.range(1, 7, 2).collect()\n [1, 3, 5]\n \"\"\"\n if end is None:\n end = start\n start = 0\n\n return self.parallelize(xrange(start, end, step), numSlices)" }, { "instruction": "Write or improve a Python function based on this description:\n\nDistribute a local Python collection to form an RDD. Using xrange\n is recommended if the input represents a range for performance.\n\n >>> sc.parallelize([0, 2, 3, 4, 6], 5).glom().collect()\n [[0], [2], [3], [4], [6]]\n >>> sc.parallelize(xrange(0, 6, 2), 5).glom().collect()\n [[], [0], [], [2], [4]]", "output": "def parallelize(self, c, numSlices=None):\n \"\"\"\n Distribute a local Python collection to form an RDD. Using xrange\n is recommended if the input represents a range for performance.\n\n >>> sc.parallelize([0, 2, 3, 4, 6], 5).glom().collect()\n [[0], [2], [3], [4], [6]]\n >>> sc.parallelize(xrange(0, 6, 2), 5).glom().collect()\n [[], [0], [], [2], [4]]\n \"\"\"\n numSlices = int(numSlices) if numSlices is not None else self.defaultParallelism\n if isinstance(c, xrange):\n size = len(c)\n if size == 0:\n return self.parallelize([], numSlices)\n step = c[1] - c[0] if size > 1 else 1\n start0 = c[0]\n\n def getStart(split):\n return start0 + int((split * size / numSlices)) * step\n\n def f(split, iterator):\n # it's an empty iterator here but we need this line for triggering the\n # logic of signal handling in FramedSerializer.load_stream, for instance,\n # SpecialLengths.END_OF_DATA_SECTION in _read_with_length. Since\n # FramedSerializer.load_stream produces a generator, the control should\n # at least be in that function once. Here we do it by explicitly converting\n # the empty iterator to a list, thus make sure worker reuse takes effect.\n # See more details in SPARK-26549.\n assert len(list(iterator)) == 0\n return xrange(getStart(split), getStart(split + 1), step)\n\n return self.parallelize([], numSlices).mapPartitionsWithIndex(f)\n\n # Make sure we distribute data evenly if it's smaller than self.batchSize\n if \"__len__\" not in dir(c):\n c = list(c) # Make it a list so we can compute its length\n batchSize = max(1, min(len(c) // numSlices, self._batchSize or 1024))\n serializer = BatchedSerializer(self._unbatched_serializer, batchSize)\n\n def reader_func(temp_filename):\n return self._jvm.PythonRDD.readRDDFromFile(self._jsc, temp_filename, numSlices)\n\n def createRDDServer():\n return self._jvm.PythonParallelizeServer(self._jsc.sc(), numSlices)\n\n jrdd = self._serialize_to_jvm(c, serializer, reader_func, createRDDServer)\n return RDD(jrdd, self, serializer)" }, { "instruction": "Write or improve a Python function based on this description:\n\nUsing py4j to send a large dataset to the jvm is really slow, so we use either a file\n or a socket if we have encryption enabled.\n :param data:\n :param serializer:\n :param reader_func: A function which takes a filename and reads in the data in the jvm and\n returns a JavaRDD. Only used when encryption is disabled.\n :param createRDDServer: A function which creates a PythonRDDServer in the jvm to\n accept the serialized data, for use when encryption is enabled.\n :return:", "output": "def _serialize_to_jvm(self, data, serializer, reader_func, createRDDServer):\n \"\"\"\n Using py4j to send a large dataset to the jvm is really slow, so we use either a file\n or a socket if we have encryption enabled.\n :param data:\n :param serializer:\n :param reader_func: A function which takes a filename and reads in the data in the jvm and\n returns a JavaRDD. Only used when encryption is disabled.\n :param createRDDServer: A function which creates a PythonRDDServer in the jvm to\n accept the serialized data, for use when encryption is enabled.\n :return:\n \"\"\"\n if self._encryption_enabled:\n # with encryption, we open a server in java and send the data directly\n server = createRDDServer()\n (sock_file, _) = local_connect_and_auth(server.port(), server.secret())\n chunked_out = ChunkedStream(sock_file, 8192)\n serializer.dump_stream(data, chunked_out)\n chunked_out.close()\n # this call will block until the server has read all the data and processed it (or\n # throws an exception)\n r = server.getResult()\n return r\n else:\n # without encryption, we serialize to a file, and we read the file in java and\n # parallelize from there.\n tempFile = NamedTemporaryFile(delete=False, dir=self._temp_dir)\n try:\n try:\n serializer.dump_stream(data, tempFile)\n finally:\n tempFile.close()\n return reader_func(tempFile.name)\n finally:\n # we eagerily reads the file so we can delete right after.\n os.unlink(tempFile.name)" }, { "instruction": "Write or improve a Python function based on this description:\n\nLoad an RDD previously saved using L{RDD.saveAsPickleFile} method.\n\n >>> tmpFile = NamedTemporaryFile(delete=True)\n >>> tmpFile.close()\n >>> sc.parallelize(range(10)).saveAsPickleFile(tmpFile.name, 5)\n >>> sorted(sc.pickleFile(tmpFile.name, 3).collect())\n [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]", "output": "def pickleFile(self, name, minPartitions=None):\n \"\"\"\n Load an RDD previously saved using L{RDD.saveAsPickleFile} method.\n\n >>> tmpFile = NamedTemporaryFile(delete=True)\n >>> tmpFile.close()\n >>> sc.parallelize(range(10)).saveAsPickleFile(tmpFile.name, 5)\n >>> sorted(sc.pickleFile(tmpFile.name, 3).collect())\n [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n \"\"\"\n minPartitions = minPartitions or self.defaultMinPartitions\n return RDD(self._jsc.objectFile(name, minPartitions), self)" }, { "instruction": "Write or improve a Python function based on this description:\n\nRead a text file from HDFS, a local file system (available on all\n nodes), or any Hadoop-supported file system URI, and return it as an\n RDD of Strings.\n The text files must be encoded as UTF-8.\n\n If use_unicode is False, the strings will be kept as `str` (encoding\n as `utf-8`), which is faster and smaller than unicode. (Added in\n Spark 1.2)\n\n >>> path = os.path.join(tempdir, \"sample-text.txt\")\n >>> with open(path, \"w\") as testFile:\n ... _ = testFile.write(\"Hello world!\")\n >>> textFile = sc.textFile(path)\n >>> textFile.collect()\n [u'Hello world!']", "output": "def textFile(self, name, minPartitions=None, use_unicode=True):\n \"\"\"\n Read a text file from HDFS, a local file system (available on all\n nodes), or any Hadoop-supported file system URI, and return it as an\n RDD of Strings.\n The text files must be encoded as UTF-8.\n\n If use_unicode is False, the strings will be kept as `str` (encoding\n as `utf-8`), which is faster and smaller than unicode. (Added in\n Spark 1.2)\n\n >>> path = os.path.join(tempdir, \"sample-text.txt\")\n >>> with open(path, \"w\") as testFile:\n ... _ = testFile.write(\"Hello world!\")\n >>> textFile = sc.textFile(path)\n >>> textFile.collect()\n [u'Hello world!']\n \"\"\"\n minPartitions = minPartitions or min(self.defaultParallelism, 2)\n return RDD(self._jsc.textFile(name, minPartitions), self,\n UTF8Deserializer(use_unicode))" }, { "instruction": "Write or improve a Python function based on this description:\n\nRead a directory of text files from HDFS, a local file system\n (available on all nodes), or any Hadoop-supported file system\n URI. Each file is read as a single record and returned in a\n key-value pair, where the key is the path of each file, the\n value is the content of each file.\n The text files must be encoded as UTF-8.\n\n If use_unicode is False, the strings will be kept as `str` (encoding\n as `utf-8`), which is faster and smaller than unicode. (Added in\n Spark 1.2)\n\n For example, if you have the following files::\n\n hdfs://a-hdfs-path/part-00000\n hdfs://a-hdfs-path/part-00001\n ...\n hdfs://a-hdfs-path/part-nnnnn\n\n Do C{rdd = sparkContext.wholeTextFiles(\"hdfs://a-hdfs-path\")},\n then C{rdd} contains::\n\n (a-hdfs-path/part-00000, its content)\n (a-hdfs-path/part-00001, its content)\n ...\n (a-hdfs-path/part-nnnnn, its content)\n\n .. note:: Small files are preferred, as each file will be loaded\n fully in memory.\n\n >>> dirPath = os.path.join(tempdir, \"files\")\n >>> os.mkdir(dirPath)\n >>> with open(os.path.join(dirPath, \"1.txt\"), \"w\") as file1:\n ... _ = file1.write(\"1\")\n >>> with open(os.path.join(dirPath, \"2.txt\"), \"w\") as file2:\n ... _ = file2.write(\"2\")\n >>> textFiles = sc.wholeTextFiles(dirPath)\n >>> sorted(textFiles.collect())\n [(u'.../1.txt', u'1'), (u'.../2.txt', u'2')]", "output": "def wholeTextFiles(self, path, minPartitions=None, use_unicode=True):\n \"\"\"\n Read a directory of text files from HDFS, a local file system\n (available on all nodes), or any Hadoop-supported file system\n URI. Each file is read as a single record and returned in a\n key-value pair, where the key is the path of each file, the\n value is the content of each file.\n The text files must be encoded as UTF-8.\n\n If use_unicode is False, the strings will be kept as `str` (encoding\n as `utf-8`), which is faster and smaller than unicode. (Added in\n Spark 1.2)\n\n For example, if you have the following files::\n\n hdfs://a-hdfs-path/part-00000\n hdfs://a-hdfs-path/part-00001\n ...\n hdfs://a-hdfs-path/part-nnnnn\n\n Do C{rdd = sparkContext.wholeTextFiles(\"hdfs://a-hdfs-path\")},\n then C{rdd} contains::\n\n (a-hdfs-path/part-00000, its content)\n (a-hdfs-path/part-00001, its content)\n ...\n (a-hdfs-path/part-nnnnn, its content)\n\n .. note:: Small files are preferred, as each file will be loaded\n fully in memory.\n\n >>> dirPath = os.path.join(tempdir, \"files\")\n >>> os.mkdir(dirPath)\n >>> with open(os.path.join(dirPath, \"1.txt\"), \"w\") as file1:\n ... _ = file1.write(\"1\")\n >>> with open(os.path.join(dirPath, \"2.txt\"), \"w\") as file2:\n ... _ = file2.write(\"2\")\n >>> textFiles = sc.wholeTextFiles(dirPath)\n >>> sorted(textFiles.collect())\n [(u'.../1.txt', u'1'), (u'.../2.txt', u'2')]\n \"\"\"\n minPartitions = minPartitions or self.defaultMinPartitions\n return RDD(self._jsc.wholeTextFiles(path, minPartitions), self,\n PairDeserializer(UTF8Deserializer(use_unicode), UTF8Deserializer(use_unicode)))" }, { "instruction": "Write or improve a Python function based on this description:\n\n.. note:: Experimental\n\n Read a directory of binary files from HDFS, a local file system\n (available on all nodes), or any Hadoop-supported file system URI\n as a byte array. Each file is read as a single record and returned\n in a key-value pair, where the key is the path of each file, the\n value is the content of each file.\n\n .. note:: Small files are preferred, large file is also allowable, but\n may cause bad performance.", "output": "def binaryFiles(self, path, minPartitions=None):\n \"\"\"\n .. note:: Experimental\n\n Read a directory of binary files from HDFS, a local file system\n (available on all nodes), or any Hadoop-supported file system URI\n as a byte array. Each file is read as a single record and returned\n in a key-value pair, where the key is the path of each file, the\n value is the content of each file.\n\n .. note:: Small files are preferred, large file is also allowable, but\n may cause bad performance.\n \"\"\"\n minPartitions = minPartitions or self.defaultMinPartitions\n return RDD(self._jsc.binaryFiles(path, minPartitions), self,\n PairDeserializer(UTF8Deserializer(), NoOpSerializer()))" }, { "instruction": "Write or improve a Python function based on this description:\n\n.. note:: Experimental\n\n Load data from a flat binary file, assuming each record is a set of numbers\n with the specified numerical format (see ByteBuffer), and the number of\n bytes per record is constant.\n\n :param path: Directory to the input data files\n :param recordLength: The length at which to split the records", "output": "def binaryRecords(self, path, recordLength):\n \"\"\"\n .. note:: Experimental\n\n Load data from a flat binary file, assuming each record is a set of numbers\n with the specified numerical format (see ByteBuffer), and the number of\n bytes per record is constant.\n\n :param path: Directory to the input data files\n :param recordLength: The length at which to split the records\n \"\"\"\n return RDD(self._jsc.binaryRecords(path, recordLength), self, NoOpSerializer())" }, { "instruction": "Write or improve a Python function based on this description:\n\nRead a Hadoop SequenceFile with arbitrary key and value Writable class from HDFS,\n a local file system (available on all nodes), or any Hadoop-supported file system URI.\n The mechanism is as follows:\n\n 1. A Java RDD is created from the SequenceFile or other InputFormat, and the key\n and value Writable classes\n 2. Serialization is attempted via Pyrolite pickling\n 3. If this fails, the fallback is to call 'toString' on each key and value\n 4. C{PickleSerializer} is used to deserialize pickled objects on the Python side\n\n :param path: path to sequncefile\n :param keyClass: fully qualified classname of key Writable class\n (e.g. \"org.apache.hadoop.io.Text\")\n :param valueClass: fully qualified classname of value Writable class\n (e.g. \"org.apache.hadoop.io.LongWritable\")\n :param keyConverter:\n :param valueConverter:\n :param minSplits: minimum splits in dataset\n (default min(2, sc.defaultParallelism))\n :param batchSize: The number of Python objects represented as a single\n Java object. (default 0, choose batchSize automatically)", "output": "def sequenceFile(self, path, keyClass=None, valueClass=None, keyConverter=None,\n valueConverter=None, minSplits=None, batchSize=0):\n \"\"\"\n Read a Hadoop SequenceFile with arbitrary key and value Writable class from HDFS,\n a local file system (available on all nodes), or any Hadoop-supported file system URI.\n The mechanism is as follows:\n\n 1. A Java RDD is created from the SequenceFile or other InputFormat, and the key\n and value Writable classes\n 2. Serialization is attempted via Pyrolite pickling\n 3. If this fails, the fallback is to call 'toString' on each key and value\n 4. C{PickleSerializer} is used to deserialize pickled objects on the Python side\n\n :param path: path to sequncefile\n :param keyClass: fully qualified classname of key Writable class\n (e.g. \"org.apache.hadoop.io.Text\")\n :param valueClass: fully qualified classname of value Writable class\n (e.g. \"org.apache.hadoop.io.LongWritable\")\n :param keyConverter:\n :param valueConverter:\n :param minSplits: minimum splits in dataset\n (default min(2, sc.defaultParallelism))\n :param batchSize: The number of Python objects represented as a single\n Java object. (default 0, choose batchSize automatically)\n \"\"\"\n minSplits = minSplits or min(self.defaultParallelism, 2)\n jrdd = self._jvm.PythonRDD.sequenceFile(self._jsc, path, keyClass, valueClass,\n keyConverter, valueConverter, minSplits, batchSize)\n return RDD(jrdd, self)" }, { "instruction": "Write or improve a Python function based on this description:\n\nRead a 'new API' Hadoop InputFormat with arbitrary key and value class from HDFS,\n a local file system (available on all nodes), or any Hadoop-supported file system URI.\n The mechanism is the same as for sc.sequenceFile.\n\n A Hadoop configuration can be passed in as a Python dict. This will be converted into a\n Configuration in Java\n\n :param path: path to Hadoop file\n :param inputFormatClass: fully qualified classname of Hadoop InputFormat\n (e.g. \"org.apache.hadoop.mapreduce.lib.input.TextInputFormat\")\n :param keyClass: fully qualified classname of key Writable class\n (e.g. \"org.apache.hadoop.io.Text\")\n :param valueClass: fully qualified classname of value Writable class\n (e.g. \"org.apache.hadoop.io.LongWritable\")\n :param keyConverter: (None by default)\n :param valueConverter: (None by default)\n :param conf: Hadoop configuration, passed in as a dict\n (None by default)\n :param batchSize: The number of Python objects represented as a single\n Java object. (default 0, choose batchSize automatically)", "output": "def newAPIHadoopFile(self, path, inputFormatClass, keyClass, valueClass, keyConverter=None,\n valueConverter=None, conf=None, batchSize=0):\n \"\"\"\n Read a 'new API' Hadoop InputFormat with arbitrary key and value class from HDFS,\n a local file system (available on all nodes), or any Hadoop-supported file system URI.\n The mechanism is the same as for sc.sequenceFile.\n\n A Hadoop configuration can be passed in as a Python dict. This will be converted into a\n Configuration in Java\n\n :param path: path to Hadoop file\n :param inputFormatClass: fully qualified classname of Hadoop InputFormat\n (e.g. \"org.apache.hadoop.mapreduce.lib.input.TextInputFormat\")\n :param keyClass: fully qualified classname of key Writable class\n (e.g. \"org.apache.hadoop.io.Text\")\n :param valueClass: fully qualified classname of value Writable class\n (e.g. \"org.apache.hadoop.io.LongWritable\")\n :param keyConverter: (None by default)\n :param valueConverter: (None by default)\n :param conf: Hadoop configuration, passed in as a dict\n (None by default)\n :param batchSize: The number of Python objects represented as a single\n Java object. (default 0, choose batchSize automatically)\n \"\"\"\n jconf = self._dictToJavaMap(conf)\n jrdd = self._jvm.PythonRDD.newAPIHadoopFile(self._jsc, path, inputFormatClass, keyClass,\n valueClass, keyConverter, valueConverter,\n jconf, batchSize)\n return RDD(jrdd, self)" }, { "instruction": "Write or improve a Python function based on this description:\n\nBuild the union of a list of RDDs.\n\n This supports unions() of RDDs with different serialized formats,\n although this forces them to be reserialized using the default\n serializer:\n\n >>> path = os.path.join(tempdir, \"union-text.txt\")\n >>> with open(path, \"w\") as testFile:\n ... _ = testFile.write(\"Hello\")\n >>> textFile = sc.textFile(path)\n >>> textFile.collect()\n [u'Hello']\n >>> parallelized = sc.parallelize([\"World!\"])\n >>> sorted(sc.union([textFile, parallelized]).collect())\n [u'Hello', 'World!']", "output": "def union(self, rdds):\n \"\"\"\n Build the union of a list of RDDs.\n\n This supports unions() of RDDs with different serialized formats,\n although this forces them to be reserialized using the default\n serializer:\n\n >>> path = os.path.join(tempdir, \"union-text.txt\")\n >>> with open(path, \"w\") as testFile:\n ... _ = testFile.write(\"Hello\")\n >>> textFile = sc.textFile(path)\n >>> textFile.collect()\n [u'Hello']\n >>> parallelized = sc.parallelize([\"World!\"])\n >>> sorted(sc.union([textFile, parallelized]).collect())\n [u'Hello', 'World!']\n \"\"\"\n first_jrdd_deserializer = rdds[0]._jrdd_deserializer\n if any(x._jrdd_deserializer != first_jrdd_deserializer for x in rdds):\n rdds = [x._reserialize() for x in rdds]\n cls = SparkContext._jvm.org.apache.spark.api.java.JavaRDD\n jrdds = SparkContext._gateway.new_array(cls, len(rdds))\n for i in range(0, len(rdds)):\n jrdds[i] = rdds[i]._jrdd\n return RDD(self._jsc.union(jrdds), self, rdds[0]._jrdd_deserializer)" }, { "instruction": "Write or improve a Python function based on this description:\n\nCreate an L{Accumulator} with the given initial value, using a given\n L{AccumulatorParam} helper object to define how to add values of the\n data type if provided. Default AccumulatorParams are used for integers\n and floating-point numbers if you do not provide one. For other types,\n a custom AccumulatorParam can be used.", "output": "def accumulator(self, value, accum_param=None):\n \"\"\"\n Create an L{Accumulator} with the given initial value, using a given\n L{AccumulatorParam} helper object to define how to add values of the\n data type if provided. Default AccumulatorParams are used for integers\n and floating-point numbers if you do not provide one. For other types,\n a custom AccumulatorParam can be used.\n \"\"\"\n if accum_param is None:\n if isinstance(value, int):\n accum_param = accumulators.INT_ACCUMULATOR_PARAM\n elif isinstance(value, float):\n accum_param = accumulators.FLOAT_ACCUMULATOR_PARAM\n elif isinstance(value, complex):\n accum_param = accumulators.COMPLEX_ACCUMULATOR_PARAM\n else:\n raise TypeError(\"No default accumulator param for type %s\" % type(value))\n SparkContext._next_accum_id += 1\n return Accumulator(SparkContext._next_accum_id - 1, value, accum_param)" }, { "instruction": "Write or improve a Python function based on this description:\n\nAdd a file to be downloaded with this Spark job on every node.\n The C{path} passed can be either a local file, a file in HDFS\n (or other Hadoop-supported filesystems), or an HTTP, HTTPS or\n FTP URI.\n\n To access the file in Spark jobs, use\n L{SparkFiles.get(fileName)} with the\n filename to find its download location.\n\n A directory can be given if the recursive option is set to True.\n Currently directories are only supported for Hadoop-supported filesystems.\n\n .. note:: A path can be added only once. Subsequent additions of the same path are ignored.\n\n >>> from pyspark import SparkFiles\n >>> path = os.path.join(tempdir, \"test.txt\")\n >>> with open(path, \"w\") as testFile:\n ... _ = testFile.write(\"100\")\n >>> sc.addFile(path)\n >>> def func(iterator):\n ... with open(SparkFiles.get(\"test.txt\")) as testFile:\n ... fileVal = int(testFile.readline())\n ... return [x * fileVal for x in iterator]\n >>> sc.parallelize([1, 2, 3, 4]).mapPartitions(func).collect()\n [100, 200, 300, 400]", "output": "def addFile(self, path, recursive=False):\n \"\"\"\n Add a file to be downloaded with this Spark job on every node.\n The C{path} passed can be either a local file, a file in HDFS\n (or other Hadoop-supported filesystems), or an HTTP, HTTPS or\n FTP URI.\n\n To access the file in Spark jobs, use\n L{SparkFiles.get(fileName)} with the\n filename to find its download location.\n\n A directory can be given if the recursive option is set to True.\n Currently directories are only supported for Hadoop-supported filesystems.\n\n .. note:: A path can be added only once. Subsequent additions of the same path are ignored.\n\n >>> from pyspark import SparkFiles\n >>> path = os.path.join(tempdir, \"test.txt\")\n >>> with open(path, \"w\") as testFile:\n ... _ = testFile.write(\"100\")\n >>> sc.addFile(path)\n >>> def func(iterator):\n ... with open(SparkFiles.get(\"test.txt\")) as testFile:\n ... fileVal = int(testFile.readline())\n ... return [x * fileVal for x in iterator]\n >>> sc.parallelize([1, 2, 3, 4]).mapPartitions(func).collect()\n [100, 200, 300, 400]\n \"\"\"\n self._jsc.sc().addFile(path, recursive)" }, { "instruction": "Write or improve a Python function based on this description:\n\nAdd a .py or .zip dependency for all tasks to be executed on this\n SparkContext in the future. The C{path} passed can be either a local\n file, a file in HDFS (or other Hadoop-supported filesystems), or an\n HTTP, HTTPS or FTP URI.\n\n .. note:: A path can be added only once. Subsequent additions of the same path are ignored.", "output": "def addPyFile(self, path):\n \"\"\"\n Add a .py or .zip dependency for all tasks to be executed on this\n SparkContext in the future. The C{path} passed can be either a local\n file, a file in HDFS (or other Hadoop-supported filesystems), or an\n HTTP, HTTPS or FTP URI.\n\n .. note:: A path can be added only once. Subsequent additions of the same path are ignored.\n \"\"\"\n self.addFile(path)\n (dirname, filename) = os.path.split(path) # dirname may be directory or HDFS/S3 prefix\n if filename[-4:].lower() in self.PACKAGE_EXTENSIONS:\n self._python_includes.append(filename)\n # for tests in local mode\n sys.path.insert(1, os.path.join(SparkFiles.getRootDirectory(), filename))\n if sys.version > '3':\n import importlib\n importlib.invalidate_caches()" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns a Java StorageLevel based on a pyspark.StorageLevel.", "output": "def _getJavaStorageLevel(self, storageLevel):\n \"\"\"\n Returns a Java StorageLevel based on a pyspark.StorageLevel.\n \"\"\"\n if not isinstance(storageLevel, StorageLevel):\n raise Exception(\"storageLevel must be of type pyspark.StorageLevel\")\n\n newStorageLevel = self._jvm.org.apache.spark.storage.StorageLevel\n return newStorageLevel(storageLevel.useDisk,\n storageLevel.useMemory,\n storageLevel.useOffHeap,\n storageLevel.deserialized,\n storageLevel.replication)" }, { "instruction": "Write or improve a Python function based on this description:\n\nAssigns a group ID to all the jobs started by this thread until the group ID is set to a\n different value or cleared.\n\n Often, a unit of execution in an application consists of multiple Spark actions or jobs.\n Application programmers can use this method to group all those jobs together and give a\n group description. Once set, the Spark web UI will associate such jobs with this group.\n\n The application can use L{SparkContext.cancelJobGroup} to cancel all\n running jobs in this group.\n\n >>> import threading\n >>> from time import sleep\n >>> result = \"Not Set\"\n >>> lock = threading.Lock()\n >>> def map_func(x):\n ... sleep(100)\n ... raise Exception(\"Task should have been cancelled\")\n >>> def start_job(x):\n ... global result\n ... try:\n ... sc.setJobGroup(\"job_to_cancel\", \"some description\")\n ... result = sc.parallelize(range(x)).map(map_func).collect()\n ... except Exception as e:\n ... result = \"Cancelled\"\n ... lock.release()\n >>> def stop_job():\n ... sleep(5)\n ... sc.cancelJobGroup(\"job_to_cancel\")\n >>> suppress = lock.acquire()\n >>> suppress = threading.Thread(target=start_job, args=(10,)).start()\n >>> suppress = threading.Thread(target=stop_job).start()\n >>> suppress = lock.acquire()\n >>> print(result)\n Cancelled\n\n If interruptOnCancel is set to true for the job group, then job cancellation will result\n in Thread.interrupt() being called on the job's executor threads. This is useful to help\n ensure that the tasks are actually stopped in a timely manner, but is off by default due\n to HDFS-1208, where HDFS may respond to Thread.interrupt() by marking nodes as dead.", "output": "def setJobGroup(self, groupId, description, interruptOnCancel=False):\n \"\"\"\n Assigns a group ID to all the jobs started by this thread until the group ID is set to a\n different value or cleared.\n\n Often, a unit of execution in an application consists of multiple Spark actions or jobs.\n Application programmers can use this method to group all those jobs together and give a\n group description. Once set, the Spark web UI will associate such jobs with this group.\n\n The application can use L{SparkContext.cancelJobGroup} to cancel all\n running jobs in this group.\n\n >>> import threading\n >>> from time import sleep\n >>> result = \"Not Set\"\n >>> lock = threading.Lock()\n >>> def map_func(x):\n ... sleep(100)\n ... raise Exception(\"Task should have been cancelled\")\n >>> def start_job(x):\n ... global result\n ... try:\n ... sc.setJobGroup(\"job_to_cancel\", \"some description\")\n ... result = sc.parallelize(range(x)).map(map_func).collect()\n ... except Exception as e:\n ... result = \"Cancelled\"\n ... lock.release()\n >>> def stop_job():\n ... sleep(5)\n ... sc.cancelJobGroup(\"job_to_cancel\")\n >>> suppress = lock.acquire()\n >>> suppress = threading.Thread(target=start_job, args=(10,)).start()\n >>> suppress = threading.Thread(target=stop_job).start()\n >>> suppress = lock.acquire()\n >>> print(result)\n Cancelled\n\n If interruptOnCancel is set to true for the job group, then job cancellation will result\n in Thread.interrupt() being called on the job's executor threads. This is useful to help\n ensure that the tasks are actually stopped in a timely manner, but is off by default due\n to HDFS-1208, where HDFS may respond to Thread.interrupt() by marking nodes as dead.\n \"\"\"\n self._jsc.setJobGroup(groupId, description, interruptOnCancel)" }, { "instruction": "Write or improve a Python function based on this description:\n\nExecutes the given partitionFunc on the specified set of partitions,\n returning the result as an array of elements.\n\n If 'partitions' is not specified, this will run over all partitions.\n\n >>> myRDD = sc.parallelize(range(6), 3)\n >>> sc.runJob(myRDD, lambda part: [x * x for x in part])\n [0, 1, 4, 9, 16, 25]\n\n >>> myRDD = sc.parallelize(range(6), 3)\n >>> sc.runJob(myRDD, lambda part: [x * x for x in part], [0, 2], True)\n [0, 1, 16, 25]", "output": "def runJob(self, rdd, partitionFunc, partitions=None, allowLocal=False):\n \"\"\"\n Executes the given partitionFunc on the specified set of partitions,\n returning the result as an array of elements.\n\n If 'partitions' is not specified, this will run over all partitions.\n\n >>> myRDD = sc.parallelize(range(6), 3)\n >>> sc.runJob(myRDD, lambda part: [x * x for x in part])\n [0, 1, 4, 9, 16, 25]\n\n >>> myRDD = sc.parallelize(range(6), 3)\n >>> sc.runJob(myRDD, lambda part: [x * x for x in part], [0, 2], True)\n [0, 1, 16, 25]\n \"\"\"\n if partitions is None:\n partitions = range(rdd._jrdd.partitions().size())\n\n # Implementation note: This is implemented as a mapPartitions followed\n # by runJob() in order to avoid having to pass a Python lambda into\n # SparkContext#runJob.\n mappedRDD = rdd.mapPartitions(partitionFunc)\n sock_info = self._jvm.PythonRDD.runJob(self._jsc.sc(), mappedRDD._jrdd, partitions)\n return list(_load_from_socket(sock_info, mappedRDD._jrdd_deserializer))" }, { "instruction": "Write or improve a Python function based on this description:\n\nDump the profile stats into directory `path`", "output": "def dump_profiles(self, path):\n \"\"\" Dump the profile stats into directory `path`\n \"\"\"\n if self.profiler_collector is not None:\n self.profiler_collector.dump_profiles(path)\n else:\n raise RuntimeError(\"'spark.python.profile' configuration must be set \"\n \"to 'true' to enable Python profile.\")" }, { "instruction": "Write or improve a Python function based on this description:\n\nTrain a matrix factorization model given an RDD of ratings by users\n for a subset of products. The ratings matrix is approximated as the\n product of two lower-rank matrices of a given rank (number of\n features). To solve for these features, ALS is run iteratively with\n a configurable level of parallelism.\n\n :param ratings:\n RDD of `Rating` or (userID, productID, rating) tuple.\n :param rank:\n Number of features to use (also referred to as the number of latent factors).\n :param iterations:\n Number of iterations of ALS.\n (default: 5)\n :param lambda_:\n Regularization parameter.\n (default: 0.01)\n :param blocks:\n Number of blocks used to parallelize the computation. A value\n of -1 will use an auto-configured number of blocks.\n (default: -1)\n :param nonnegative:\n A value of True will solve least-squares with nonnegativity\n constraints.\n (default: False)\n :param seed:\n Random seed for initial matrix factorization model. A value\n of None will use system time as the seed.\n (default: None)", "output": "def train(cls, ratings, rank, iterations=5, lambda_=0.01, blocks=-1, nonnegative=False,\n seed=None):\n \"\"\"\n Train a matrix factorization model given an RDD of ratings by users\n for a subset of products. The ratings matrix is approximated as the\n product of two lower-rank matrices of a given rank (number of\n features). To solve for these features, ALS is run iteratively with\n a configurable level of parallelism.\n\n :param ratings:\n RDD of `Rating` or (userID, productID, rating) tuple.\n :param rank:\n Number of features to use (also referred to as the number of latent factors).\n :param iterations:\n Number of iterations of ALS.\n (default: 5)\n :param lambda_:\n Regularization parameter.\n (default: 0.01)\n :param blocks:\n Number of blocks used to parallelize the computation. A value\n of -1 will use an auto-configured number of blocks.\n (default: -1)\n :param nonnegative:\n A value of True will solve least-squares with nonnegativity\n constraints.\n (default: False)\n :param seed:\n Random seed for initial matrix factorization model. A value\n of None will use system time as the seed.\n (default: None)\n \"\"\"\n model = callMLlibFunc(\"trainALSModel\", cls._prepare(ratings), rank, iterations,\n lambda_, blocks, nonnegative, seed)\n return MatrixFactorizationModel(model)" }, { "instruction": "Write or improve a Python function based on this description:\n\nComputes an FP-Growth model that contains frequent itemsets.\n\n :param data:\n The input data set, each element contains a transaction.\n :param minSupport:\n The minimal support level.\n (default: 0.3)\n :param numPartitions:\n The number of partitions used by parallel FP-growth. A value\n of -1 will use the same number as input data.\n (default: -1)", "output": "def train(cls, data, minSupport=0.3, numPartitions=-1):\n \"\"\"\n Computes an FP-Growth model that contains frequent itemsets.\n\n :param data:\n The input data set, each element contains a transaction.\n :param minSupport:\n The minimal support level.\n (default: 0.3)\n :param numPartitions:\n The number of partitions used by parallel FP-growth. A value\n of -1 will use the same number as input data.\n (default: -1)\n \"\"\"\n model = callMLlibFunc(\"trainFPGrowthModel\", data, float(minSupport), int(numPartitions))\n return FPGrowthModel(model)" }, { "instruction": "Write or improve a Python function based on this description:\n\nFinds the complete set of frequent sequential patterns in the\n input sequences of itemsets.\n\n :param data:\n The input data set, each element contains a sequence of\n itemsets.\n :param minSupport:\n The minimal support level of the sequential pattern, any\n pattern that appears more than (minSupport *\n size-of-the-dataset) times will be output.\n (default: 0.1)\n :param maxPatternLength:\n The maximal length of the sequential pattern, any pattern\n that appears less than maxPatternLength will be output.\n (default: 10)\n :param maxLocalProjDBSize:\n The maximum number of items (including delimiters used in the\n internal storage format) allowed in a projected database before\n local processing. If a projected database exceeds this size,\n another iteration of distributed prefix growth is run.\n (default: 32000000)", "output": "def train(cls, data, minSupport=0.1, maxPatternLength=10, maxLocalProjDBSize=32000000):\n \"\"\"\n Finds the complete set of frequent sequential patterns in the\n input sequences of itemsets.\n\n :param data:\n The input data set, each element contains a sequence of\n itemsets.\n :param minSupport:\n The minimal support level of the sequential pattern, any\n pattern that appears more than (minSupport *\n size-of-the-dataset) times will be output.\n (default: 0.1)\n :param maxPatternLength:\n The maximal length of the sequential pattern, any pattern\n that appears less than maxPatternLength will be output.\n (default: 10)\n :param maxLocalProjDBSize:\n The maximum number of items (including delimiters used in the\n internal storage format) allowed in a projected database before\n local processing. If a projected database exceeds this size,\n another iteration of distributed prefix growth is run.\n (default: 32000000)\n \"\"\"\n model = callMLlibFunc(\"trainPrefixSpanModel\",\n data, minSupport, maxPatternLength, maxLocalProjDBSize)\n return PrefixSpanModel(model)" }, { "instruction": "Write or improve a Python function based on this description:\n\nSet sample points from the population. Should be a RDD", "output": "def setSample(self, sample):\n \"\"\"Set sample points from the population. Should be a RDD\"\"\"\n if not isinstance(sample, RDD):\n raise TypeError(\"samples should be a RDD, received %s\" % type(sample))\n self._sample = sample" }, { "instruction": "Write or improve a Python function based on this description:\n\nEstimate the probability density at points", "output": "def estimate(self, points):\n \"\"\"Estimate the probability density at points\"\"\"\n points = list(points)\n densities = callMLlibFunc(\n \"estimateKernelDensity\", self._sample, self._bandwidth, points)\n return np.asarray(densities)" }, { "instruction": "Write or improve a Python function based on this description:\n\nStart a TCP server to receive accumulator updates in a daemon thread, and returns it", "output": "def _start_update_server(auth_token):\n \"\"\"Start a TCP server to receive accumulator updates in a daemon thread, and returns it\"\"\"\n server = AccumulatorServer((\"localhost\", 0), _UpdateRequestHandler, auth_token)\n thread = threading.Thread(target=server.serve_forever)\n thread.daemon = True\n thread.start()\n return server" }, { "instruction": "Write or improve a Python function based on this description:\n\nAdds a term to this accumulator's value", "output": "def add(self, term):\n \"\"\"Adds a term to this accumulator's value\"\"\"\n self._value = self.accum_param.addInPlace(self._value, term)" }, { "instruction": "Write or improve a Python function based on this description:\n\nCompute aggregates and returns the result as a :class:`DataFrame`.\n\n The available aggregate functions can be:\n\n 1. built-in aggregation functions, such as `avg`, `max`, `min`, `sum`, `count`\n\n 2. group aggregate pandas UDFs, created with :func:`pyspark.sql.functions.pandas_udf`\n\n .. note:: There is no partial aggregation with group aggregate UDFs, i.e.,\n a full shuffle is required. Also, all the data of a group will be loaded into\n memory, so the user should be aware of the potential OOM risk if data is skewed\n and certain groups are too large to fit in memory.\n\n .. seealso:: :func:`pyspark.sql.functions.pandas_udf`\n\n If ``exprs`` is a single :class:`dict` mapping from string to string, then the key\n is the column to perform aggregation on, and the value is the aggregate function.\n\n Alternatively, ``exprs`` can also be a list of aggregate :class:`Column` expressions.\n\n .. note:: Built-in aggregation functions and group aggregate pandas UDFs cannot be mixed\n in a single call to this function.\n\n :param exprs: a dict mapping from column name (string) to aggregate functions (string),\n or a list of :class:`Column`.\n\n >>> gdf = df.groupBy(df.name)\n >>> sorted(gdf.agg({\"*\": \"count\"}).collect())\n [Row(name=u'Alice', count(1)=1), Row(name=u'Bob', count(1)=1)]\n\n >>> from pyspark.sql import functions as F\n >>> sorted(gdf.agg(F.min(df.age)).collect())\n [Row(name=u'Alice', min(age)=2), Row(name=u'Bob', min(age)=5)]\n\n >>> from pyspark.sql.functions import pandas_udf, PandasUDFType\n >>> @pandas_udf('int', PandasUDFType.GROUPED_AGG) # doctest: +SKIP\n ... def min_udf(v):\n ... return v.min()\n >>> sorted(gdf.agg(min_udf(df.age)).collect()) # doctest: +SKIP\n [Row(name=u'Alice', min_udf(age)=2), Row(name=u'Bob', min_udf(age)=5)]", "output": "def agg(self, *exprs):\n \"\"\"Compute aggregates and returns the result as a :class:`DataFrame`.\n\n The available aggregate functions can be:\n\n 1. built-in aggregation functions, such as `avg`, `max`, `min`, `sum`, `count`\n\n 2. group aggregate pandas UDFs, created with :func:`pyspark.sql.functions.pandas_udf`\n\n .. note:: There is no partial aggregation with group aggregate UDFs, i.e.,\n a full shuffle is required. Also, all the data of a group will be loaded into\n memory, so the user should be aware of the potential OOM risk if data is skewed\n and certain groups are too large to fit in memory.\n\n .. seealso:: :func:`pyspark.sql.functions.pandas_udf`\n\n If ``exprs`` is a single :class:`dict` mapping from string to string, then the key\n is the column to perform aggregation on, and the value is the aggregate function.\n\n Alternatively, ``exprs`` can also be a list of aggregate :class:`Column` expressions.\n\n .. note:: Built-in aggregation functions and group aggregate pandas UDFs cannot be mixed\n in a single call to this function.\n\n :param exprs: a dict mapping from column name (string) to aggregate functions (string),\n or a list of :class:`Column`.\n\n >>> gdf = df.groupBy(df.name)\n >>> sorted(gdf.agg({\"*\": \"count\"}).collect())\n [Row(name=u'Alice', count(1)=1), Row(name=u'Bob', count(1)=1)]\n\n >>> from pyspark.sql import functions as F\n >>> sorted(gdf.agg(F.min(df.age)).collect())\n [Row(name=u'Alice', min(age)=2), Row(name=u'Bob', min(age)=5)]\n\n >>> from pyspark.sql.functions import pandas_udf, PandasUDFType\n >>> @pandas_udf('int', PandasUDFType.GROUPED_AGG) # doctest: +SKIP\n ... def min_udf(v):\n ... return v.min()\n >>> sorted(gdf.agg(min_udf(df.age)).collect()) # doctest: +SKIP\n [Row(name=u'Alice', min_udf(age)=2), Row(name=u'Bob', min_udf(age)=5)]\n \"\"\"\n assert exprs, \"exprs should not be empty\"\n if len(exprs) == 1 and isinstance(exprs[0], dict):\n jdf = self._jgd.agg(exprs[0])\n else:\n # Columns\n assert all(isinstance(c, Column) for c in exprs), \"all exprs should be Column\"\n jdf = self._jgd.agg(exprs[0]._jc,\n _to_seq(self.sql_ctx._sc, [c._jc for c in exprs[1:]]))\n return DataFrame(jdf, self.sql_ctx)" }, { "instruction": "Write or improve a Python function based on this description:\n\nPivots a column of the current :class:`DataFrame` and perform the specified aggregation.\n There are two versions of pivot function: one that requires the caller to specify the list\n of distinct values to pivot on, and one that does not. The latter is more concise but less\n efficient, because Spark needs to first compute the list of distinct values internally.\n\n :param pivot_col: Name of the column to pivot.\n :param values: List of values that will be translated to columns in the output DataFrame.\n\n # Compute the sum of earnings for each year by course with each course as a separate column\n\n >>> df4.groupBy(\"year\").pivot(\"course\", [\"dotNET\", \"Java\"]).sum(\"earnings\").collect()\n [Row(year=2012, dotNET=15000, Java=20000), Row(year=2013, dotNET=48000, Java=30000)]\n\n # Or without specifying column values (less efficient)\n\n >>> df4.groupBy(\"year\").pivot(\"course\").sum(\"earnings\").collect()\n [Row(year=2012, Java=20000, dotNET=15000), Row(year=2013, Java=30000, dotNET=48000)]\n >>> df5.groupBy(\"sales.year\").pivot(\"sales.course\").sum(\"sales.earnings\").collect()\n [Row(year=2012, Java=20000, dotNET=15000), Row(year=2013, Java=30000, dotNET=48000)]", "output": "def pivot(self, pivot_col, values=None):\n \"\"\"\n Pivots a column of the current :class:`DataFrame` and perform the specified aggregation.\n There are two versions of pivot function: one that requires the caller to specify the list\n of distinct values to pivot on, and one that does not. The latter is more concise but less\n efficient, because Spark needs to first compute the list of distinct values internally.\n\n :param pivot_col: Name of the column to pivot.\n :param values: List of values that will be translated to columns in the output DataFrame.\n\n # Compute the sum of earnings for each year by course with each course as a separate column\n\n >>> df4.groupBy(\"year\").pivot(\"course\", [\"dotNET\", \"Java\"]).sum(\"earnings\").collect()\n [Row(year=2012, dotNET=15000, Java=20000), Row(year=2013, dotNET=48000, Java=30000)]\n\n # Or without specifying column values (less efficient)\n\n >>> df4.groupBy(\"year\").pivot(\"course\").sum(\"earnings\").collect()\n [Row(year=2012, Java=20000, dotNET=15000), Row(year=2013, Java=30000, dotNET=48000)]\n >>> df5.groupBy(\"sales.year\").pivot(\"sales.course\").sum(\"sales.earnings\").collect()\n [Row(year=2012, Java=20000, dotNET=15000), Row(year=2013, Java=30000, dotNET=48000)]\n \"\"\"\n if values is None:\n jgd = self._jgd.pivot(pivot_col)\n else:\n jgd = self._jgd.pivot(pivot_col, values)\n return GroupedData(jgd, self._df)" }, { "instruction": "Write or improve a Python function based on this description:\n\nMaps each group of the current :class:`DataFrame` using a pandas udf and returns the result\n as a `DataFrame`.\n\n The user-defined function should take a `pandas.DataFrame` and return another\n `pandas.DataFrame`. For each group, all columns are passed together as a `pandas.DataFrame`\n to the user-function and the returned `pandas.DataFrame` are combined as a\n :class:`DataFrame`.\n\n The returned `pandas.DataFrame` can be of arbitrary length and its schema must match the\n returnType of the pandas udf.\n\n .. note:: This function requires a full shuffle. all the data of a group will be loaded\n into memory, so the user should be aware of the potential OOM risk if data is skewed\n and certain groups are too large to fit in memory.\n\n .. note:: Experimental\n\n :param udf: a grouped map user-defined function returned by\n :func:`pyspark.sql.functions.pandas_udf`.\n\n >>> from pyspark.sql.functions import pandas_udf, PandasUDFType\n >>> df = spark.createDataFrame(\n ... [(1, 1.0), (1, 2.0), (2, 3.0), (2, 5.0), (2, 10.0)],\n ... (\"id\", \"v\"))\n >>> @pandas_udf(\"id long, v double\", PandasUDFType.GROUPED_MAP) # doctest: +SKIP\n ... def normalize(pdf):\n ... v = pdf.v\n ... return pdf.assign(v=(v - v.mean()) / v.std())\n >>> df.groupby(\"id\").apply(normalize).show() # doctest: +SKIP\n +---+-------------------+\n | id| v|\n +---+-------------------+\n | 1|-0.7071067811865475|\n | 1| 0.7071067811865475|\n | 2|-0.8320502943378437|\n | 2|-0.2773500981126146|\n | 2| 1.1094003924504583|\n +---+-------------------+\n\n .. seealso:: :meth:`pyspark.sql.functions.pandas_udf`", "output": "def apply(self, udf):\n \"\"\"\n Maps each group of the current :class:`DataFrame` using a pandas udf and returns the result\n as a `DataFrame`.\n\n The user-defined function should take a `pandas.DataFrame` and return another\n `pandas.DataFrame`. For each group, all columns are passed together as a `pandas.DataFrame`\n to the user-function and the returned `pandas.DataFrame` are combined as a\n :class:`DataFrame`.\n\n The returned `pandas.DataFrame` can be of arbitrary length and its schema must match the\n returnType of the pandas udf.\n\n .. note:: This function requires a full shuffle. all the data of a group will be loaded\n into memory, so the user should be aware of the potential OOM risk if data is skewed\n and certain groups are too large to fit in memory.\n\n .. note:: Experimental\n\n :param udf: a grouped map user-defined function returned by\n :func:`pyspark.sql.functions.pandas_udf`.\n\n >>> from pyspark.sql.functions import pandas_udf, PandasUDFType\n >>> df = spark.createDataFrame(\n ... [(1, 1.0), (1, 2.0), (2, 3.0), (2, 5.0), (2, 10.0)],\n ... (\"id\", \"v\"))\n >>> @pandas_udf(\"id long, v double\", PandasUDFType.GROUPED_MAP) # doctest: +SKIP\n ... def normalize(pdf):\n ... v = pdf.v\n ... return pdf.assign(v=(v - v.mean()) / v.std())\n >>> df.groupby(\"id\").apply(normalize).show() # doctest: +SKIP\n +---+-------------------+\n | id| v|\n +---+-------------------+\n | 1|-0.7071067811865475|\n | 1| 0.7071067811865475|\n | 2|-0.8320502943378437|\n | 2|-0.2773500981126146|\n | 2| 1.1094003924504583|\n +---+-------------------+\n\n .. seealso:: :meth:`pyspark.sql.functions.pandas_udf`\n\n \"\"\"\n # Columns are special because hasattr always return True\n if isinstance(udf, Column) or not hasattr(udf, 'func') \\\n or udf.evalType != PythonEvalType.SQL_GROUPED_MAP_PANDAS_UDF:\n raise ValueError(\"Invalid udf: the udf argument must be a pandas_udf of type \"\n \"GROUPED_MAP.\")\n df = self._df\n udf_column = udf(*[df[col] for col in df.columns])\n jdf = self._jgd.flatMapGroupsInPandas(udf_column._jc.expr())\n return DataFrame(jdf, self.sql_ctx)" }, { "instruction": "Write or improve a Python function based on this description:\n\nCreates a :class:`WindowSpec` with the partitioning defined.", "output": "def partitionBy(*cols):\n \"\"\"\n Creates a :class:`WindowSpec` with the partitioning defined.\n \"\"\"\n sc = SparkContext._active_spark_context\n jspec = sc._jvm.org.apache.spark.sql.expressions.Window.partitionBy(_to_java_cols(cols))\n return WindowSpec(jspec)" }, { "instruction": "Write or improve a Python function based on this description:\n\nCreates a :class:`WindowSpec` with the frame boundaries defined,\n from `start` (inclusive) to `end` (inclusive).\n\n Both `start` and `end` are relative positions from the current row.\n For example, \"0\" means \"current row\", while \"-1\" means the row before\n the current row, and \"5\" means the fifth row after the current row.\n\n We recommend users use ``Window.unboundedPreceding``, ``Window.unboundedFollowing``,\n and ``Window.currentRow`` to specify special boundary values, rather than using integral\n values directly.\n\n A row based boundary is based on the position of the row within the partition.\n An offset indicates the number of rows above or below the current row, the frame for the\n current row starts or ends. For instance, given a row based sliding frame with a lower bound\n offset of -1 and a upper bound offset of +2. The frame for row with index 5 would range from\n index 4 to index 6.\n\n >>> from pyspark.sql import Window\n >>> from pyspark.sql import functions as func\n >>> from pyspark.sql import SQLContext\n >>> sc = SparkContext.getOrCreate()\n >>> sqlContext = SQLContext(sc)\n >>> tup = [(1, \"a\"), (1, \"a\"), (2, \"a\"), (1, \"b\"), (2, \"b\"), (3, \"b\")]\n >>> df = sqlContext.createDataFrame(tup, [\"id\", \"category\"])\n >>> window = Window.partitionBy(\"category\").orderBy(\"id\").rowsBetween(Window.currentRow, 1)\n >>> df.withColumn(\"sum\", func.sum(\"id\").over(window)).show()\n +---+--------+---+\n | id|category|sum|\n +---+--------+---+\n | 1| b| 3|\n | 2| b| 5|\n | 3| b| 3|\n | 1| a| 2|\n | 1| a| 3|\n | 2| a| 2|\n +---+--------+---+\n\n :param start: boundary start, inclusive.\n The frame is unbounded if this is ``Window.unboundedPreceding``, or\n any value less than or equal to -9223372036854775808.\n :param end: boundary end, inclusive.\n The frame is unbounded if this is ``Window.unboundedFollowing``, or\n any value greater than or equal to 9223372036854775807.", "output": "def rowsBetween(start, end):\n \"\"\"\n Creates a :class:`WindowSpec` with the frame boundaries defined,\n from `start` (inclusive) to `end` (inclusive).\n\n Both `start` and `end` are relative positions from the current row.\n For example, \"0\" means \"current row\", while \"-1\" means the row before\n the current row, and \"5\" means the fifth row after the current row.\n\n We recommend users use ``Window.unboundedPreceding``, ``Window.unboundedFollowing``,\n and ``Window.currentRow`` to specify special boundary values, rather than using integral\n values directly.\n\n A row based boundary is based on the position of the row within the partition.\n An offset indicates the number of rows above or below the current row, the frame for the\n current row starts or ends. For instance, given a row based sliding frame with a lower bound\n offset of -1 and a upper bound offset of +2. The frame for row with index 5 would range from\n index 4 to index 6.\n\n >>> from pyspark.sql import Window\n >>> from pyspark.sql import functions as func\n >>> from pyspark.sql import SQLContext\n >>> sc = SparkContext.getOrCreate()\n >>> sqlContext = SQLContext(sc)\n >>> tup = [(1, \"a\"), (1, \"a\"), (2, \"a\"), (1, \"b\"), (2, \"b\"), (3, \"b\")]\n >>> df = sqlContext.createDataFrame(tup, [\"id\", \"category\"])\n >>> window = Window.partitionBy(\"category\").orderBy(\"id\").rowsBetween(Window.currentRow, 1)\n >>> df.withColumn(\"sum\", func.sum(\"id\").over(window)).show()\n +---+--------+---+\n | id|category|sum|\n +---+--------+---+\n | 1| b| 3|\n | 2| b| 5|\n | 3| b| 3|\n | 1| a| 2|\n | 1| a| 3|\n | 2| a| 2|\n +---+--------+---+\n\n :param start: boundary start, inclusive.\n The frame is unbounded if this is ``Window.unboundedPreceding``, or\n any value less than or equal to -9223372036854775808.\n :param end: boundary end, inclusive.\n The frame is unbounded if this is ``Window.unboundedFollowing``, or\n any value greater than or equal to 9223372036854775807.\n \"\"\"\n if start <= Window._PRECEDING_THRESHOLD:\n start = Window.unboundedPreceding\n if end >= Window._FOLLOWING_THRESHOLD:\n end = Window.unboundedFollowing\n sc = SparkContext._active_spark_context\n jspec = sc._jvm.org.apache.spark.sql.expressions.Window.rowsBetween(start, end)\n return WindowSpec(jspec)" }, { "instruction": "Write or improve a Python function based on this description:\n\nDefines the frame boundaries, from `start` (inclusive) to `end` (inclusive).\n\n Both `start` and `end` are relative positions from the current row.\n For example, \"0\" means \"current row\", while \"-1\" means the row before\n the current row, and \"5\" means the fifth row after the current row.\n\n We recommend users use ``Window.unboundedPreceding``, ``Window.unboundedFollowing``,\n and ``Window.currentRow`` to specify special boundary values, rather than using integral\n values directly.\n\n :param start: boundary start, inclusive.\n The frame is unbounded if this is ``Window.unboundedPreceding``, or\n any value less than or equal to max(-sys.maxsize, -9223372036854775808).\n :param end: boundary end, inclusive.\n The frame is unbounded if this is ``Window.unboundedFollowing``, or\n any value greater than or equal to min(sys.maxsize, 9223372036854775807).", "output": "def rowsBetween(self, start, end):\n \"\"\"\n Defines the frame boundaries, from `start` (inclusive) to `end` (inclusive).\n\n Both `start` and `end` are relative positions from the current row.\n For example, \"0\" means \"current row\", while \"-1\" means the row before\n the current row, and \"5\" means the fifth row after the current row.\n\n We recommend users use ``Window.unboundedPreceding``, ``Window.unboundedFollowing``,\n and ``Window.currentRow`` to specify special boundary values, rather than using integral\n values directly.\n\n :param start: boundary start, inclusive.\n The frame is unbounded if this is ``Window.unboundedPreceding``, or\n any value less than or equal to max(-sys.maxsize, -9223372036854775808).\n :param end: boundary end, inclusive.\n The frame is unbounded if this is ``Window.unboundedFollowing``, or\n any value greater than or equal to min(sys.maxsize, 9223372036854775807).\n \"\"\"\n if start <= Window._PRECEDING_THRESHOLD:\n start = Window.unboundedPreceding\n if end >= Window._FOLLOWING_THRESHOLD:\n end = Window.unboundedFollowing\n return WindowSpec(self._jspec.rowsBetween(start, end))" }, { "instruction": "Write or improve a Python function based on this description:\n\nGenerates an RDD comprised of i.i.d. samples from the\n uniform distribution U(0.0, 1.0).\n\n To transform the distribution in the generated RDD from U(0.0, 1.0)\n to U(a, b), use\n C{RandomRDDs.uniformRDD(sc, n, p, seed)\\\n .map(lambda v: a + (b - a) * v)}\n\n :param sc: SparkContext used to create the RDD.\n :param size: Size of the RDD.\n :param numPartitions: Number of partitions in the RDD (default: `sc.defaultParallelism`).\n :param seed: Random seed (default: a random long integer).\n :return: RDD of float comprised of i.i.d. samples ~ `U(0.0, 1.0)`.\n\n >>> x = RandomRDDs.uniformRDD(sc, 100).collect()\n >>> len(x)\n 100\n >>> max(x) <= 1.0 and min(x) >= 0.0\n True\n >>> RandomRDDs.uniformRDD(sc, 100, 4).getNumPartitions()\n 4\n >>> parts = RandomRDDs.uniformRDD(sc, 100, seed=4).getNumPartitions()\n >>> parts == sc.defaultParallelism\n True", "output": "def uniformRDD(sc, size, numPartitions=None, seed=None):\n \"\"\"\n Generates an RDD comprised of i.i.d. samples from the\n uniform distribution U(0.0, 1.0).\n\n To transform the distribution in the generated RDD from U(0.0, 1.0)\n to U(a, b), use\n C{RandomRDDs.uniformRDD(sc, n, p, seed)\\\n .map(lambda v: a + (b - a) * v)}\n\n :param sc: SparkContext used to create the RDD.\n :param size: Size of the RDD.\n :param numPartitions: Number of partitions in the RDD (default: `sc.defaultParallelism`).\n :param seed: Random seed (default: a random long integer).\n :return: RDD of float comprised of i.i.d. samples ~ `U(0.0, 1.0)`.\n\n >>> x = RandomRDDs.uniformRDD(sc, 100).collect()\n >>> len(x)\n 100\n >>> max(x) <= 1.0 and min(x) >= 0.0\n True\n >>> RandomRDDs.uniformRDD(sc, 100, 4).getNumPartitions()\n 4\n >>> parts = RandomRDDs.uniformRDD(sc, 100, seed=4).getNumPartitions()\n >>> parts == sc.defaultParallelism\n True\n \"\"\"\n return callMLlibFunc(\"uniformRDD\", sc._jsc, size, numPartitions, seed)" }, { "instruction": "Write or improve a Python function based on this description:\n\nGenerates an RDD comprised of i.i.d. samples from the standard normal\n distribution.\n\n To transform the distribution in the generated RDD from standard normal\n to some other normal N(mean, sigma^2), use\n C{RandomRDDs.normal(sc, n, p, seed)\\\n .map(lambda v: mean + sigma * v)}\n\n :param sc: SparkContext used to create the RDD.\n :param size: Size of the RDD.\n :param numPartitions: Number of partitions in the RDD (default: `sc.defaultParallelism`).\n :param seed: Random seed (default: a random long integer).\n :return: RDD of float comprised of i.i.d. samples ~ N(0.0, 1.0).\n\n >>> x = RandomRDDs.normalRDD(sc, 1000, seed=1)\n >>> stats = x.stats()\n >>> stats.count()\n 1000\n >>> abs(stats.mean() - 0.0) < 0.1\n True\n >>> abs(stats.stdev() - 1.0) < 0.1\n True", "output": "def normalRDD(sc, size, numPartitions=None, seed=None):\n \"\"\"\n Generates an RDD comprised of i.i.d. samples from the standard normal\n distribution.\n\n To transform the distribution in the generated RDD from standard normal\n to some other normal N(mean, sigma^2), use\n C{RandomRDDs.normal(sc, n, p, seed)\\\n .map(lambda v: mean + sigma * v)}\n\n :param sc: SparkContext used to create the RDD.\n :param size: Size of the RDD.\n :param numPartitions: Number of partitions in the RDD (default: `sc.defaultParallelism`).\n :param seed: Random seed (default: a random long integer).\n :return: RDD of float comprised of i.i.d. samples ~ N(0.0, 1.0).\n\n >>> x = RandomRDDs.normalRDD(sc, 1000, seed=1)\n >>> stats = x.stats()\n >>> stats.count()\n 1000\n >>> abs(stats.mean() - 0.0) < 0.1\n True\n >>> abs(stats.stdev() - 1.0) < 0.1\n True\n \"\"\"\n return callMLlibFunc(\"normalRDD\", sc._jsc, size, numPartitions, seed)" }, { "instruction": "Write or improve a Python function based on this description:\n\nGenerates an RDD comprised of i.i.d. samples from the log normal\n distribution with the input mean and standard distribution.\n\n :param sc: SparkContext used to create the RDD.\n :param mean: mean for the log Normal distribution\n :param std: std for the log Normal distribution\n :param size: Size of the RDD.\n :param numPartitions: Number of partitions in the RDD (default: `sc.defaultParallelism`).\n :param seed: Random seed (default: a random long integer).\n :return: RDD of float comprised of i.i.d. samples ~ log N(mean, std).\n\n >>> from math import sqrt, exp\n >>> mean = 0.0\n >>> std = 1.0\n >>> expMean = exp(mean + 0.5 * std * std)\n >>> expStd = sqrt((exp(std * std) - 1.0) * exp(2.0 * mean + std * std))\n >>> x = RandomRDDs.logNormalRDD(sc, mean, std, 1000, seed=2)\n >>> stats = x.stats()\n >>> stats.count()\n 1000\n >>> abs(stats.mean() - expMean) < 0.5\n True\n >>> from math import sqrt\n >>> abs(stats.stdev() - expStd) < 0.5\n True", "output": "def logNormalRDD(sc, mean, std, size, numPartitions=None, seed=None):\n \"\"\"\n Generates an RDD comprised of i.i.d. samples from the log normal\n distribution with the input mean and standard distribution.\n\n :param sc: SparkContext used to create the RDD.\n :param mean: mean for the log Normal distribution\n :param std: std for the log Normal distribution\n :param size: Size of the RDD.\n :param numPartitions: Number of partitions in the RDD (default: `sc.defaultParallelism`).\n :param seed: Random seed (default: a random long integer).\n :return: RDD of float comprised of i.i.d. samples ~ log N(mean, std).\n\n >>> from math import sqrt, exp\n >>> mean = 0.0\n >>> std = 1.0\n >>> expMean = exp(mean + 0.5 * std * std)\n >>> expStd = sqrt((exp(std * std) - 1.0) * exp(2.0 * mean + std * std))\n >>> x = RandomRDDs.logNormalRDD(sc, mean, std, 1000, seed=2)\n >>> stats = x.stats()\n >>> stats.count()\n 1000\n >>> abs(stats.mean() - expMean) < 0.5\n True\n >>> from math import sqrt\n >>> abs(stats.stdev() - expStd) < 0.5\n True\n \"\"\"\n return callMLlibFunc(\"logNormalRDD\", sc._jsc, float(mean), float(std),\n size, numPartitions, seed)" }, { "instruction": "Write or improve a Python function based on this description:\n\nGenerates an RDD comprised of i.i.d. samples from the Exponential\n distribution with the input mean.\n\n :param sc: SparkContext used to create the RDD.\n :param mean: Mean, or 1 / lambda, for the Exponential distribution.\n :param size: Size of the RDD.\n :param numPartitions: Number of partitions in the RDD (default: `sc.defaultParallelism`).\n :param seed: Random seed (default: a random long integer).\n :return: RDD of float comprised of i.i.d. samples ~ Exp(mean).\n\n >>> mean = 2.0\n >>> x = RandomRDDs.exponentialRDD(sc, mean, 1000, seed=2)\n >>> stats = x.stats()\n >>> stats.count()\n 1000\n >>> abs(stats.mean() - mean) < 0.5\n True\n >>> from math import sqrt\n >>> abs(stats.stdev() - sqrt(mean)) < 0.5\n True", "output": "def exponentialRDD(sc, mean, size, numPartitions=None, seed=None):\n \"\"\"\n Generates an RDD comprised of i.i.d. samples from the Exponential\n distribution with the input mean.\n\n :param sc: SparkContext used to create the RDD.\n :param mean: Mean, or 1 / lambda, for the Exponential distribution.\n :param size: Size of the RDD.\n :param numPartitions: Number of partitions in the RDD (default: `sc.defaultParallelism`).\n :param seed: Random seed (default: a random long integer).\n :return: RDD of float comprised of i.i.d. samples ~ Exp(mean).\n\n >>> mean = 2.0\n >>> x = RandomRDDs.exponentialRDD(sc, mean, 1000, seed=2)\n >>> stats = x.stats()\n >>> stats.count()\n 1000\n >>> abs(stats.mean() - mean) < 0.5\n True\n >>> from math import sqrt\n >>> abs(stats.stdev() - sqrt(mean)) < 0.5\n True\n \"\"\"\n return callMLlibFunc(\"exponentialRDD\", sc._jsc, float(mean), size, numPartitions, seed)" }, { "instruction": "Write or improve a Python function based on this description:\n\nGenerates an RDD comprised of i.i.d. samples from the Gamma\n distribution with the input shape and scale.\n\n :param sc: SparkContext used to create the RDD.\n :param shape: shape (> 0) parameter for the Gamma distribution\n :param scale: scale (> 0) parameter for the Gamma distribution\n :param size: Size of the RDD.\n :param numPartitions: Number of partitions in the RDD (default: `sc.defaultParallelism`).\n :param seed: Random seed (default: a random long integer).\n :return: RDD of float comprised of i.i.d. samples ~ Gamma(shape, scale).\n\n >>> from math import sqrt\n >>> shape = 1.0\n >>> scale = 2.0\n >>> expMean = shape * scale\n >>> expStd = sqrt(shape * scale * scale)\n >>> x = RandomRDDs.gammaRDD(sc, shape, scale, 1000, seed=2)\n >>> stats = x.stats()\n >>> stats.count()\n 1000\n >>> abs(stats.mean() - expMean) < 0.5\n True\n >>> abs(stats.stdev() - expStd) < 0.5\n True", "output": "def gammaRDD(sc, shape, scale, size, numPartitions=None, seed=None):\n \"\"\"\n Generates an RDD comprised of i.i.d. samples from the Gamma\n distribution with the input shape and scale.\n\n :param sc: SparkContext used to create the RDD.\n :param shape: shape (> 0) parameter for the Gamma distribution\n :param scale: scale (> 0) parameter for the Gamma distribution\n :param size: Size of the RDD.\n :param numPartitions: Number of partitions in the RDD (default: `sc.defaultParallelism`).\n :param seed: Random seed (default: a random long integer).\n :return: RDD of float comprised of i.i.d. samples ~ Gamma(shape, scale).\n\n >>> from math import sqrt\n >>> shape = 1.0\n >>> scale = 2.0\n >>> expMean = shape * scale\n >>> expStd = sqrt(shape * scale * scale)\n >>> x = RandomRDDs.gammaRDD(sc, shape, scale, 1000, seed=2)\n >>> stats = x.stats()\n >>> stats.count()\n 1000\n >>> abs(stats.mean() - expMean) < 0.5\n True\n >>> abs(stats.stdev() - expStd) < 0.5\n True\n \"\"\"\n return callMLlibFunc(\"gammaRDD\", sc._jsc, float(shape),\n float(scale), size, numPartitions, seed)" }, { "instruction": "Write or improve a Python function based on this description:\n\nGenerates an RDD comprised of vectors containing i.i.d. samples drawn\n from the uniform distribution U(0.0, 1.0).\n\n :param sc: SparkContext used to create the RDD.\n :param numRows: Number of Vectors in the RDD.\n :param numCols: Number of elements in each Vector.\n :param numPartitions: Number of partitions in the RDD.\n :param seed: Seed for the RNG that generates the seed for the generator in each partition.\n :return: RDD of Vector with vectors containing i.i.d samples ~ `U(0.0, 1.0)`.\n\n >>> import numpy as np\n >>> mat = np.matrix(RandomRDDs.uniformVectorRDD(sc, 10, 10).collect())\n >>> mat.shape\n (10, 10)\n >>> mat.max() <= 1.0 and mat.min() >= 0.0\n True\n >>> RandomRDDs.uniformVectorRDD(sc, 10, 10, 4).getNumPartitions()\n 4", "output": "def uniformVectorRDD(sc, numRows, numCols, numPartitions=None, seed=None):\n \"\"\"\n Generates an RDD comprised of vectors containing i.i.d. samples drawn\n from the uniform distribution U(0.0, 1.0).\n\n :param sc: SparkContext used to create the RDD.\n :param numRows: Number of Vectors in the RDD.\n :param numCols: Number of elements in each Vector.\n :param numPartitions: Number of partitions in the RDD.\n :param seed: Seed for the RNG that generates the seed for the generator in each partition.\n :return: RDD of Vector with vectors containing i.i.d samples ~ `U(0.0, 1.0)`.\n\n >>> import numpy as np\n >>> mat = np.matrix(RandomRDDs.uniformVectorRDD(sc, 10, 10).collect())\n >>> mat.shape\n (10, 10)\n >>> mat.max() <= 1.0 and mat.min() >= 0.0\n True\n >>> RandomRDDs.uniformVectorRDD(sc, 10, 10, 4).getNumPartitions()\n 4\n \"\"\"\n return callMLlibFunc(\"uniformVectorRDD\", sc._jsc, numRows, numCols, numPartitions, seed)" }, { "instruction": "Write or improve a Python function based on this description:\n\nGenerates an RDD comprised of vectors containing i.i.d. samples drawn\n from the standard normal distribution.\n\n :param sc: SparkContext used to create the RDD.\n :param numRows: Number of Vectors in the RDD.\n :param numCols: Number of elements in each Vector.\n :param numPartitions: Number of partitions in the RDD (default: `sc.defaultParallelism`).\n :param seed: Random seed (default: a random long integer).\n :return: RDD of Vector with vectors containing i.i.d. samples ~ `N(0.0, 1.0)`.\n\n >>> import numpy as np\n >>> mat = np.matrix(RandomRDDs.normalVectorRDD(sc, 100, 100, seed=1).collect())\n >>> mat.shape\n (100, 100)\n >>> abs(mat.mean() - 0.0) < 0.1\n True\n >>> abs(mat.std() - 1.0) < 0.1\n True", "output": "def normalVectorRDD(sc, numRows, numCols, numPartitions=None, seed=None):\n \"\"\"\n Generates an RDD comprised of vectors containing i.i.d. samples drawn\n from the standard normal distribution.\n\n :param sc: SparkContext used to create the RDD.\n :param numRows: Number of Vectors in the RDD.\n :param numCols: Number of elements in each Vector.\n :param numPartitions: Number of partitions in the RDD (default: `sc.defaultParallelism`).\n :param seed: Random seed (default: a random long integer).\n :return: RDD of Vector with vectors containing i.i.d. samples ~ `N(0.0, 1.0)`.\n\n >>> import numpy as np\n >>> mat = np.matrix(RandomRDDs.normalVectorRDD(sc, 100, 100, seed=1).collect())\n >>> mat.shape\n (100, 100)\n >>> abs(mat.mean() - 0.0) < 0.1\n True\n >>> abs(mat.std() - 1.0) < 0.1\n True\n \"\"\"\n return callMLlibFunc(\"normalVectorRDD\", sc._jsc, numRows, numCols, numPartitions, seed)" }, { "instruction": "Write or improve a Python function based on this description:\n\nGenerates an RDD comprised of vectors containing i.i.d. samples drawn\n from the log normal distribution.\n\n :param sc: SparkContext used to create the RDD.\n :param mean: Mean of the log normal distribution\n :param std: Standard Deviation of the log normal distribution\n :param numRows: Number of Vectors in the RDD.\n :param numCols: Number of elements in each Vector.\n :param numPartitions: Number of partitions in the RDD (default: `sc.defaultParallelism`).\n :param seed: Random seed (default: a random long integer).\n :return: RDD of Vector with vectors containing i.i.d. samples ~ log `N(mean, std)`.\n\n >>> import numpy as np\n >>> from math import sqrt, exp\n >>> mean = 0.0\n >>> std = 1.0\n >>> expMean = exp(mean + 0.5 * std * std)\n >>> expStd = sqrt((exp(std * std) - 1.0) * exp(2.0 * mean + std * std))\n >>> m = RandomRDDs.logNormalVectorRDD(sc, mean, std, 100, 100, seed=1).collect()\n >>> mat = np.matrix(m)\n >>> mat.shape\n (100, 100)\n >>> abs(mat.mean() - expMean) < 0.1\n True\n >>> abs(mat.std() - expStd) < 0.1\n True", "output": "def logNormalVectorRDD(sc, mean, std, numRows, numCols, numPartitions=None, seed=None):\n \"\"\"\n Generates an RDD comprised of vectors containing i.i.d. samples drawn\n from the log normal distribution.\n\n :param sc: SparkContext used to create the RDD.\n :param mean: Mean of the log normal distribution\n :param std: Standard Deviation of the log normal distribution\n :param numRows: Number of Vectors in the RDD.\n :param numCols: Number of elements in each Vector.\n :param numPartitions: Number of partitions in the RDD (default: `sc.defaultParallelism`).\n :param seed: Random seed (default: a random long integer).\n :return: RDD of Vector with vectors containing i.i.d. samples ~ log `N(mean, std)`.\n\n >>> import numpy as np\n >>> from math import sqrt, exp\n >>> mean = 0.0\n >>> std = 1.0\n >>> expMean = exp(mean + 0.5 * std * std)\n >>> expStd = sqrt((exp(std * std) - 1.0) * exp(2.0 * mean + std * std))\n >>> m = RandomRDDs.logNormalVectorRDD(sc, mean, std, 100, 100, seed=1).collect()\n >>> mat = np.matrix(m)\n >>> mat.shape\n (100, 100)\n >>> abs(mat.mean() - expMean) < 0.1\n True\n >>> abs(mat.std() - expStd) < 0.1\n True\n \"\"\"\n return callMLlibFunc(\"logNormalVectorRDD\", sc._jsc, float(mean), float(std),\n numRows, numCols, numPartitions, seed)" }, { "instruction": "Write or improve a Python function based on this description:\n\nGenerates an RDD comprised of vectors containing i.i.d. samples drawn\n from the Poisson distribution with the input mean.\n\n :param sc: SparkContext used to create the RDD.\n :param mean: Mean, or lambda, for the Poisson distribution.\n :param numRows: Number of Vectors in the RDD.\n :param numCols: Number of elements in each Vector.\n :param numPartitions: Number of partitions in the RDD (default: `sc.defaultParallelism`)\n :param seed: Random seed (default: a random long integer).\n :return: RDD of Vector with vectors containing i.i.d. samples ~ Pois(mean).\n\n >>> import numpy as np\n >>> mean = 100.0\n >>> rdd = RandomRDDs.poissonVectorRDD(sc, mean, 100, 100, seed=1)\n >>> mat = np.mat(rdd.collect())\n >>> mat.shape\n (100, 100)\n >>> abs(mat.mean() - mean) < 0.5\n True\n >>> from math import sqrt\n >>> abs(mat.std() - sqrt(mean)) < 0.5\n True", "output": "def poissonVectorRDD(sc, mean, numRows, numCols, numPartitions=None, seed=None):\n \"\"\"\n Generates an RDD comprised of vectors containing i.i.d. samples drawn\n from the Poisson distribution with the input mean.\n\n :param sc: SparkContext used to create the RDD.\n :param mean: Mean, or lambda, for the Poisson distribution.\n :param numRows: Number of Vectors in the RDD.\n :param numCols: Number of elements in each Vector.\n :param numPartitions: Number of partitions in the RDD (default: `sc.defaultParallelism`)\n :param seed: Random seed (default: a random long integer).\n :return: RDD of Vector with vectors containing i.i.d. samples ~ Pois(mean).\n\n >>> import numpy as np\n >>> mean = 100.0\n >>> rdd = RandomRDDs.poissonVectorRDD(sc, mean, 100, 100, seed=1)\n >>> mat = np.mat(rdd.collect())\n >>> mat.shape\n (100, 100)\n >>> abs(mat.mean() - mean) < 0.5\n True\n >>> from math import sqrt\n >>> abs(mat.std() - sqrt(mean)) < 0.5\n True\n \"\"\"\n return callMLlibFunc(\"poissonVectorRDD\", sc._jsc, float(mean), numRows, numCols,\n numPartitions, seed)" }, { "instruction": "Write or improve a Python function based on this description:\n\nGenerates an RDD comprised of vectors containing i.i.d. samples drawn\n from the Gamma distribution.\n\n :param sc: SparkContext used to create the RDD.\n :param shape: Shape (> 0) of the Gamma distribution\n :param scale: Scale (> 0) of the Gamma distribution\n :param numRows: Number of Vectors in the RDD.\n :param numCols: Number of elements in each Vector.\n :param numPartitions: Number of partitions in the RDD (default: `sc.defaultParallelism`).\n :param seed: Random seed (default: a random long integer).\n :return: RDD of Vector with vectors containing i.i.d. samples ~ Gamma(shape, scale).\n\n >>> import numpy as np\n >>> from math import sqrt\n >>> shape = 1.0\n >>> scale = 2.0\n >>> expMean = shape * scale\n >>> expStd = sqrt(shape * scale * scale)\n >>> mat = np.matrix(RandomRDDs.gammaVectorRDD(sc, shape, scale, 100, 100, seed=1).collect())\n >>> mat.shape\n (100, 100)\n >>> abs(mat.mean() - expMean) < 0.1\n True\n >>> abs(mat.std() - expStd) < 0.1\n True", "output": "def gammaVectorRDD(sc, shape, scale, numRows, numCols, numPartitions=None, seed=None):\n \"\"\"\n Generates an RDD comprised of vectors containing i.i.d. samples drawn\n from the Gamma distribution.\n\n :param sc: SparkContext used to create the RDD.\n :param shape: Shape (> 0) of the Gamma distribution\n :param scale: Scale (> 0) of the Gamma distribution\n :param numRows: Number of Vectors in the RDD.\n :param numCols: Number of elements in each Vector.\n :param numPartitions: Number of partitions in the RDD (default: `sc.defaultParallelism`).\n :param seed: Random seed (default: a random long integer).\n :return: RDD of Vector with vectors containing i.i.d. samples ~ Gamma(shape, scale).\n\n >>> import numpy as np\n >>> from math import sqrt\n >>> shape = 1.0\n >>> scale = 2.0\n >>> expMean = shape * scale\n >>> expStd = sqrt(shape * scale * scale)\n >>> mat = np.matrix(RandomRDDs.gammaVectorRDD(sc, shape, scale, 100, 100, seed=1).collect())\n >>> mat.shape\n (100, 100)\n >>> abs(mat.mean() - expMean) < 0.1\n True\n >>> abs(mat.std() - expStd) < 0.1\n True\n \"\"\"\n return callMLlibFunc(\"gammaVectorRDD\", sc._jsc, float(shape), float(scale),\n numRows, numCols, numPartitions, seed)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns the active SparkSession for the current thread, returned by the builder.\n >>> s = SparkSession.getActiveSession()\n >>> l = [('Alice', 1)]\n >>> rdd = s.sparkContext.parallelize(l)\n >>> df = s.createDataFrame(rdd, ['name', 'age'])\n >>> df.select(\"age\").collect()\n [Row(age=1)]", "output": "def getActiveSession(cls):\n \"\"\"\n Returns the active SparkSession for the current thread, returned by the builder.\n >>> s = SparkSession.getActiveSession()\n >>> l = [('Alice', 1)]\n >>> rdd = s.sparkContext.parallelize(l)\n >>> df = s.createDataFrame(rdd, ['name', 'age'])\n >>> df.select(\"age\").collect()\n [Row(age=1)]\n \"\"\"\n from pyspark import SparkContext\n sc = SparkContext._active_spark_context\n if sc is None:\n return None\n else:\n if sc._jvm.SparkSession.getActiveSession().isDefined():\n SparkSession(sc, sc._jvm.SparkSession.getActiveSession().get())\n return SparkSession._activeSession\n else:\n return None" }, { "instruction": "Write or improve a Python function based on this description:\n\nRuntime configuration interface for Spark.\n\n This is the interface through which the user can get and set all Spark and Hadoop\n configurations that are relevant to Spark SQL. When getting the value of a config,\n this defaults to the value set in the underlying :class:`SparkContext`, if any.", "output": "def conf(self):\n \"\"\"Runtime configuration interface for Spark.\n\n This is the interface through which the user can get and set all Spark and Hadoop\n configurations that are relevant to Spark SQL. When getting the value of a config,\n this defaults to the value set in the underlying :class:`SparkContext`, if any.\n \"\"\"\n if not hasattr(self, \"_conf\"):\n self._conf = RuntimeConfig(self._jsparkSession.conf())\n return self._conf" }, { "instruction": "Write or improve a Python function based on this description:\n\nInterface through which the user may create, drop, alter or query underlying\n databases, tables, functions etc.\n\n :return: :class:`Catalog`", "output": "def catalog(self):\n \"\"\"Interface through which the user may create, drop, alter or query underlying\n databases, tables, functions etc.\n\n :return: :class:`Catalog`\n \"\"\"\n from pyspark.sql.catalog import Catalog\n if not hasattr(self, \"_catalog\"):\n self._catalog = Catalog(self)\n return self._catalog" }, { "instruction": "Write or improve a Python function based on this description:\n\nCreate a :class:`DataFrame` with single :class:`pyspark.sql.types.LongType` column named\n ``id``, containing elements in a range from ``start`` to ``end`` (exclusive) with\n step value ``step``.\n\n :param start: the start value\n :param end: the end value (exclusive)\n :param step: the incremental step (default: 1)\n :param numPartitions: the number of partitions of the DataFrame\n :return: :class:`DataFrame`\n\n >>> spark.range(1, 7, 2).collect()\n [Row(id=1), Row(id=3), Row(id=5)]\n\n If only one argument is specified, it will be used as the end value.\n\n >>> spark.range(3).collect()\n [Row(id=0), Row(id=1), Row(id=2)]", "output": "def range(self, start, end=None, step=1, numPartitions=None):\n \"\"\"\n Create a :class:`DataFrame` with single :class:`pyspark.sql.types.LongType` column named\n ``id``, containing elements in a range from ``start`` to ``end`` (exclusive) with\n step value ``step``.\n\n :param start: the start value\n :param end: the end value (exclusive)\n :param step: the incremental step (default: 1)\n :param numPartitions: the number of partitions of the DataFrame\n :return: :class:`DataFrame`\n\n >>> spark.range(1, 7, 2).collect()\n [Row(id=1), Row(id=3), Row(id=5)]\n\n If only one argument is specified, it will be used as the end value.\n\n >>> spark.range(3).collect()\n [Row(id=0), Row(id=1), Row(id=2)]\n \"\"\"\n if numPartitions is None:\n numPartitions = self._sc.defaultParallelism\n\n if end is None:\n jdf = self._jsparkSession.range(0, int(start), int(step), int(numPartitions))\n else:\n jdf = self._jsparkSession.range(int(start), int(end), int(step), int(numPartitions))\n\n return DataFrame(jdf, self._wrapped)" }, { "instruction": "Write or improve a Python function based on this description:\n\nInfer schema from list of Row or tuple.\n\n :param data: list of Row or tuple\n :param names: list of column names\n :return: :class:`pyspark.sql.types.StructType`", "output": "def _inferSchemaFromList(self, data, names=None):\n \"\"\"\n Infer schema from list of Row or tuple.\n\n :param data: list of Row or tuple\n :param names: list of column names\n :return: :class:`pyspark.sql.types.StructType`\n \"\"\"\n if not data:\n raise ValueError(\"can not infer schema from empty dataset\")\n first = data[0]\n if type(first) is dict:\n warnings.warn(\"inferring schema from dict is deprecated,\"\n \"please use pyspark.sql.Row instead\")\n schema = reduce(_merge_type, (_infer_schema(row, names) for row in data))\n if _has_nulltype(schema):\n raise ValueError(\"Some of types cannot be determined after inferring\")\n return schema" }, { "instruction": "Write or improve a Python function based on this description:\n\nInfer schema from an RDD of Row or tuple.\n\n :param rdd: an RDD of Row or tuple\n :param samplingRatio: sampling ratio, or no sampling (default)\n :return: :class:`pyspark.sql.types.StructType`", "output": "def _inferSchema(self, rdd, samplingRatio=None, names=None):\n \"\"\"\n Infer schema from an RDD of Row or tuple.\n\n :param rdd: an RDD of Row or tuple\n :param samplingRatio: sampling ratio, or no sampling (default)\n :return: :class:`pyspark.sql.types.StructType`\n \"\"\"\n first = rdd.first()\n if not first:\n raise ValueError(\"The first row in RDD is empty, \"\n \"can not infer schema\")\n if type(first) is dict:\n warnings.warn(\"Using RDD of dict to inferSchema is deprecated. \"\n \"Use pyspark.sql.Row instead\")\n\n if samplingRatio is None:\n schema = _infer_schema(first, names=names)\n if _has_nulltype(schema):\n for row in rdd.take(100)[1:]:\n schema = _merge_type(schema, _infer_schema(row, names=names))\n if not _has_nulltype(schema):\n break\n else:\n raise ValueError(\"Some of types cannot be determined by the \"\n \"first 100 rows, please try again with sampling\")\n else:\n if samplingRatio < 0.99:\n rdd = rdd.sample(False, float(samplingRatio))\n schema = rdd.map(lambda row: _infer_schema(row, names)).reduce(_merge_type)\n return schema" }, { "instruction": "Write or improve a Python function based on this description:\n\nCreate an RDD for DataFrame from an existing RDD, returns the RDD and schema.", "output": "def _createFromRDD(self, rdd, schema, samplingRatio):\n \"\"\"\n Create an RDD for DataFrame from an existing RDD, returns the RDD and schema.\n \"\"\"\n if schema is None or isinstance(schema, (list, tuple)):\n struct = self._inferSchema(rdd, samplingRatio, names=schema)\n converter = _create_converter(struct)\n rdd = rdd.map(converter)\n if isinstance(schema, (list, tuple)):\n for i, name in enumerate(schema):\n struct.fields[i].name = name\n struct.names[i] = name\n schema = struct\n\n elif not isinstance(schema, StructType):\n raise TypeError(\"schema should be StructType or list or None, but got: %s\" % schema)\n\n # convert python objects to sql data\n rdd = rdd.map(schema.toInternal)\n return rdd, schema" }, { "instruction": "Write or improve a Python function based on this description:\n\nCreate an RDD for DataFrame from a list or pandas.DataFrame, returns\n the RDD and schema.", "output": "def _createFromLocal(self, data, schema):\n \"\"\"\n Create an RDD for DataFrame from a list or pandas.DataFrame, returns\n the RDD and schema.\n \"\"\"\n # make sure data could consumed multiple times\n if not isinstance(data, list):\n data = list(data)\n\n if schema is None or isinstance(schema, (list, tuple)):\n struct = self._inferSchemaFromList(data, names=schema)\n converter = _create_converter(struct)\n data = map(converter, data)\n if isinstance(schema, (list, tuple)):\n for i, name in enumerate(schema):\n struct.fields[i].name = name\n struct.names[i] = name\n schema = struct\n\n elif not isinstance(schema, StructType):\n raise TypeError(\"schema should be StructType or list or None, but got: %s\" % schema)\n\n # convert python objects to sql data\n data = [schema.toInternal(row) for row in data]\n return self._sc.parallelize(data), schema" }, { "instruction": "Write or improve a Python function based on this description:\n\nUsed when converting a pandas.DataFrame to Spark using to_records(), this will correct\n the dtypes of fields in a record so they can be properly loaded into Spark.\n :param rec: a numpy record to check field dtypes\n :return corrected dtype for a numpy.record or None if no correction needed", "output": "def _get_numpy_record_dtype(self, rec):\n \"\"\"\n Used when converting a pandas.DataFrame to Spark using to_records(), this will correct\n the dtypes of fields in a record so they can be properly loaded into Spark.\n :param rec: a numpy record to check field dtypes\n :return corrected dtype for a numpy.record or None if no correction needed\n \"\"\"\n import numpy as np\n cur_dtypes = rec.dtype\n col_names = cur_dtypes.names\n record_type_list = []\n has_rec_fix = False\n for i in xrange(len(cur_dtypes)):\n curr_type = cur_dtypes[i]\n # If type is a datetime64 timestamp, convert to microseconds\n # NOTE: if dtype is datetime[ns] then np.record.tolist() will output values as longs,\n # conversion from [us] or lower will lead to py datetime objects, see SPARK-22417\n if curr_type == np.dtype('datetime64[ns]'):\n curr_type = 'datetime64[us]'\n has_rec_fix = True\n record_type_list.append((str(col_names[i]), curr_type))\n return np.dtype(record_type_list) if has_rec_fix else None" }, { "instruction": "Write or improve a Python function based on this description:\n\nConvert a pandas.DataFrame to list of records that can be used to make a DataFrame\n :return list of records", "output": "def _convert_from_pandas(self, pdf, schema, timezone):\n \"\"\"\n Convert a pandas.DataFrame to list of records that can be used to make a DataFrame\n :return list of records\n \"\"\"\n if timezone is not None:\n from pyspark.sql.types import _check_series_convert_timestamps_tz_local\n copied = False\n if isinstance(schema, StructType):\n for field in schema:\n # TODO: handle nested timestamps, such as ArrayType(TimestampType())?\n if isinstance(field.dataType, TimestampType):\n s = _check_series_convert_timestamps_tz_local(pdf[field.name], timezone)\n if s is not pdf[field.name]:\n if not copied:\n # Copy once if the series is modified to prevent the original\n # Pandas DataFrame from being updated\n pdf = pdf.copy()\n copied = True\n pdf[field.name] = s\n else:\n for column, series in pdf.iteritems():\n s = _check_series_convert_timestamps_tz_local(series, timezone)\n if s is not series:\n if not copied:\n # Copy once if the series is modified to prevent the original\n # Pandas DataFrame from being updated\n pdf = pdf.copy()\n copied = True\n pdf[column] = s\n\n # Convert pandas.DataFrame to list of numpy records\n np_records = pdf.to_records(index=False)\n\n # Check if any columns need to be fixed for Spark to infer properly\n if len(np_records) > 0:\n record_dtype = self._get_numpy_record_dtype(np_records[0])\n if record_dtype is not None:\n return [r.astype(record_dtype).tolist() for r in np_records]\n\n # Convert list of numpy records to python lists\n return [r.tolist() for r in np_records]" }, { "instruction": "Write or improve a Python function based on this description:\n\nCreate a DataFrame from a given pandas.DataFrame by slicing it into partitions, converting\n to Arrow data, then sending to the JVM to parallelize. If a schema is passed in, the\n data types will be used to coerce the data in Pandas to Arrow conversion.", "output": "def _create_from_pandas_with_arrow(self, pdf, schema, timezone):\n \"\"\"\n Create a DataFrame from a given pandas.DataFrame by slicing it into partitions, converting\n to Arrow data, then sending to the JVM to parallelize. If a schema is passed in, the\n data types will be used to coerce the data in Pandas to Arrow conversion.\n \"\"\"\n from pyspark.serializers import ArrowStreamPandasSerializer\n from pyspark.sql.types import from_arrow_type, to_arrow_type, TimestampType\n from pyspark.sql.utils import require_minimum_pandas_version, \\\n require_minimum_pyarrow_version\n\n require_minimum_pandas_version()\n require_minimum_pyarrow_version()\n\n from pandas.api.types import is_datetime64_dtype, is_datetime64tz_dtype\n import pyarrow as pa\n\n # Create the Spark schema from list of names passed in with Arrow types\n if isinstance(schema, (list, tuple)):\n arrow_schema = pa.Schema.from_pandas(pdf, preserve_index=False)\n struct = StructType()\n for name, field in zip(schema, arrow_schema):\n struct.add(name, from_arrow_type(field.type), nullable=field.nullable)\n schema = struct\n\n # Determine arrow types to coerce data when creating batches\n if isinstance(schema, StructType):\n arrow_types = [to_arrow_type(f.dataType) for f in schema.fields]\n elif isinstance(schema, DataType):\n raise ValueError(\"Single data type %s is not supported with Arrow\" % str(schema))\n else:\n # Any timestamps must be coerced to be compatible with Spark\n arrow_types = [to_arrow_type(TimestampType())\n if is_datetime64_dtype(t) or is_datetime64tz_dtype(t) else None\n for t in pdf.dtypes]\n\n # Slice the DataFrame to be batched\n step = -(-len(pdf) // self.sparkContext.defaultParallelism) # round int up\n pdf_slices = (pdf[start:start + step] for start in xrange(0, len(pdf), step))\n\n # Create list of Arrow (columns, type) for serializer dump_stream\n arrow_data = [[(c, t) for (_, c), t in zip(pdf_slice.iteritems(), arrow_types)]\n for pdf_slice in pdf_slices]\n\n jsqlContext = self._wrapped._jsqlContext\n\n safecheck = self._wrapped._conf.arrowSafeTypeConversion()\n col_by_name = True # col by name only applies to StructType columns, can't happen here\n ser = ArrowStreamPandasSerializer(timezone, safecheck, col_by_name)\n\n def reader_func(temp_filename):\n return self._jvm.PythonSQLUtils.readArrowStreamFromFile(jsqlContext, temp_filename)\n\n def create_RDD_server():\n return self._jvm.ArrowRDDServer(jsqlContext)\n\n # Create Spark DataFrame from Arrow stream file, using one batch per partition\n jrdd = self._sc._serialize_to_jvm(arrow_data, ser, reader_func, create_RDD_server)\n jdf = self._jvm.PythonSQLUtils.toDataFrame(jrdd, schema.json(), jsqlContext)\n df = DataFrame(jdf, self._wrapped)\n df._schema = schema\n return df" }, { "instruction": "Write or improve a Python function based on this description:\n\nInitialize a SparkSession for a pyspark shell session. This is called from shell.py\n to make error handling simpler without needing to declare local variables in that\n script, which would expose those to users.", "output": "def _create_shell_session():\n \"\"\"\n Initialize a SparkSession for a pyspark shell session. This is called from shell.py\n to make error handling simpler without needing to declare local variables in that\n script, which would expose those to users.\n \"\"\"\n import py4j\n from pyspark.conf import SparkConf\n from pyspark.context import SparkContext\n try:\n # Try to access HiveConf, it will raise exception if Hive is not added\n conf = SparkConf()\n if conf.get('spark.sql.catalogImplementation', 'hive').lower() == 'hive':\n SparkContext._jvm.org.apache.hadoop.hive.conf.HiveConf()\n return SparkSession.builder\\\n .enableHiveSupport()\\\n .getOrCreate()\n else:\n return SparkSession.builder.getOrCreate()\n except (py4j.protocol.Py4JError, TypeError):\n if conf.get('spark.sql.catalogImplementation', '').lower() == 'hive':\n warnings.warn(\"Fall back to non-hive support because failing to access HiveConf, \"\n \"please make sure you build spark with hive\")\n\n return SparkSession.builder.getOrCreate()" }, { "instruction": "Write or improve a Python function based on this description:\n\nCreates a :class:`DataFrame` from an :class:`RDD`, a list or a :class:`pandas.DataFrame`.\n\n When ``schema`` is a list of column names, the type of each column\n will be inferred from ``data``.\n\n When ``schema`` is ``None``, it will try to infer the schema (column names and types)\n from ``data``, which should be an RDD of :class:`Row`,\n or :class:`namedtuple`, or :class:`dict`.\n\n When ``schema`` is :class:`pyspark.sql.types.DataType` or a datatype string, it must match\n the real data, or an exception will be thrown at runtime. If the given schema is not\n :class:`pyspark.sql.types.StructType`, it will be wrapped into a\n :class:`pyspark.sql.types.StructType` as its only field, and the field name will be \"value\",\n each record will also be wrapped into a tuple, which can be converted to row later.\n\n If schema inference is needed, ``samplingRatio`` is used to determined the ratio of\n rows used for schema inference. The first row will be used if ``samplingRatio`` is ``None``.\n\n :param data: an RDD of any kind of SQL data representation(e.g. row, tuple, int, boolean,\n etc.), or :class:`list`, or :class:`pandas.DataFrame`.\n :param schema: a :class:`pyspark.sql.types.DataType` or a datatype string or a list of\n column names, default is ``None``. The data type string format equals to\n :class:`pyspark.sql.types.DataType.simpleString`, except that top level struct type can\n omit the ``struct<>`` and atomic types use ``typeName()`` as their format, e.g. use\n ``byte`` instead of ``tinyint`` for :class:`pyspark.sql.types.ByteType`. We can also use\n ``int`` as a short name for ``IntegerType``.\n :param samplingRatio: the sample ratio of rows used for inferring\n :param verifySchema: verify data types of every row against schema.\n :return: :class:`DataFrame`\n\n .. versionchanged:: 2.1\n Added verifySchema.\n\n .. note:: Usage with spark.sql.execution.arrow.enabled=True is experimental.\n\n >>> l = [('Alice', 1)]\n >>> spark.createDataFrame(l).collect()\n [Row(_1=u'Alice', _2=1)]\n >>> spark.createDataFrame(l, ['name', 'age']).collect()\n [Row(name=u'Alice', age=1)]\n\n >>> d = [{'name': 'Alice', 'age': 1}]\n >>> spark.createDataFrame(d).collect()\n [Row(age=1, name=u'Alice')]\n\n >>> rdd = sc.parallelize(l)\n >>> spark.createDataFrame(rdd).collect()\n [Row(_1=u'Alice', _2=1)]\n >>> df = spark.createDataFrame(rdd, ['name', 'age'])\n >>> df.collect()\n [Row(name=u'Alice', age=1)]\n\n >>> from pyspark.sql import Row\n >>> Person = Row('name', 'age')\n >>> person = rdd.map(lambda r: Person(*r))\n >>> df2 = spark.createDataFrame(person)\n >>> df2.collect()\n [Row(name=u'Alice', age=1)]\n\n >>> from pyspark.sql.types import *\n >>> schema = StructType([\n ... StructField(\"name\", StringType(), True),\n ... StructField(\"age\", IntegerType(), True)])\n >>> df3 = spark.createDataFrame(rdd, schema)\n >>> df3.collect()\n [Row(name=u'Alice', age=1)]\n\n >>> spark.createDataFrame(df.toPandas()).collect() # doctest: +SKIP\n [Row(name=u'Alice', age=1)]\n >>> spark.createDataFrame(pandas.DataFrame([[1, 2]])).collect() # doctest: +SKIP\n [Row(0=1, 1=2)]\n\n >>> spark.createDataFrame(rdd, \"a: string, b: int\").collect()\n [Row(a=u'Alice', b=1)]\n >>> rdd = rdd.map(lambda row: row[1])\n >>> spark.createDataFrame(rdd, \"int\").collect()\n [Row(value=1)]\n >>> spark.createDataFrame(rdd, \"boolean\").collect() # doctest: +IGNORE_EXCEPTION_DETAIL\n Traceback (most recent call last):\n ...\n Py4JJavaError: ...", "output": "def createDataFrame(self, data, schema=None, samplingRatio=None, verifySchema=True):\n \"\"\"\n Creates a :class:`DataFrame` from an :class:`RDD`, a list or a :class:`pandas.DataFrame`.\n\n When ``schema`` is a list of column names, the type of each column\n will be inferred from ``data``.\n\n When ``schema`` is ``None``, it will try to infer the schema (column names and types)\n from ``data``, which should be an RDD of :class:`Row`,\n or :class:`namedtuple`, or :class:`dict`.\n\n When ``schema`` is :class:`pyspark.sql.types.DataType` or a datatype string, it must match\n the real data, or an exception will be thrown at runtime. If the given schema is not\n :class:`pyspark.sql.types.StructType`, it will be wrapped into a\n :class:`pyspark.sql.types.StructType` as its only field, and the field name will be \"value\",\n each record will also be wrapped into a tuple, which can be converted to row later.\n\n If schema inference is needed, ``samplingRatio`` is used to determined the ratio of\n rows used for schema inference. The first row will be used if ``samplingRatio`` is ``None``.\n\n :param data: an RDD of any kind of SQL data representation(e.g. row, tuple, int, boolean,\n etc.), or :class:`list`, or :class:`pandas.DataFrame`.\n :param schema: a :class:`pyspark.sql.types.DataType` or a datatype string or a list of\n column names, default is ``None``. The data type string format equals to\n :class:`pyspark.sql.types.DataType.simpleString`, except that top level struct type can\n omit the ``struct<>`` and atomic types use ``typeName()`` as their format, e.g. use\n ``byte`` instead of ``tinyint`` for :class:`pyspark.sql.types.ByteType`. We can also use\n ``int`` as a short name for ``IntegerType``.\n :param samplingRatio: the sample ratio of rows used for inferring\n :param verifySchema: verify data types of every row against schema.\n :return: :class:`DataFrame`\n\n .. versionchanged:: 2.1\n Added verifySchema.\n\n .. note:: Usage with spark.sql.execution.arrow.enabled=True is experimental.\n\n >>> l = [('Alice', 1)]\n >>> spark.createDataFrame(l).collect()\n [Row(_1=u'Alice', _2=1)]\n >>> spark.createDataFrame(l, ['name', 'age']).collect()\n [Row(name=u'Alice', age=1)]\n\n >>> d = [{'name': 'Alice', 'age': 1}]\n >>> spark.createDataFrame(d).collect()\n [Row(age=1, name=u'Alice')]\n\n >>> rdd = sc.parallelize(l)\n >>> spark.createDataFrame(rdd).collect()\n [Row(_1=u'Alice', _2=1)]\n >>> df = spark.createDataFrame(rdd, ['name', 'age'])\n >>> df.collect()\n [Row(name=u'Alice', age=1)]\n\n >>> from pyspark.sql import Row\n >>> Person = Row('name', 'age')\n >>> person = rdd.map(lambda r: Person(*r))\n >>> df2 = spark.createDataFrame(person)\n >>> df2.collect()\n [Row(name=u'Alice', age=1)]\n\n >>> from pyspark.sql.types import *\n >>> schema = StructType([\n ... StructField(\"name\", StringType(), True),\n ... StructField(\"age\", IntegerType(), True)])\n >>> df3 = spark.createDataFrame(rdd, schema)\n >>> df3.collect()\n [Row(name=u'Alice', age=1)]\n\n >>> spark.createDataFrame(df.toPandas()).collect() # doctest: +SKIP\n [Row(name=u'Alice', age=1)]\n >>> spark.createDataFrame(pandas.DataFrame([[1, 2]])).collect() # doctest: +SKIP\n [Row(0=1, 1=2)]\n\n >>> spark.createDataFrame(rdd, \"a: string, b: int\").collect()\n [Row(a=u'Alice', b=1)]\n >>> rdd = rdd.map(lambda row: row[1])\n >>> spark.createDataFrame(rdd, \"int\").collect()\n [Row(value=1)]\n >>> spark.createDataFrame(rdd, \"boolean\").collect() # doctest: +IGNORE_EXCEPTION_DETAIL\n Traceback (most recent call last):\n ...\n Py4JJavaError: ...\n \"\"\"\n SparkSession._activeSession = self\n self._jvm.SparkSession.setActiveSession(self._jsparkSession)\n if isinstance(data, DataFrame):\n raise TypeError(\"data is already a DataFrame\")\n\n if isinstance(schema, basestring):\n schema = _parse_datatype_string(schema)\n elif isinstance(schema, (list, tuple)):\n # Must re-encode any unicode strings to be consistent with StructField names\n schema = [x.encode('utf-8') if not isinstance(x, str) else x for x in schema]\n\n try:\n import pandas\n has_pandas = True\n except Exception:\n has_pandas = False\n if has_pandas and isinstance(data, pandas.DataFrame):\n from pyspark.sql.utils import require_minimum_pandas_version\n require_minimum_pandas_version()\n\n if self._wrapped._conf.pandasRespectSessionTimeZone():\n timezone = self._wrapped._conf.sessionLocalTimeZone()\n else:\n timezone = None\n\n # If no schema supplied by user then get the names of columns only\n if schema is None:\n schema = [str(x) if not isinstance(x, basestring) else\n (x.encode('utf-8') if not isinstance(x, str) else x)\n for x in data.columns]\n\n if self._wrapped._conf.arrowEnabled() and len(data) > 0:\n try:\n return self._create_from_pandas_with_arrow(data, schema, timezone)\n except Exception as e:\n from pyspark.util import _exception_message\n\n if self._wrapped._conf.arrowFallbackEnabled():\n msg = (\n \"createDataFrame attempted Arrow optimization because \"\n \"'spark.sql.execution.arrow.enabled' is set to true; however, \"\n \"failed by the reason below:\\n %s\\n\"\n \"Attempting non-optimization as \"\n \"'spark.sql.execution.arrow.fallback.enabled' is set to \"\n \"true.\" % _exception_message(e))\n warnings.warn(msg)\n else:\n msg = (\n \"createDataFrame attempted Arrow optimization because \"\n \"'spark.sql.execution.arrow.enabled' is set to true, but has reached \"\n \"the error below and will not continue because automatic fallback \"\n \"with 'spark.sql.execution.arrow.fallback.enabled' has been set to \"\n \"false.\\n %s\" % _exception_message(e))\n warnings.warn(msg)\n raise\n data = self._convert_from_pandas(data, schema, timezone)\n\n if isinstance(schema, StructType):\n verify_func = _make_type_verifier(schema) if verifySchema else lambda _: True\n\n def prepare(obj):\n verify_func(obj)\n return obj\n elif isinstance(schema, DataType):\n dataType = schema\n schema = StructType().add(\"value\", schema)\n\n verify_func = _make_type_verifier(\n dataType, name=\"field value\") if verifySchema else lambda _: True\n\n def prepare(obj):\n verify_func(obj)\n return obj,\n else:\n prepare = lambda obj: obj\n\n if isinstance(data, RDD):\n rdd, schema = self._createFromRDD(data.map(prepare), schema, samplingRatio)\n else:\n rdd, schema = self._createFromLocal(map(prepare, data), schema)\n jrdd = self._jvm.SerDeUtil.toJavaArray(rdd._to_java_object_rdd())\n jdf = self._jsparkSession.applySchemaToPythonRDD(jrdd.rdd(), schema.json())\n df = DataFrame(jdf, self._wrapped)\n df._schema = schema\n return df" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns a :class:`DataFrame` representing the result of the given query.\n\n :return: :class:`DataFrame`\n\n >>> df.createOrReplaceTempView(\"table1\")\n >>> df2 = spark.sql(\"SELECT field1 AS f1, field2 as f2 from table1\")\n >>> df2.collect()\n [Row(f1=1, f2=u'row1'), Row(f1=2, f2=u'row2'), Row(f1=3, f2=u'row3')]", "output": "def sql(self, sqlQuery):\n \"\"\"Returns a :class:`DataFrame` representing the result of the given query.\n\n :return: :class:`DataFrame`\n\n >>> df.createOrReplaceTempView(\"table1\")\n >>> df2 = spark.sql(\"SELECT field1 AS f1, field2 as f2 from table1\")\n >>> df2.collect()\n [Row(f1=1, f2=u'row1'), Row(f1=2, f2=u'row2'), Row(f1=3, f2=u'row3')]\n \"\"\"\n return DataFrame(self._jsparkSession.sql(sqlQuery), self._wrapped)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns the specified table as a :class:`DataFrame`.\n\n :return: :class:`DataFrame`\n\n >>> df.createOrReplaceTempView(\"table1\")\n >>> df2 = spark.table(\"table1\")\n >>> sorted(df.collect()) == sorted(df2.collect())\n True", "output": "def table(self, tableName):\n \"\"\"Returns the specified table as a :class:`DataFrame`.\n\n :return: :class:`DataFrame`\n\n >>> df.createOrReplaceTempView(\"table1\")\n >>> df2 = spark.table(\"table1\")\n >>> sorted(df.collect()) == sorted(df2.collect())\n True\n \"\"\"\n return DataFrame(self._jsparkSession.table(tableName), self._wrapped)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns a :class:`StreamingQueryManager` that allows managing all the\n :class:`StreamingQuery` StreamingQueries active on `this` context.\n\n .. note:: Evolving.\n\n :return: :class:`StreamingQueryManager`", "output": "def streams(self):\n \"\"\"Returns a :class:`StreamingQueryManager` that allows managing all the\n :class:`StreamingQuery` StreamingQueries active on `this` context.\n\n .. note:: Evolving.\n\n :return: :class:`StreamingQueryManager`\n \"\"\"\n from pyspark.sql.streaming import StreamingQueryManager\n return StreamingQueryManager(self._jsparkSession.streams())" }, { "instruction": "Write or improve a Python function based on this description:\n\nStop the underlying :class:`SparkContext`.", "output": "def stop(self):\n \"\"\"Stop the underlying :class:`SparkContext`.\n \"\"\"\n self._sc.stop()\n # We should clean the default session up. See SPARK-23228.\n self._jvm.SparkSession.clearDefaultSession()\n self._jvm.SparkSession.clearActiveSession()\n SparkSession._instantiatedSession = None\n SparkSession._activeSession = None" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns a :class:`SparkJobInfo` object, or None if the job info\n could not be found or was garbage collected.", "output": "def getJobInfo(self, jobId):\n \"\"\"\n Returns a :class:`SparkJobInfo` object, or None if the job info\n could not be found or was garbage collected.\n \"\"\"\n job = self._jtracker.getJobInfo(jobId)\n if job is not None:\n return SparkJobInfo(jobId, job.stageIds(), str(job.status()))" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns a :class:`SparkStageInfo` object, or None if the stage\n info could not be found or was garbage collected.", "output": "def getStageInfo(self, stageId):\n \"\"\"\n Returns a :class:`SparkStageInfo` object, or None if the stage\n info could not be found or was garbage collected.\n \"\"\"\n stage = self._jtracker.getStageInfo(stageId)\n if stage is not None:\n # TODO: fetch them in batch for better performance\n attrs = [getattr(stage, f)() for f in SparkStageInfo._fields[1:]]\n return SparkStageInfo(stageId, *attrs)" }, { "instruction": "Write or improve a Python function based on this description:\n\nRestore an object of namedtuple", "output": "def _restore(name, fields, value):\n \"\"\" Restore an object of namedtuple\"\"\"\n k = (name, fields)\n cls = __cls.get(k)\n if cls is None:\n cls = collections.namedtuple(name, fields)\n __cls[k] = cls\n return cls(*value)" }, { "instruction": "Write or improve a Python function based on this description:\n\nMake class generated by namedtuple picklable", "output": "def _hack_namedtuple(cls):\n \"\"\" Make class generated by namedtuple picklable \"\"\"\n name = cls.__name__\n fields = cls._fields\n\n def __reduce__(self):\n return (_restore, (name, fields, tuple(self)))\n cls.__reduce__ = __reduce__\n cls._is_namedtuple_ = True\n return cls" }, { "instruction": "Write or improve a Python function based on this description:\n\nHack namedtuple() to make it picklable", "output": "def _hijack_namedtuple():\n \"\"\" Hack namedtuple() to make it picklable \"\"\"\n # hijack only one time\n if hasattr(collections.namedtuple, \"__hijack\"):\n return\n\n global _old_namedtuple # or it will put in closure\n global _old_namedtuple_kwdefaults # or it will put in closure too\n\n def _copy_func(f):\n return types.FunctionType(f.__code__, f.__globals__, f.__name__,\n f.__defaults__, f.__closure__)\n\n def _kwdefaults(f):\n # __kwdefaults__ contains the default values of keyword-only arguments which are\n # introduced from Python 3. The possible cases for __kwdefaults__ in namedtuple\n # are as below:\n #\n # - Does not exist in Python 2.\n # - Returns None in <= Python 3.5.x.\n # - Returns a dictionary containing the default values to the keys from Python 3.6.x\n # (See https://bugs.python.org/issue25628).\n kargs = getattr(f, \"__kwdefaults__\", None)\n if kargs is None:\n return {}\n else:\n return kargs\n\n _old_namedtuple = _copy_func(collections.namedtuple)\n _old_namedtuple_kwdefaults = _kwdefaults(collections.namedtuple)\n\n def namedtuple(*args, **kwargs):\n for k, v in _old_namedtuple_kwdefaults.items():\n kwargs[k] = kwargs.get(k, v)\n cls = _old_namedtuple(*args, **kwargs)\n return _hack_namedtuple(cls)\n\n # replace namedtuple with the new one\n collections.namedtuple.__globals__[\"_old_namedtuple_kwdefaults\"] = _old_namedtuple_kwdefaults\n collections.namedtuple.__globals__[\"_old_namedtuple\"] = _old_namedtuple\n collections.namedtuple.__globals__[\"_hack_namedtuple\"] = _hack_namedtuple\n collections.namedtuple.__code__ = namedtuple.__code__\n collections.namedtuple.__hijack = 1\n\n # hack the cls already generated by namedtuple.\n # Those created in other modules can be pickled as normal,\n # so only hack those in __main__ module\n for n, o in sys.modules[\"__main__\"].__dict__.items():\n if (type(o) is type and o.__base__ is tuple\n and hasattr(o, \"_fields\")\n and \"__reduce__\" not in o.__dict__):\n _hack_namedtuple(o)" }, { "instruction": "Write or improve a Python function based on this description:\n\nLoad a stream of un-ordered Arrow RecordBatches, where the last iteration yields\n a list of indices that can be used to put the RecordBatches in the correct order.", "output": "def load_stream(self, stream):\n \"\"\"\n Load a stream of un-ordered Arrow RecordBatches, where the last iteration yields\n a list of indices that can be used to put the RecordBatches in the correct order.\n \"\"\"\n # load the batches\n for batch in self.serializer.load_stream(stream):\n yield batch\n\n # load the batch order indices\n num = read_int(stream)\n batch_order = []\n for i in xrange(num):\n index = read_int(stream)\n batch_order.append(index)\n yield batch_order" }, { "instruction": "Write or improve a Python function based on this description:\n\nCreate an Arrow record batch from the given pandas.Series or list of Series,\n with optional type.\n\n :param series: A single pandas.Series, list of Series, or list of (series, arrow_type)\n :return: Arrow RecordBatch", "output": "def _create_batch(self, series):\n \"\"\"\n Create an Arrow record batch from the given pandas.Series or list of Series,\n with optional type.\n\n :param series: A single pandas.Series, list of Series, or list of (series, arrow_type)\n :return: Arrow RecordBatch\n \"\"\"\n import pandas as pd\n import pyarrow as pa\n from pyspark.sql.types import _check_series_convert_timestamps_internal\n # Make input conform to [(series1, type1), (series2, type2), ...]\n if not isinstance(series, (list, tuple)) or \\\n (len(series) == 2 and isinstance(series[1], pa.DataType)):\n series = [series]\n series = ((s, None) if not isinstance(s, (list, tuple)) else s for s in series)\n\n def create_array(s, t):\n mask = s.isnull()\n # Ensure timestamp series are in expected form for Spark internal representation\n if t is not None and pa.types.is_timestamp(t):\n s = _check_series_convert_timestamps_internal(s.fillna(0), self._timezone)\n # TODO: need cast after Arrow conversion, ns values cause error with pandas 0.19.2\n return pa.Array.from_pandas(s, mask=mask).cast(t, safe=False)\n\n try:\n array = pa.Array.from_pandas(s, mask=mask, type=t, safe=self._safecheck)\n except pa.ArrowException as e:\n error_msg = \"Exception thrown when converting pandas.Series (%s) to Arrow \" + \\\n \"Array (%s). It can be caused by overflows or other unsafe \" + \\\n \"conversions warned by Arrow. Arrow safe type check can be \" + \\\n \"disabled by using SQL config \" + \\\n \"`spark.sql.execution.pandas.arrowSafeTypeConversion`.\"\n raise RuntimeError(error_msg % (s.dtype, t), e)\n return array\n\n arrs = []\n for s, t in series:\n if t is not None and pa.types.is_struct(t):\n if not isinstance(s, pd.DataFrame):\n raise ValueError(\"A field of type StructType expects a pandas.DataFrame, \"\n \"but got: %s\" % str(type(s)))\n\n # Input partition and result pandas.DataFrame empty, make empty Arrays with struct\n if len(s) == 0 and len(s.columns) == 0:\n arrs_names = [(pa.array([], type=field.type), field.name) for field in t]\n # Assign result columns by schema name if user labeled with strings\n elif self._assign_cols_by_name and any(isinstance(name, basestring)\n for name in s.columns):\n arrs_names = [(create_array(s[field.name], field.type), field.name)\n for field in t]\n # Assign result columns by position\n else:\n arrs_names = [(create_array(s[s.columns[i]], field.type), field.name)\n for i, field in enumerate(t)]\n\n struct_arrs, struct_names = zip(*arrs_names)\n arrs.append(pa.StructArray.from_arrays(struct_arrs, struct_names))\n else:\n arrs.append(create_array(s, t))\n\n return pa.RecordBatch.from_arrays(arrs, [\"_%d\" % i for i in xrange(len(arrs))])" }, { "instruction": "Write or improve a Python function based on this description:\n\nMake ArrowRecordBatches from Pandas Series and serialize. Input is a single series or\n a list of series accompanied by an optional pyarrow type to coerce the data to.", "output": "def dump_stream(self, iterator, stream):\n \"\"\"\n Make ArrowRecordBatches from Pandas Series and serialize. Input is a single series or\n a list of series accompanied by an optional pyarrow type to coerce the data to.\n \"\"\"\n batches = (self._create_batch(series) for series in iterator)\n super(ArrowStreamPandasSerializer, self).dump_stream(batches, stream)" }, { "instruction": "Write or improve a Python function based on this description:\n\nDeserialize ArrowRecordBatches to an Arrow table and return as a list of pandas.Series.", "output": "def load_stream(self, stream):\n \"\"\"\n Deserialize ArrowRecordBatches to an Arrow table and return as a list of pandas.Series.\n \"\"\"\n batches = super(ArrowStreamPandasSerializer, self).load_stream(stream)\n import pyarrow as pa\n for batch in batches:\n yield [self.arrow_to_pandas(c) for c in pa.Table.from_batches([batch]).itercolumns()]" }, { "instruction": "Write or improve a Python function based on this description:\n\nOverride because Pandas UDFs require a START_ARROW_STREAM before the Arrow stream is sent.\n This should be sent after creating the first record batch so in case of an error, it can\n be sent back to the JVM before the Arrow stream starts.", "output": "def dump_stream(self, iterator, stream):\n \"\"\"\n Override because Pandas UDFs require a START_ARROW_STREAM before the Arrow stream is sent.\n This should be sent after creating the first record batch so in case of an error, it can\n be sent back to the JVM before the Arrow stream starts.\n \"\"\"\n\n def init_stream_yield_batches():\n should_write_start_length = True\n for series in iterator:\n batch = self._create_batch(series)\n if should_write_start_length:\n write_int(SpecialLengths.START_ARROW_STREAM, stream)\n should_write_start_length = False\n yield batch\n\n return ArrowStreamSerializer.dump_stream(self, init_stream_yield_batches(), stream)" }, { "instruction": "Write or improve a Python function based on this description:\n\nWaits for the termination of `this` query, either by :func:`query.stop()` or by an\n exception. If the query has terminated with an exception, then the exception will be thrown.\n If `timeout` is set, it returns whether the query has terminated or not within the\n `timeout` seconds.\n\n If the query has terminated, then all subsequent calls to this method will either return\n immediately (if the query was terminated by :func:`stop()`), or throw the exception\n immediately (if the query has terminated with exception).\n\n throws :class:`StreamingQueryException`, if `this` query has terminated with an exception", "output": "def awaitTermination(self, timeout=None):\n \"\"\"Waits for the termination of `this` query, either by :func:`query.stop()` or by an\n exception. If the query has terminated with an exception, then the exception will be thrown.\n If `timeout` is set, it returns whether the query has terminated or not within the\n `timeout` seconds.\n\n If the query has terminated, then all subsequent calls to this method will either return\n immediately (if the query was terminated by :func:`stop()`), or throw the exception\n immediately (if the query has terminated with exception).\n\n throws :class:`StreamingQueryException`, if `this` query has terminated with an exception\n \"\"\"\n if timeout is not None:\n if not isinstance(timeout, (int, float)) or timeout < 0:\n raise ValueError(\"timeout must be a positive integer or float. Got %s\" % timeout)\n return self._jsq.awaitTermination(int(timeout * 1000))\n else:\n return self._jsq.awaitTermination()" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns an array of the most recent [[StreamingQueryProgress]] updates for this query.\n The number of progress updates retained for each stream is configured by Spark session\n configuration `spark.sql.streaming.numRecentProgressUpdates`.", "output": "def recentProgress(self):\n \"\"\"Returns an array of the most recent [[StreamingQueryProgress]] updates for this query.\n The number of progress updates retained for each stream is configured by Spark session\n configuration `spark.sql.streaming.numRecentProgressUpdates`.\n \"\"\"\n return [json.loads(p.json()) for p in self._jsq.recentProgress()]" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns the most recent :class:`StreamingQueryProgress` update of this streaming query or\n None if there were no progress updates\n :return: a map", "output": "def lastProgress(self):\n \"\"\"\n Returns the most recent :class:`StreamingQueryProgress` update of this streaming query or\n None if there were no progress updates\n :return: a map\n \"\"\"\n lastProgress = self._jsq.lastProgress()\n if lastProgress:\n return json.loads(lastProgress.json())\n else:\n return None" }, { "instruction": "Write or improve a Python function based on this description:\n\n:return: the StreamingQueryException if the query was terminated by an exception, or None.", "output": "def exception(self):\n \"\"\"\n :return: the StreamingQueryException if the query was terminated by an exception, or None.\n \"\"\"\n if self._jsq.exception().isDefined():\n je = self._jsq.exception().get()\n msg = je.toString().split(': ', 1)[1] # Drop the Java StreamingQueryException type info\n stackTrace = '\\n\\t at '.join(map(lambda x: x.toString(), je.getStackTrace()))\n return StreamingQueryException(msg, stackTrace, je.getCause())\n else:\n return None" }, { "instruction": "Write or improve a Python function based on this description:\n\nWait until any of the queries on the associated SQLContext has terminated since the\n creation of the context, or since :func:`resetTerminated()` was called. If any query was\n terminated with an exception, then the exception will be thrown.\n If `timeout` is set, it returns whether the query has terminated or not within the\n `timeout` seconds.\n\n If a query has terminated, then subsequent calls to :func:`awaitAnyTermination()` will\n either return immediately (if the query was terminated by :func:`query.stop()`),\n or throw the exception immediately (if the query was terminated with exception). Use\n :func:`resetTerminated()` to clear past terminations and wait for new terminations.\n\n In the case where multiple queries have terminated since :func:`resetTermination()`\n was called, if any query has terminated with exception, then :func:`awaitAnyTermination()`\n will throw any of the exception. For correctly documenting exceptions across multiple\n queries, users need to stop all of them after any of them terminates with exception, and\n then check the `query.exception()` for each query.\n\n throws :class:`StreamingQueryException`, if `this` query has terminated with an exception", "output": "def awaitAnyTermination(self, timeout=None):\n \"\"\"Wait until any of the queries on the associated SQLContext has terminated since the\n creation of the context, or since :func:`resetTerminated()` was called. If any query was\n terminated with an exception, then the exception will be thrown.\n If `timeout` is set, it returns whether the query has terminated or not within the\n `timeout` seconds.\n\n If a query has terminated, then subsequent calls to :func:`awaitAnyTermination()` will\n either return immediately (if the query was terminated by :func:`query.stop()`),\n or throw the exception immediately (if the query was terminated with exception). Use\n :func:`resetTerminated()` to clear past terminations and wait for new terminations.\n\n In the case where multiple queries have terminated since :func:`resetTermination()`\n was called, if any query has terminated with exception, then :func:`awaitAnyTermination()`\n will throw any of the exception. For correctly documenting exceptions across multiple\n queries, users need to stop all of them after any of them terminates with exception, and\n then check the `query.exception()` for each query.\n\n throws :class:`StreamingQueryException`, if `this` query has terminated with an exception\n \"\"\"\n if timeout is not None:\n if not isinstance(timeout, (int, float)) or timeout < 0:\n raise ValueError(\"timeout must be a positive integer or float. Got %s\" % timeout)\n return self._jsqm.awaitAnyTermination(int(timeout * 1000))\n else:\n return self._jsqm.awaitAnyTermination()" }, { "instruction": "Write or improve a Python function based on this description:\n\nLoads a data stream from a data source and returns it as a :class`DataFrame`.\n\n .. note:: Evolving.\n\n :param path: optional string for file-system backed data sources.\n :param format: optional string for format of the data source. Default to 'parquet'.\n :param schema: optional :class:`pyspark.sql.types.StructType` for the input schema\n or a DDL-formatted string (For example ``col0 INT, col1 DOUBLE``).\n :param options: all other string options\n\n >>> json_sdf = spark.readStream.format(\"json\") \\\\\n ... .schema(sdf_schema) \\\\\n ... .load(tempfile.mkdtemp())\n >>> json_sdf.isStreaming\n True\n >>> json_sdf.schema == sdf_schema\n True", "output": "def load(self, path=None, format=None, schema=None, **options):\n \"\"\"Loads a data stream from a data source and returns it as a :class`DataFrame`.\n\n .. note:: Evolving.\n\n :param path: optional string for file-system backed data sources.\n :param format: optional string for format of the data source. Default to 'parquet'.\n :param schema: optional :class:`pyspark.sql.types.StructType` for the input schema\n or a DDL-formatted string (For example ``col0 INT, col1 DOUBLE``).\n :param options: all other string options\n\n >>> json_sdf = spark.readStream.format(\"json\") \\\\\n ... .schema(sdf_schema) \\\\\n ... .load(tempfile.mkdtemp())\n >>> json_sdf.isStreaming\n True\n >>> json_sdf.schema == sdf_schema\n True\n \"\"\"\n if format is not None:\n self.format(format)\n if schema is not None:\n self.schema(schema)\n self.options(**options)\n if path is not None:\n if type(path) != str or len(path.strip()) == 0:\n raise ValueError(\"If the path is provided for stream, it needs to be a \" +\n \"non-empty string. List of paths are not supported.\")\n return self._df(self._jreader.load(path))\n else:\n return self._df(self._jreader.load())" }, { "instruction": "Write or improve a Python function based on this description:\n\nLoads a JSON file stream and returns the results as a :class:`DataFrame`.\n\n `JSON Lines `_ (newline-delimited JSON) is supported by default.\n For JSON (one record per file), set the ``multiLine`` parameter to ``true``.\n\n If the ``schema`` parameter is not specified, this function goes\n through the input once to determine the input schema.\n\n .. note:: Evolving.\n\n :param path: string represents path to the JSON dataset,\n or RDD of Strings storing JSON objects.\n :param schema: an optional :class:`pyspark.sql.types.StructType` for the input schema\n or a DDL-formatted string (For example ``col0 INT, col1 DOUBLE``).\n :param primitivesAsString: infers all primitive values as a string type. If None is set,\n it uses the default value, ``false``.\n :param prefersDecimal: infers all floating-point values as a decimal type. If the values\n do not fit in decimal, then it infers them as doubles. If None is\n set, it uses the default value, ``false``.\n :param allowComments: ignores Java/C++ style comment in JSON records. If None is set,\n it uses the default value, ``false``.\n :param allowUnquotedFieldNames: allows unquoted JSON field names. If None is set,\n it uses the default value, ``false``.\n :param allowSingleQuotes: allows single quotes in addition to double quotes. If None is\n set, it uses the default value, ``true``.\n :param allowNumericLeadingZero: allows leading zeros in numbers (e.g. 00012). If None is\n set, it uses the default value, ``false``.\n :param allowBackslashEscapingAnyCharacter: allows accepting quoting of all character\n using backslash quoting mechanism. If None is\n set, it uses the default value, ``false``.\n :param mode: allows a mode for dealing with corrupt records during parsing. If None is\n set, it uses the default value, ``PERMISSIVE``.\n\n * ``PERMISSIVE`` : when it meets a corrupted record, puts the malformed string \\\n into a field configured by ``columnNameOfCorruptRecord``, and sets malformed \\\n fields to ``null``. To keep corrupt records, an user can set a string type \\\n field named ``columnNameOfCorruptRecord`` in an user-defined schema. If a \\\n schema does not have the field, it drops corrupt records during parsing. \\\n When inferring a schema, it implicitly adds a ``columnNameOfCorruptRecord`` \\\n field in an output schema.\n * ``DROPMALFORMED`` : ignores the whole corrupted records.\n * ``FAILFAST`` : throws an exception when it meets corrupted records.\n\n :param columnNameOfCorruptRecord: allows renaming the new field having malformed string\n created by ``PERMISSIVE`` mode. This overrides\n ``spark.sql.columnNameOfCorruptRecord``. If None is set,\n it uses the value specified in\n ``spark.sql.columnNameOfCorruptRecord``.\n :param dateFormat: sets the string that indicates a date format. Custom date formats\n follow the formats at ``java.time.format.DateTimeFormatter``. This\n applies to date type. If None is set, it uses the\n default value, ``yyyy-MM-dd``.\n :param timestampFormat: sets the string that indicates a timestamp format.\n Custom date formats follow the formats at\n ``java.time.format.DateTimeFormatter``.\n This applies to timestamp type. If None is set, it uses the\n default value, ``yyyy-MM-dd'T'HH:mm:ss.SSSXXX``.\n :param multiLine: parse one record, which may span multiple lines, per file. If None is\n set, it uses the default value, ``false``.\n :param allowUnquotedControlChars: allows JSON Strings to contain unquoted control\n characters (ASCII characters with value less than 32,\n including tab and line feed characters) or not.\n :param lineSep: defines the line separator that should be used for parsing. If None is\n set, it covers all ``\\\\r``, ``\\\\r\\\\n`` and ``\\\\n``.\n :param locale: sets a locale as language tag in IETF BCP 47 format. If None is set,\n it uses the default value, ``en-US``. For instance, ``locale`` is used while\n parsing dates and timestamps.\n :param dropFieldIfAllNull: whether to ignore column of all null values or empty\n array/struct during schema inference. If None is set, it\n uses the default value, ``false``.\n :param encoding: allows to forcibly set one of standard basic or extended encoding for\n the JSON files. For example UTF-16BE, UTF-32LE. If None is set,\n the encoding of input JSON will be detected automatically\n when the multiLine option is set to ``true``.\n\n >>> json_sdf = spark.readStream.json(tempfile.mkdtemp(), schema = sdf_schema)\n >>> json_sdf.isStreaming\n True\n >>> json_sdf.schema == sdf_schema\n True", "output": "def json(self, path, schema=None, primitivesAsString=None, prefersDecimal=None,\n allowComments=None, allowUnquotedFieldNames=None, allowSingleQuotes=None,\n allowNumericLeadingZero=None, allowBackslashEscapingAnyCharacter=None,\n mode=None, columnNameOfCorruptRecord=None, dateFormat=None, timestampFormat=None,\n multiLine=None, allowUnquotedControlChars=None, lineSep=None, locale=None,\n dropFieldIfAllNull=None, encoding=None):\n \"\"\"\n Loads a JSON file stream and returns the results as a :class:`DataFrame`.\n\n `JSON Lines `_ (newline-delimited JSON) is supported by default.\n For JSON (one record per file), set the ``multiLine`` parameter to ``true``.\n\n If the ``schema`` parameter is not specified, this function goes\n through the input once to determine the input schema.\n\n .. note:: Evolving.\n\n :param path: string represents path to the JSON dataset,\n or RDD of Strings storing JSON objects.\n :param schema: an optional :class:`pyspark.sql.types.StructType` for the input schema\n or a DDL-formatted string (For example ``col0 INT, col1 DOUBLE``).\n :param primitivesAsString: infers all primitive values as a string type. If None is set,\n it uses the default value, ``false``.\n :param prefersDecimal: infers all floating-point values as a decimal type. If the values\n do not fit in decimal, then it infers them as doubles. If None is\n set, it uses the default value, ``false``.\n :param allowComments: ignores Java/C++ style comment in JSON records. If None is set,\n it uses the default value, ``false``.\n :param allowUnquotedFieldNames: allows unquoted JSON field names. If None is set,\n it uses the default value, ``false``.\n :param allowSingleQuotes: allows single quotes in addition to double quotes. If None is\n set, it uses the default value, ``true``.\n :param allowNumericLeadingZero: allows leading zeros in numbers (e.g. 00012). If None is\n set, it uses the default value, ``false``.\n :param allowBackslashEscapingAnyCharacter: allows accepting quoting of all character\n using backslash quoting mechanism. If None is\n set, it uses the default value, ``false``.\n :param mode: allows a mode for dealing with corrupt records during parsing. If None is\n set, it uses the default value, ``PERMISSIVE``.\n\n * ``PERMISSIVE`` : when it meets a corrupted record, puts the malformed string \\\n into a field configured by ``columnNameOfCorruptRecord``, and sets malformed \\\n fields to ``null``. To keep corrupt records, an user can set a string type \\\n field named ``columnNameOfCorruptRecord`` in an user-defined schema. If a \\\n schema does not have the field, it drops corrupt records during parsing. \\\n When inferring a schema, it implicitly adds a ``columnNameOfCorruptRecord`` \\\n field in an output schema.\n * ``DROPMALFORMED`` : ignores the whole corrupted records.\n * ``FAILFAST`` : throws an exception when it meets corrupted records.\n\n :param columnNameOfCorruptRecord: allows renaming the new field having malformed string\n created by ``PERMISSIVE`` mode. This overrides\n ``spark.sql.columnNameOfCorruptRecord``. If None is set,\n it uses the value specified in\n ``spark.sql.columnNameOfCorruptRecord``.\n :param dateFormat: sets the string that indicates a date format. Custom date formats\n follow the formats at ``java.time.format.DateTimeFormatter``. This\n applies to date type. If None is set, it uses the\n default value, ``yyyy-MM-dd``.\n :param timestampFormat: sets the string that indicates a timestamp format.\n Custom date formats follow the formats at\n ``java.time.format.DateTimeFormatter``.\n This applies to timestamp type. If None is set, it uses the\n default value, ``yyyy-MM-dd'T'HH:mm:ss.SSSXXX``.\n :param multiLine: parse one record, which may span multiple lines, per file. If None is\n set, it uses the default value, ``false``.\n :param allowUnquotedControlChars: allows JSON Strings to contain unquoted control\n characters (ASCII characters with value less than 32,\n including tab and line feed characters) or not.\n :param lineSep: defines the line separator that should be used for parsing. If None is\n set, it covers all ``\\\\r``, ``\\\\r\\\\n`` and ``\\\\n``.\n :param locale: sets a locale as language tag in IETF BCP 47 format. If None is set,\n it uses the default value, ``en-US``. For instance, ``locale`` is used while\n parsing dates and timestamps.\n :param dropFieldIfAllNull: whether to ignore column of all null values or empty\n array/struct during schema inference. If None is set, it\n uses the default value, ``false``.\n :param encoding: allows to forcibly set one of standard basic or extended encoding for\n the JSON files. For example UTF-16BE, UTF-32LE. If None is set,\n the encoding of input JSON will be detected automatically\n when the multiLine option is set to ``true``.\n\n >>> json_sdf = spark.readStream.json(tempfile.mkdtemp(), schema = sdf_schema)\n >>> json_sdf.isStreaming\n True\n >>> json_sdf.schema == sdf_schema\n True\n \"\"\"\n self._set_opts(\n schema=schema, primitivesAsString=primitivesAsString, prefersDecimal=prefersDecimal,\n allowComments=allowComments, allowUnquotedFieldNames=allowUnquotedFieldNames,\n allowSingleQuotes=allowSingleQuotes, allowNumericLeadingZero=allowNumericLeadingZero,\n allowBackslashEscapingAnyCharacter=allowBackslashEscapingAnyCharacter,\n mode=mode, columnNameOfCorruptRecord=columnNameOfCorruptRecord, dateFormat=dateFormat,\n timestampFormat=timestampFormat, multiLine=multiLine,\n allowUnquotedControlChars=allowUnquotedControlChars, lineSep=lineSep, locale=locale,\n dropFieldIfAllNull=dropFieldIfAllNull, encoding=encoding)\n if isinstance(path, basestring):\n return self._df(self._jreader.json(path))\n else:\n raise TypeError(\"path can be only a single string\")" }, { "instruction": "Write or improve a Python function based on this description:\n\nLoads a ORC file stream, returning the result as a :class:`DataFrame`.\n\n .. note:: Evolving.\n\n >>> orc_sdf = spark.readStream.schema(sdf_schema).orc(tempfile.mkdtemp())\n >>> orc_sdf.isStreaming\n True\n >>> orc_sdf.schema == sdf_schema\n True", "output": "def orc(self, path):\n \"\"\"Loads a ORC file stream, returning the result as a :class:`DataFrame`.\n\n .. note:: Evolving.\n\n >>> orc_sdf = spark.readStream.schema(sdf_schema).orc(tempfile.mkdtemp())\n >>> orc_sdf.isStreaming\n True\n >>> orc_sdf.schema == sdf_schema\n True\n \"\"\"\n if isinstance(path, basestring):\n return self._df(self._jreader.orc(path))\n else:\n raise TypeError(\"path can be only a single string\")" }, { "instruction": "Write or improve a Python function based on this description:\n\nLoads a Parquet file stream, returning the result as a :class:`DataFrame`.\n\n You can set the following Parquet-specific option(s) for reading Parquet files:\n * ``mergeSchema``: sets whether we should merge schemas collected from all \\\n Parquet part-files. This will override ``spark.sql.parquet.mergeSchema``. \\\n The default value is specified in ``spark.sql.parquet.mergeSchema``.\n\n .. note:: Evolving.\n\n >>> parquet_sdf = spark.readStream.schema(sdf_schema).parquet(tempfile.mkdtemp())\n >>> parquet_sdf.isStreaming\n True\n >>> parquet_sdf.schema == sdf_schema\n True", "output": "def parquet(self, path):\n \"\"\"Loads a Parquet file stream, returning the result as a :class:`DataFrame`.\n\n You can set the following Parquet-specific option(s) for reading Parquet files:\n * ``mergeSchema``: sets whether we should merge schemas collected from all \\\n Parquet part-files. This will override ``spark.sql.parquet.mergeSchema``. \\\n The default value is specified in ``spark.sql.parquet.mergeSchema``.\n\n .. note:: Evolving.\n\n >>> parquet_sdf = spark.readStream.schema(sdf_schema).parquet(tempfile.mkdtemp())\n >>> parquet_sdf.isStreaming\n True\n >>> parquet_sdf.schema == sdf_schema\n True\n \"\"\"\n if isinstance(path, basestring):\n return self._df(self._jreader.parquet(path))\n else:\n raise TypeError(\"path can be only a single string\")" }, { "instruction": "Write or improve a Python function based on this description:\n\nLoads a text file stream and returns a :class:`DataFrame` whose schema starts with a\n string column named \"value\", and followed by partitioned columns if there\n are any.\n The text files must be encoded as UTF-8.\n\n By default, each line in the text file is a new row in the resulting DataFrame.\n\n .. note:: Evolving.\n\n :param paths: string, or list of strings, for input path(s).\n :param wholetext: if true, read each file from input path(s) as a single row.\n :param lineSep: defines the line separator that should be used for parsing. If None is\n set, it covers all ``\\\\r``, ``\\\\r\\\\n`` and ``\\\\n``.\n\n >>> text_sdf = spark.readStream.text(tempfile.mkdtemp())\n >>> text_sdf.isStreaming\n True\n >>> \"value\" in str(text_sdf.schema)\n True", "output": "def text(self, path, wholetext=False, lineSep=None):\n \"\"\"\n Loads a text file stream and returns a :class:`DataFrame` whose schema starts with a\n string column named \"value\", and followed by partitioned columns if there\n are any.\n The text files must be encoded as UTF-8.\n\n By default, each line in the text file is a new row in the resulting DataFrame.\n\n .. note:: Evolving.\n\n :param paths: string, or list of strings, for input path(s).\n :param wholetext: if true, read each file from input path(s) as a single row.\n :param lineSep: defines the line separator that should be used for parsing. If None is\n set, it covers all ``\\\\r``, ``\\\\r\\\\n`` and ``\\\\n``.\n\n >>> text_sdf = spark.readStream.text(tempfile.mkdtemp())\n >>> text_sdf.isStreaming\n True\n >>> \"value\" in str(text_sdf.schema)\n True\n \"\"\"\n self._set_opts(wholetext=wholetext, lineSep=lineSep)\n if isinstance(path, basestring):\n return self._df(self._jreader.text(path))\n else:\n raise TypeError(\"path can be only a single string\")" }, { "instruction": "Write or improve a Python function based on this description:\n\nr\"\"\"Loads a CSV file stream and returns the result as a :class:`DataFrame`.\n\n This function will go through the input once to determine the input schema if\n ``inferSchema`` is enabled. To avoid going through the entire data once, disable\n ``inferSchema`` option or specify the schema explicitly using ``schema``.\n\n .. note:: Evolving.\n\n :param path: string, or list of strings, for input path(s).\n :param schema: an optional :class:`pyspark.sql.types.StructType` for the input schema\n or a DDL-formatted string (For example ``col0 INT, col1 DOUBLE``).\n :param sep: sets a single character as a separator for each field and value.\n If None is set, it uses the default value, ``,``.\n :param encoding: decodes the CSV files by the given encoding type. If None is set,\n it uses the default value, ``UTF-8``.\n :param quote: sets a single character used for escaping quoted values where the\n separator can be part of the value. If None is set, it uses the default\n value, ``\"``. If you would like to turn off quotations, you need to set an\n empty string.\n :param escape: sets a single character used for escaping quotes inside an already\n quoted value. If None is set, it uses the default value, ``\\``.\n :param comment: sets a single character used for skipping lines beginning with this\n character. By default (None), it is disabled.\n :param header: uses the first line as names of columns. If None is set, it uses the\n default value, ``false``.\n :param inferSchema: infers the input schema automatically from data. It requires one extra\n pass over the data. If None is set, it uses the default value, ``false``.\n :param enforceSchema: If it is set to ``true``, the specified or inferred schema will be\n forcibly applied to datasource files, and headers in CSV files will be\n ignored. If the option is set to ``false``, the schema will be\n validated against all headers in CSV files or the first header in RDD\n if the ``header`` option is set to ``true``. Field names in the schema\n and column names in CSV headers are checked by their positions\n taking into account ``spark.sql.caseSensitive``. If None is set,\n ``true`` is used by default. Though the default value is ``true``,\n it is recommended to disable the ``enforceSchema`` option\n to avoid incorrect results.\n :param ignoreLeadingWhiteSpace: a flag indicating whether or not leading whitespaces from\n values being read should be skipped. If None is set, it\n uses the default value, ``false``.\n :param ignoreTrailingWhiteSpace: a flag indicating whether or not trailing whitespaces from\n values being read should be skipped. If None is set, it\n uses the default value, ``false``.\n :param nullValue: sets the string representation of a null value. If None is set, it uses\n the default value, empty string. Since 2.0.1, this ``nullValue`` param\n applies to all supported types including the string type.\n :param nanValue: sets the string representation of a non-number value. If None is set, it\n uses the default value, ``NaN``.\n :param positiveInf: sets the string representation of a positive infinity value. If None\n is set, it uses the default value, ``Inf``.\n :param negativeInf: sets the string representation of a negative infinity value. If None\n is set, it uses the default value, ``Inf``.\n :param dateFormat: sets the string that indicates a date format. Custom date formats\n follow the formats at ``java.time.format.DateTimeFormatter``. This\n applies to date type. If None is set, it uses the\n default value, ``yyyy-MM-dd``.\n :param timestampFormat: sets the string that indicates a timestamp format.\n Custom date formats follow the formats at\n ``java.time.format.DateTimeFormatter``.\n This applies to timestamp type. If None is set, it uses the\n default value, ``yyyy-MM-dd'T'HH:mm:ss.SSSXXX``.\n :param maxColumns: defines a hard limit of how many columns a record can have. If None is\n set, it uses the default value, ``20480``.\n :param maxCharsPerColumn: defines the maximum number of characters allowed for any given\n value being read. If None is set, it uses the default value,\n ``-1`` meaning unlimited length.\n :param maxMalformedLogPerPartition: this parameter is no longer used since Spark 2.2.0.\n If specified, it is ignored.\n :param mode: allows a mode for dealing with corrupt records during parsing. If None is\n set, it uses the default value, ``PERMISSIVE``.\n\n * ``PERMISSIVE`` : when it meets a corrupted record, puts the malformed string \\\n into a field configured by ``columnNameOfCorruptRecord``, and sets malformed \\\n fields to ``null``. To keep corrupt records, an user can set a string type \\\n field named ``columnNameOfCorruptRecord`` in an user-defined schema. If a \\\n schema does not have the field, it drops corrupt records during parsing. \\\n A record with less/more tokens than schema is not a corrupted record to CSV. \\\n When it meets a record having fewer tokens than the length of the schema, \\\n sets ``null`` to extra fields. When the record has more tokens than the \\\n length of the schema, it drops extra tokens.\n * ``DROPMALFORMED`` : ignores the whole corrupted records.\n * ``FAILFAST`` : throws an exception when it meets corrupted records.\n\n :param columnNameOfCorruptRecord: allows renaming the new field having malformed string\n created by ``PERMISSIVE`` mode. This overrides\n ``spark.sql.columnNameOfCorruptRecord``. If None is set,\n it uses the value specified in\n ``spark.sql.columnNameOfCorruptRecord``.\n :param multiLine: parse one record, which may span multiple lines. If None is\n set, it uses the default value, ``false``.\n :param charToEscapeQuoteEscaping: sets a single character used for escaping the escape for\n the quote character. If None is set, the default value is\n escape character when escape and quote characters are\n different, ``\\0`` otherwise..\n :param emptyValue: sets the string representation of an empty value. If None is set, it uses\n the default value, empty string.\n :param locale: sets a locale as language tag in IETF BCP 47 format. If None is set,\n it uses the default value, ``en-US``. For instance, ``locale`` is used while\n parsing dates and timestamps.\n :param lineSep: defines the line separator that should be used for parsing. If None is\n set, it covers all ``\\\\r``, ``\\\\r\\\\n`` and ``\\\\n``.\n Maximum length is 1 character.\n\n >>> csv_sdf = spark.readStream.csv(tempfile.mkdtemp(), schema = sdf_schema)\n >>> csv_sdf.isStreaming\n True\n >>> csv_sdf.schema == sdf_schema\n True", "output": "def csv(self, path, schema=None, sep=None, encoding=None, quote=None, escape=None,\n comment=None, header=None, inferSchema=None, ignoreLeadingWhiteSpace=None,\n ignoreTrailingWhiteSpace=None, nullValue=None, nanValue=None, positiveInf=None,\n negativeInf=None, dateFormat=None, timestampFormat=None, maxColumns=None,\n maxCharsPerColumn=None, maxMalformedLogPerPartition=None, mode=None,\n columnNameOfCorruptRecord=None, multiLine=None, charToEscapeQuoteEscaping=None,\n enforceSchema=None, emptyValue=None, locale=None, lineSep=None):\n r\"\"\"Loads a CSV file stream and returns the result as a :class:`DataFrame`.\n\n This function will go through the input once to determine the input schema if\n ``inferSchema`` is enabled. To avoid going through the entire data once, disable\n ``inferSchema`` option or specify the schema explicitly using ``schema``.\n\n .. note:: Evolving.\n\n :param path: string, or list of strings, for input path(s).\n :param schema: an optional :class:`pyspark.sql.types.StructType` for the input schema\n or a DDL-formatted string (For example ``col0 INT, col1 DOUBLE``).\n :param sep: sets a single character as a separator for each field and value.\n If None is set, it uses the default value, ``,``.\n :param encoding: decodes the CSV files by the given encoding type. If None is set,\n it uses the default value, ``UTF-8``.\n :param quote: sets a single character used for escaping quoted values where the\n separator can be part of the value. If None is set, it uses the default\n value, ``\"``. If you would like to turn off quotations, you need to set an\n empty string.\n :param escape: sets a single character used for escaping quotes inside an already\n quoted value. If None is set, it uses the default value, ``\\``.\n :param comment: sets a single character used for skipping lines beginning with this\n character. By default (None), it is disabled.\n :param header: uses the first line as names of columns. If None is set, it uses the\n default value, ``false``.\n :param inferSchema: infers the input schema automatically from data. It requires one extra\n pass over the data. If None is set, it uses the default value, ``false``.\n :param enforceSchema: If it is set to ``true``, the specified or inferred schema will be\n forcibly applied to datasource files, and headers in CSV files will be\n ignored. If the option is set to ``false``, the schema will be\n validated against all headers in CSV files or the first header in RDD\n if the ``header`` option is set to ``true``. Field names in the schema\n and column names in CSV headers are checked by their positions\n taking into account ``spark.sql.caseSensitive``. If None is set,\n ``true`` is used by default. Though the default value is ``true``,\n it is recommended to disable the ``enforceSchema`` option\n to avoid incorrect results.\n :param ignoreLeadingWhiteSpace: a flag indicating whether or not leading whitespaces from\n values being read should be skipped. If None is set, it\n uses the default value, ``false``.\n :param ignoreTrailingWhiteSpace: a flag indicating whether or not trailing whitespaces from\n values being read should be skipped. If None is set, it\n uses the default value, ``false``.\n :param nullValue: sets the string representation of a null value. If None is set, it uses\n the default value, empty string. Since 2.0.1, this ``nullValue`` param\n applies to all supported types including the string type.\n :param nanValue: sets the string representation of a non-number value. If None is set, it\n uses the default value, ``NaN``.\n :param positiveInf: sets the string representation of a positive infinity value. If None\n is set, it uses the default value, ``Inf``.\n :param negativeInf: sets the string representation of a negative infinity value. If None\n is set, it uses the default value, ``Inf``.\n :param dateFormat: sets the string that indicates a date format. Custom date formats\n follow the formats at ``java.time.format.DateTimeFormatter``. This\n applies to date type. If None is set, it uses the\n default value, ``yyyy-MM-dd``.\n :param timestampFormat: sets the string that indicates a timestamp format.\n Custom date formats follow the formats at\n ``java.time.format.DateTimeFormatter``.\n This applies to timestamp type. If None is set, it uses the\n default value, ``yyyy-MM-dd'T'HH:mm:ss.SSSXXX``.\n :param maxColumns: defines a hard limit of how many columns a record can have. If None is\n set, it uses the default value, ``20480``.\n :param maxCharsPerColumn: defines the maximum number of characters allowed for any given\n value being read. If None is set, it uses the default value,\n ``-1`` meaning unlimited length.\n :param maxMalformedLogPerPartition: this parameter is no longer used since Spark 2.2.0.\n If specified, it is ignored.\n :param mode: allows a mode for dealing with corrupt records during parsing. If None is\n set, it uses the default value, ``PERMISSIVE``.\n\n * ``PERMISSIVE`` : when it meets a corrupted record, puts the malformed string \\\n into a field configured by ``columnNameOfCorruptRecord``, and sets malformed \\\n fields to ``null``. To keep corrupt records, an user can set a string type \\\n field named ``columnNameOfCorruptRecord`` in an user-defined schema. If a \\\n schema does not have the field, it drops corrupt records during parsing. \\\n A record with less/more tokens than schema is not a corrupted record to CSV. \\\n When it meets a record having fewer tokens than the length of the schema, \\\n sets ``null`` to extra fields. When the record has more tokens than the \\\n length of the schema, it drops extra tokens.\n * ``DROPMALFORMED`` : ignores the whole corrupted records.\n * ``FAILFAST`` : throws an exception when it meets corrupted records.\n\n :param columnNameOfCorruptRecord: allows renaming the new field having malformed string\n created by ``PERMISSIVE`` mode. This overrides\n ``spark.sql.columnNameOfCorruptRecord``. If None is set,\n it uses the value specified in\n ``spark.sql.columnNameOfCorruptRecord``.\n :param multiLine: parse one record, which may span multiple lines. If None is\n set, it uses the default value, ``false``.\n :param charToEscapeQuoteEscaping: sets a single character used for escaping the escape for\n the quote character. If None is set, the default value is\n escape character when escape and quote characters are\n different, ``\\0`` otherwise..\n :param emptyValue: sets the string representation of an empty value. If None is set, it uses\n the default value, empty string.\n :param locale: sets a locale as language tag in IETF BCP 47 format. If None is set,\n it uses the default value, ``en-US``. For instance, ``locale`` is used while\n parsing dates and timestamps.\n :param lineSep: defines the line separator that should be used for parsing. If None is\n set, it covers all ``\\\\r``, ``\\\\r\\\\n`` and ``\\\\n``.\n Maximum length is 1 character.\n\n >>> csv_sdf = spark.readStream.csv(tempfile.mkdtemp(), schema = sdf_schema)\n >>> csv_sdf.isStreaming\n True\n >>> csv_sdf.schema == sdf_schema\n True\n \"\"\"\n self._set_opts(\n schema=schema, sep=sep, encoding=encoding, quote=quote, escape=escape, comment=comment,\n header=header, inferSchema=inferSchema, ignoreLeadingWhiteSpace=ignoreLeadingWhiteSpace,\n ignoreTrailingWhiteSpace=ignoreTrailingWhiteSpace, nullValue=nullValue,\n nanValue=nanValue, positiveInf=positiveInf, negativeInf=negativeInf,\n dateFormat=dateFormat, timestampFormat=timestampFormat, maxColumns=maxColumns,\n maxCharsPerColumn=maxCharsPerColumn,\n maxMalformedLogPerPartition=maxMalformedLogPerPartition, mode=mode,\n columnNameOfCorruptRecord=columnNameOfCorruptRecord, multiLine=multiLine,\n charToEscapeQuoteEscaping=charToEscapeQuoteEscaping, enforceSchema=enforceSchema,\n emptyValue=emptyValue, locale=locale, lineSep=lineSep)\n if isinstance(path, basestring):\n return self._df(self._jreader.csv(path))\n else:\n raise TypeError(\"path can be only a single string\")" }, { "instruction": "Write or improve a Python function based on this description:\n\nSpecifies how data of a streaming DataFrame/Dataset is written to a streaming sink.\n\n Options include:\n\n * `append`:Only the new rows in the streaming DataFrame/Dataset will be written to\n the sink\n * `complete`:All the rows in the streaming DataFrame/Dataset will be written to the sink\n every time these is some updates\n * `update`:only the rows that were updated in the streaming DataFrame/Dataset will be\n written to the sink every time there are some updates. If the query doesn't contain\n aggregations, it will be equivalent to `append` mode.\n\n .. note:: Evolving.\n\n >>> writer = sdf.writeStream.outputMode('append')", "output": "def outputMode(self, outputMode):\n \"\"\"Specifies how data of a streaming DataFrame/Dataset is written to a streaming sink.\n\n Options include:\n\n * `append`:Only the new rows in the streaming DataFrame/Dataset will be written to\n the sink\n * `complete`:All the rows in the streaming DataFrame/Dataset will be written to the sink\n every time these is some updates\n * `update`:only the rows that were updated in the streaming DataFrame/Dataset will be\n written to the sink every time there are some updates. If the query doesn't contain\n aggregations, it will be equivalent to `append` mode.\n\n .. note:: Evolving.\n\n >>> writer = sdf.writeStream.outputMode('append')\n \"\"\"\n if not outputMode or type(outputMode) != str or len(outputMode.strip()) == 0:\n raise ValueError('The output mode must be a non-empty string. Got: %s' % outputMode)\n self._jwrite = self._jwrite.outputMode(outputMode)\n return self" }, { "instruction": "Write or improve a Python function based on this description:\n\nSpecifies the name of the :class:`StreamingQuery` that can be started with\n :func:`start`. This name must be unique among all the currently active queries\n in the associated SparkSession.\n\n .. note:: Evolving.\n\n :param queryName: unique name for the query\n\n >>> writer = sdf.writeStream.queryName('streaming_query')", "output": "def queryName(self, queryName):\n \"\"\"Specifies the name of the :class:`StreamingQuery` that can be started with\n :func:`start`. This name must be unique among all the currently active queries\n in the associated SparkSession.\n\n .. note:: Evolving.\n\n :param queryName: unique name for the query\n\n >>> writer = sdf.writeStream.queryName('streaming_query')\n \"\"\"\n if not queryName or type(queryName) != str or len(queryName.strip()) == 0:\n raise ValueError('The queryName must be a non-empty string. Got: %s' % queryName)\n self._jwrite = self._jwrite.queryName(queryName)\n return self" }, { "instruction": "Write or improve a Python function based on this description:\n\nSet the trigger for the stream query. If this is not set it will run the query as fast\n as possible, which is equivalent to setting the trigger to ``processingTime='0 seconds'``.\n\n .. note:: Evolving.\n\n :param processingTime: a processing time interval as a string, e.g. '5 seconds', '1 minute'.\n Set a trigger that runs a query periodically based on the processing\n time. Only one trigger can be set.\n :param once: if set to True, set a trigger that processes only one batch of data in a\n streaming query then terminates the query. Only one trigger can be set.\n\n >>> # trigger the query for execution every 5 seconds\n >>> writer = sdf.writeStream.trigger(processingTime='5 seconds')\n >>> # trigger the query for just once batch of data\n >>> writer = sdf.writeStream.trigger(once=True)\n >>> # trigger the query for execution every 5 seconds\n >>> writer = sdf.writeStream.trigger(continuous='5 seconds')", "output": "def trigger(self, processingTime=None, once=None, continuous=None):\n \"\"\"Set the trigger for the stream query. If this is not set it will run the query as fast\n as possible, which is equivalent to setting the trigger to ``processingTime='0 seconds'``.\n\n .. note:: Evolving.\n\n :param processingTime: a processing time interval as a string, e.g. '5 seconds', '1 minute'.\n Set a trigger that runs a query periodically based on the processing\n time. Only one trigger can be set.\n :param once: if set to True, set a trigger that processes only one batch of data in a\n streaming query then terminates the query. Only one trigger can be set.\n\n >>> # trigger the query for execution every 5 seconds\n >>> writer = sdf.writeStream.trigger(processingTime='5 seconds')\n >>> # trigger the query for just once batch of data\n >>> writer = sdf.writeStream.trigger(once=True)\n >>> # trigger the query for execution every 5 seconds\n >>> writer = sdf.writeStream.trigger(continuous='5 seconds')\n \"\"\"\n params = [processingTime, once, continuous]\n\n if params.count(None) == 3:\n raise ValueError('No trigger provided')\n elif params.count(None) < 2:\n raise ValueError('Multiple triggers not allowed.')\n\n jTrigger = None\n if processingTime is not None:\n if type(processingTime) != str or len(processingTime.strip()) == 0:\n raise ValueError('Value for processingTime must be a non empty string. Got: %s' %\n processingTime)\n interval = processingTime.strip()\n jTrigger = self._spark._sc._jvm.org.apache.spark.sql.streaming.Trigger.ProcessingTime(\n interval)\n\n elif once is not None:\n if once is not True:\n raise ValueError('Value for once must be True. Got: %s' % once)\n jTrigger = self._spark._sc._jvm.org.apache.spark.sql.streaming.Trigger.Once()\n\n else:\n if type(continuous) != str or len(continuous.strip()) == 0:\n raise ValueError('Value for continuous must be a non empty string. Got: %s' %\n continuous)\n interval = continuous.strip()\n jTrigger = self._spark._sc._jvm.org.apache.spark.sql.streaming.Trigger.Continuous(\n interval)\n\n self._jwrite = self._jwrite.trigger(jTrigger)\n return self" }, { "instruction": "Write or improve a Python function based on this description:\n\nSets the output of the streaming query to be processed using the provided writer ``f``.\n This is often used to write the output of a streaming query to arbitrary storage systems.\n The processing logic can be specified in two ways.\n\n #. A **function** that takes a row as input.\n This is a simple way to express your processing logic. Note that this does\n not allow you to deduplicate generated data when failures cause reprocessing of\n some input data. That would require you to specify the processing logic in the next\n way.\n\n #. An **object** with a ``process`` method and optional ``open`` and ``close`` methods.\n The object can have the following methods.\n\n * ``open(partition_id, epoch_id)``: *Optional* method that initializes the processing\n (for example, open a connection, start a transaction, etc). Additionally, you can\n use the `partition_id` and `epoch_id` to deduplicate regenerated data\n (discussed later).\n\n * ``process(row)``: *Non-optional* method that processes each :class:`Row`.\n\n * ``close(error)``: *Optional* method that finalizes and cleans up (for example,\n close connection, commit transaction, etc.) after all rows have been processed.\n\n The object will be used by Spark in the following way.\n\n * A single copy of this object is responsible of all the data generated by a\n single task in a query. In other words, one instance is responsible for\n processing one partition of the data generated in a distributed manner.\n\n * This object must be serializable because each task will get a fresh\n serialized-deserialized copy of the provided object. Hence, it is strongly\n recommended that any initialization for writing data (e.g. opening a\n connection or starting a transaction) is done after the `open(...)`\n method has been called, which signifies that the task is ready to generate data.\n\n * The lifecycle of the methods are as follows.\n\n For each partition with ``partition_id``:\n\n ... For each batch/epoch of streaming data with ``epoch_id``:\n\n ....... Method ``open(partitionId, epochId)`` is called.\n\n ....... If ``open(...)`` returns true, for each row in the partition and\n batch/epoch, method ``process(row)`` is called.\n\n ....... Method ``close(errorOrNull)`` is called with error (if any) seen while\n processing rows.\n\n Important points to note:\n\n * The `partitionId` and `epochId` can be used to deduplicate generated data when\n failures cause reprocessing of some input data. This depends on the execution\n mode of the query. If the streaming query is being executed in the micro-batch\n mode, then every partition represented by a unique tuple (partition_id, epoch_id)\n is guaranteed to have the same data. Hence, (partition_id, epoch_id) can be used\n to deduplicate and/or transactionally commit data and achieve exactly-once\n guarantees. However, if the streaming query is being executed in the continuous\n mode, then this guarantee does not hold and therefore should not be used for\n deduplication.\n\n * The ``close()`` method (if exists) will be called if `open()` method exists and\n returns successfully (irrespective of the return value), except if the Python\n crashes in the middle.\n\n .. note:: Evolving.\n\n >>> # Print every row using a function\n >>> def print_row(row):\n ... print(row)\n ...\n >>> writer = sdf.writeStream.foreach(print_row)\n >>> # Print every row using a object with process() method\n >>> class RowPrinter:\n ... def open(self, partition_id, epoch_id):\n ... print(\"Opened %d, %d\" % (partition_id, epoch_id))\n ... return True\n ... def process(self, row):\n ... print(row)\n ... def close(self, error):\n ... print(\"Closed with error: %s\" % str(error))\n ...\n >>> writer = sdf.writeStream.foreach(RowPrinter())", "output": "def foreach(self, f):\n \"\"\"\n Sets the output of the streaming query to be processed using the provided writer ``f``.\n This is often used to write the output of a streaming query to arbitrary storage systems.\n The processing logic can be specified in two ways.\n\n #. A **function** that takes a row as input.\n This is a simple way to express your processing logic. Note that this does\n not allow you to deduplicate generated data when failures cause reprocessing of\n some input data. That would require you to specify the processing logic in the next\n way.\n\n #. An **object** with a ``process`` method and optional ``open`` and ``close`` methods.\n The object can have the following methods.\n\n * ``open(partition_id, epoch_id)``: *Optional* method that initializes the processing\n (for example, open a connection, start a transaction, etc). Additionally, you can\n use the `partition_id` and `epoch_id` to deduplicate regenerated data\n (discussed later).\n\n * ``process(row)``: *Non-optional* method that processes each :class:`Row`.\n\n * ``close(error)``: *Optional* method that finalizes and cleans up (for example,\n close connection, commit transaction, etc.) after all rows have been processed.\n\n The object will be used by Spark in the following way.\n\n * A single copy of this object is responsible of all the data generated by a\n single task in a query. In other words, one instance is responsible for\n processing one partition of the data generated in a distributed manner.\n\n * This object must be serializable because each task will get a fresh\n serialized-deserialized copy of the provided object. Hence, it is strongly\n recommended that any initialization for writing data (e.g. opening a\n connection or starting a transaction) is done after the `open(...)`\n method has been called, which signifies that the task is ready to generate data.\n\n * The lifecycle of the methods are as follows.\n\n For each partition with ``partition_id``:\n\n ... For each batch/epoch of streaming data with ``epoch_id``:\n\n ....... Method ``open(partitionId, epochId)`` is called.\n\n ....... If ``open(...)`` returns true, for each row in the partition and\n batch/epoch, method ``process(row)`` is called.\n\n ....... Method ``close(errorOrNull)`` is called with error (if any) seen while\n processing rows.\n\n Important points to note:\n\n * The `partitionId` and `epochId` can be used to deduplicate generated data when\n failures cause reprocessing of some input data. This depends on the execution\n mode of the query. If the streaming query is being executed in the micro-batch\n mode, then every partition represented by a unique tuple (partition_id, epoch_id)\n is guaranteed to have the same data. Hence, (partition_id, epoch_id) can be used\n to deduplicate and/or transactionally commit data and achieve exactly-once\n guarantees. However, if the streaming query is being executed in the continuous\n mode, then this guarantee does not hold and therefore should not be used for\n deduplication.\n\n * The ``close()`` method (if exists) will be called if `open()` method exists and\n returns successfully (irrespective of the return value), except if the Python\n crashes in the middle.\n\n .. note:: Evolving.\n\n >>> # Print every row using a function\n >>> def print_row(row):\n ... print(row)\n ...\n >>> writer = sdf.writeStream.foreach(print_row)\n >>> # Print every row using a object with process() method\n >>> class RowPrinter:\n ... def open(self, partition_id, epoch_id):\n ... print(\"Opened %d, %d\" % (partition_id, epoch_id))\n ... return True\n ... def process(self, row):\n ... print(row)\n ... def close(self, error):\n ... print(\"Closed with error: %s\" % str(error))\n ...\n >>> writer = sdf.writeStream.foreach(RowPrinter())\n \"\"\"\n\n from pyspark.rdd import _wrap_function\n from pyspark.serializers import PickleSerializer, AutoBatchedSerializer\n from pyspark.taskcontext import TaskContext\n\n if callable(f):\n # The provided object is a callable function that is supposed to be called on each row.\n # Construct a function that takes an iterator and calls the provided function on each\n # row.\n def func_without_process(_, iterator):\n for x in iterator:\n f(x)\n return iter([])\n\n func = func_without_process\n\n else:\n # The provided object is not a callable function. Then it is expected to have a\n # 'process(row)' method, and optional 'open(partition_id, epoch_id)' and\n # 'close(error)' methods.\n\n if not hasattr(f, 'process'):\n raise Exception(\"Provided object does not have a 'process' method\")\n\n if not callable(getattr(f, 'process')):\n raise Exception(\"Attribute 'process' in provided object is not callable\")\n\n def doesMethodExist(method_name):\n exists = hasattr(f, method_name)\n if exists and not callable(getattr(f, method_name)):\n raise Exception(\n \"Attribute '%s' in provided object is not callable\" % method_name)\n return exists\n\n open_exists = doesMethodExist('open')\n close_exists = doesMethodExist('close')\n\n def func_with_open_process_close(partition_id, iterator):\n epoch_id = TaskContext.get().getLocalProperty('streaming.sql.batchId')\n if epoch_id:\n epoch_id = int(epoch_id)\n else:\n raise Exception(\"Could not get batch id from TaskContext\")\n\n # Check if the data should be processed\n should_process = True\n if open_exists:\n should_process = f.open(partition_id, epoch_id)\n\n error = None\n\n try:\n if should_process:\n for x in iterator:\n f.process(x)\n except Exception as ex:\n error = ex\n finally:\n if close_exists:\n f.close(error)\n if error:\n raise error\n\n return iter([])\n\n func = func_with_open_process_close\n\n serializer = AutoBatchedSerializer(PickleSerializer())\n wrapped_func = _wrap_function(self._spark._sc, func, serializer, serializer)\n jForeachWriter = \\\n self._spark._sc._jvm.org.apache.spark.sql.execution.python.PythonForeachWriter(\n wrapped_func, self._df._jdf.schema())\n self._jwrite.foreach(jForeachWriter)\n return self" }, { "instruction": "Write or improve a Python function based on this description:\n\nSets the output of the streaming query to be processed using the provided\n function. This is supported only the in the micro-batch execution modes (that is, when the\n trigger is not continuous). In every micro-batch, the provided function will be called in\n every micro-batch with (i) the output rows as a DataFrame and (ii) the batch identifier.\n The batchId can be used deduplicate and transactionally write the output\n (that is, the provided Dataset) to external systems. The output DataFrame is guaranteed\n to exactly same for the same batchId (assuming all operations are deterministic in the\n query).\n\n .. note:: Evolving.\n\n >>> def func(batch_df, batch_id):\n ... batch_df.collect()\n ...\n >>> writer = sdf.writeStream.foreach(func)", "output": "def foreachBatch(self, func):\n \"\"\"\n Sets the output of the streaming query to be processed using the provided\n function. This is supported only the in the micro-batch execution modes (that is, when the\n trigger is not continuous). In every micro-batch, the provided function will be called in\n every micro-batch with (i) the output rows as a DataFrame and (ii) the batch identifier.\n The batchId can be used deduplicate and transactionally write the output\n (that is, the provided Dataset) to external systems. The output DataFrame is guaranteed\n to exactly same for the same batchId (assuming all operations are deterministic in the\n query).\n\n .. note:: Evolving.\n\n >>> def func(batch_df, batch_id):\n ... batch_df.collect()\n ...\n >>> writer = sdf.writeStream.foreach(func)\n \"\"\"\n\n from pyspark.java_gateway import ensure_callback_server_started\n gw = self._spark._sc._gateway\n java_import(gw.jvm, \"org.apache.spark.sql.execution.streaming.sources.*\")\n\n wrapped_func = ForeachBatchFunction(self._spark, func)\n gw.jvm.PythonForeachBatchHelper.callForeachBatch(self._jwrite, wrapped_func)\n ensure_callback_server_started(gw)\n return self" }, { "instruction": "Write or improve a Python function based on this description:\n\nStreams the contents of the :class:`DataFrame` to a data source.\n\n The data source is specified by the ``format`` and a set of ``options``.\n If ``format`` is not specified, the default data source configured by\n ``spark.sql.sources.default`` will be used.\n\n .. note:: Evolving.\n\n :param path: the path in a Hadoop supported file system\n :param format: the format used to save\n :param outputMode: specifies how data of a streaming DataFrame/Dataset is written to a\n streaming sink.\n\n * `append`:Only the new rows in the streaming DataFrame/Dataset will be written to the\n sink\n * `complete`:All the rows in the streaming DataFrame/Dataset will be written to the sink\n every time these is some updates\n * `update`:only the rows that were updated in the streaming DataFrame/Dataset will be\n written to the sink every time there are some updates. If the query doesn't contain\n aggregations, it will be equivalent to `append` mode.\n :param partitionBy: names of partitioning columns\n :param queryName: unique name for the query\n :param options: All other string options. You may want to provide a `checkpointLocation`\n for most streams, however it is not required for a `memory` stream.\n\n >>> sq = sdf.writeStream.format('memory').queryName('this_query').start()\n >>> sq.isActive\n True\n >>> sq.name\n u'this_query'\n >>> sq.stop()\n >>> sq.isActive\n False\n >>> sq = sdf.writeStream.trigger(processingTime='5 seconds').start(\n ... queryName='that_query', outputMode=\"append\", format='memory')\n >>> sq.name\n u'that_query'\n >>> sq.isActive\n True\n >>> sq.stop()", "output": "def start(self, path=None, format=None, outputMode=None, partitionBy=None, queryName=None,\n **options):\n \"\"\"Streams the contents of the :class:`DataFrame` to a data source.\n\n The data source is specified by the ``format`` and a set of ``options``.\n If ``format`` is not specified, the default data source configured by\n ``spark.sql.sources.default`` will be used.\n\n .. note:: Evolving.\n\n :param path: the path in a Hadoop supported file system\n :param format: the format used to save\n :param outputMode: specifies how data of a streaming DataFrame/Dataset is written to a\n streaming sink.\n\n * `append`:Only the new rows in the streaming DataFrame/Dataset will be written to the\n sink\n * `complete`:All the rows in the streaming DataFrame/Dataset will be written to the sink\n every time these is some updates\n * `update`:only the rows that were updated in the streaming DataFrame/Dataset will be\n written to the sink every time there are some updates. If the query doesn't contain\n aggregations, it will be equivalent to `append` mode.\n :param partitionBy: names of partitioning columns\n :param queryName: unique name for the query\n :param options: All other string options. You may want to provide a `checkpointLocation`\n for most streams, however it is not required for a `memory` stream.\n\n >>> sq = sdf.writeStream.format('memory').queryName('this_query').start()\n >>> sq.isActive\n True\n >>> sq.name\n u'this_query'\n >>> sq.stop()\n >>> sq.isActive\n False\n >>> sq = sdf.writeStream.trigger(processingTime='5 seconds').start(\n ... queryName='that_query', outputMode=\"append\", format='memory')\n >>> sq.name\n u'that_query'\n >>> sq.isActive\n True\n >>> sq.stop()\n \"\"\"\n self.options(**options)\n if outputMode is not None:\n self.outputMode(outputMode)\n if partitionBy is not None:\n self.partitionBy(partitionBy)\n if format is not None:\n self.format(format)\n if queryName is not None:\n self.queryName(queryName)\n if path is None:\n return self._sq(self._jwrite.start())\n else:\n return self._sq(self._jwrite.start(path))" }, { "instruction": "Write or improve a Python function based on this description:\n\nGet the Python compiler to emit LOAD_FAST(arg); STORE_DEREF\n\n Notes\n -----\n In Python 3, we could use an easier function:\n\n .. code-block:: python\n\n def f():\n cell = None\n\n def _stub(value):\n nonlocal cell\n cell = value\n\n return _stub\n\n _cell_set_template_code = f().__code__\n\n This function is _only_ a LOAD_FAST(arg); STORE_DEREF, but that is\n invalid syntax on Python 2. If we use this function we also don't need\n to do the weird freevars/cellvars swap below", "output": "def _make_cell_set_template_code():\n \"\"\"Get the Python compiler to emit LOAD_FAST(arg); STORE_DEREF\n\n Notes\n -----\n In Python 3, we could use an easier function:\n\n .. code-block:: python\n\n def f():\n cell = None\n\n def _stub(value):\n nonlocal cell\n cell = value\n\n return _stub\n\n _cell_set_template_code = f().__code__\n\n This function is _only_ a LOAD_FAST(arg); STORE_DEREF, but that is\n invalid syntax on Python 2. If we use this function we also don't need\n to do the weird freevars/cellvars swap below\n \"\"\"\n def inner(value):\n lambda: cell # make ``cell`` a closure so that we get a STORE_DEREF\n cell = value\n\n co = inner.__code__\n\n # NOTE: we are marking the cell variable as a free variable intentionally\n # so that we simulate an inner function instead of the outer function. This\n # is what gives us the ``nonlocal`` behavior in a Python 2 compatible way.\n if not PY3: # pragma: no branch\n return types.CodeType(\n co.co_argcount,\n co.co_nlocals,\n co.co_stacksize,\n co.co_flags,\n co.co_code,\n co.co_consts,\n co.co_names,\n co.co_varnames,\n co.co_filename,\n co.co_name,\n co.co_firstlineno,\n co.co_lnotab,\n co.co_cellvars, # this is the trickery\n (),\n )\n else:\n return types.CodeType(\n co.co_argcount,\n co.co_kwonlyargcount,\n co.co_nlocals,\n co.co_stacksize,\n co.co_flags,\n co.co_code,\n co.co_consts,\n co.co_names,\n co.co_varnames,\n co.co_filename,\n co.co_name,\n co.co_firstlineno,\n co.co_lnotab,\n co.co_cellvars, # this is the trickery\n (),\n )" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn whether *func* is a Tornado coroutine function.\n Running coroutines are not supported.", "output": "def is_tornado_coroutine(func):\n \"\"\"\n Return whether *func* is a Tornado coroutine function.\n Running coroutines are not supported.\n \"\"\"\n if 'tornado.gen' not in sys.modules:\n return False\n gen = sys.modules['tornado.gen']\n if not hasattr(gen, \"is_coroutine_function\"):\n # Tornado version is too old\n return False\n return gen.is_coroutine_function(func)" }, { "instruction": "Write or improve a Python function based on this description:\n\nSerialize obj as bytes streamed into file\n\n protocol defaults to cloudpickle.DEFAULT_PROTOCOL which is an alias to\n pickle.HIGHEST_PROTOCOL. This setting favors maximum communication speed\n between processes running the same Python version.\n\n Set protocol=pickle.DEFAULT_PROTOCOL instead if you need to ensure\n compatibility with older versions of Python.", "output": "def dump(obj, file, protocol=None):\n \"\"\"Serialize obj as bytes streamed into file\n\n protocol defaults to cloudpickle.DEFAULT_PROTOCOL which is an alias to\n pickle.HIGHEST_PROTOCOL. This setting favors maximum communication speed\n between processes running the same Python version.\n\n Set protocol=pickle.DEFAULT_PROTOCOL instead if you need to ensure\n compatibility with older versions of Python.\n \"\"\"\n CloudPickler(file, protocol=protocol).dump(obj)" }, { "instruction": "Write or improve a Python function based on this description:\n\nSerialize obj as a string of bytes allocated in memory\n\n protocol defaults to cloudpickle.DEFAULT_PROTOCOL which is an alias to\n pickle.HIGHEST_PROTOCOL. This setting favors maximum communication speed\n between processes running the same Python version.\n\n Set protocol=pickle.DEFAULT_PROTOCOL instead if you need to ensure\n compatibility with older versions of Python.", "output": "def dumps(obj, protocol=None):\n \"\"\"Serialize obj as a string of bytes allocated in memory\n\n protocol defaults to cloudpickle.DEFAULT_PROTOCOL which is an alias to\n pickle.HIGHEST_PROTOCOL. This setting favors maximum communication speed\n between processes running the same Python version.\n\n Set protocol=pickle.DEFAULT_PROTOCOL instead if you need to ensure\n compatibility with older versions of Python.\n \"\"\"\n file = StringIO()\n try:\n cp = CloudPickler(file, protocol=protocol)\n cp.dump(obj)\n return file.getvalue()\n finally:\n file.close()" }, { "instruction": "Write or improve a Python function based on this description:\n\nFills in the rest of function data into the skeleton function object\n\n The skeleton itself is create by _make_skel_func().", "output": "def _fill_function(*args):\n \"\"\"Fills in the rest of function data into the skeleton function object\n\n The skeleton itself is create by _make_skel_func().\n \"\"\"\n if len(args) == 2:\n func = args[0]\n state = args[1]\n elif len(args) == 5:\n # Backwards compat for cloudpickle v0.4.0, after which the `module`\n # argument was introduced\n func = args[0]\n keys = ['globals', 'defaults', 'dict', 'closure_values']\n state = dict(zip(keys, args[1:]))\n elif len(args) == 6:\n # Backwards compat for cloudpickle v0.4.1, after which the function\n # state was passed as a dict to the _fill_function it-self.\n func = args[0]\n keys = ['globals', 'defaults', 'dict', 'module', 'closure_values']\n state = dict(zip(keys, args[1:]))\n else:\n raise ValueError('Unexpected _fill_value arguments: %r' % (args,))\n\n # - At pickling time, any dynamic global variable used by func is\n # serialized by value (in state['globals']).\n # - At unpickling time, func's __globals__ attribute is initialized by\n # first retrieving an empty isolated namespace that will be shared\n # with other functions pickled from the same original module\n # by the same CloudPickler instance and then updated with the\n # content of state['globals'] to populate the shared isolated\n # namespace with all the global variables that are specifically\n # referenced for this function.\n func.__globals__.update(state['globals'])\n\n func.__defaults__ = state['defaults']\n func.__dict__ = state['dict']\n if 'annotations' in state:\n func.__annotations__ = state['annotations']\n if 'doc' in state:\n func.__doc__ = state['doc']\n if 'name' in state:\n func.__name__ = state['name']\n if 'module' in state:\n func.__module__ = state['module']\n if 'qualname' in state:\n func.__qualname__ = state['qualname']\n\n cells = func.__closure__\n if cells is not None:\n for cell, value in zip(cells, state['closure_values']):\n if value is not _empty_cell_value:\n cell_set(cell, value)\n\n return func" }, { "instruction": "Write or improve a Python function based on this description:\n\nPut attributes from `class_dict` back on `skeleton_class`.\n\n See CloudPickler.save_dynamic_class for more info.", "output": "def _rehydrate_skeleton_class(skeleton_class, class_dict):\n \"\"\"Put attributes from `class_dict` back on `skeleton_class`.\n\n See CloudPickler.save_dynamic_class for more info.\n \"\"\"\n registry = None\n for attrname, attr in class_dict.items():\n if attrname == \"_abc_impl\":\n registry = attr\n else:\n setattr(skeleton_class, attrname, attr)\n if registry is not None:\n for subclass in registry:\n skeleton_class.register(subclass)\n\n return skeleton_class" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn True if the module is special module that cannot be imported by its\n name.", "output": "def _is_dynamic(module):\n \"\"\"\n Return True if the module is special module that cannot be imported by its\n name.\n \"\"\"\n # Quick check: module that have __file__ attribute are not dynamic modules.\n if hasattr(module, '__file__'):\n return False\n\n if hasattr(module, '__spec__'):\n return module.__spec__ is None\n else:\n # Backward compat for Python 2\n import imp\n try:\n path = None\n for part in module.__name__.split('.'):\n if path is not None:\n path = [path]\n f, path, description = imp.find_module(part, path)\n if f is not None:\n f.close()\n except ImportError:\n return True\n return False" }, { "instruction": "Write or improve a Python function based on this description:\n\nSave a code object", "output": "def save_codeobject(self, obj):\n \"\"\"\n Save a code object\n \"\"\"\n if PY3: # pragma: no branch\n args = (\n obj.co_argcount, obj.co_kwonlyargcount, obj.co_nlocals, obj.co_stacksize,\n obj.co_flags, obj.co_code, obj.co_consts, obj.co_names, obj.co_varnames,\n obj.co_filename, obj.co_name, obj.co_firstlineno, obj.co_lnotab, obj.co_freevars,\n obj.co_cellvars\n )\n else:\n args = (\n obj.co_argcount, obj.co_nlocals, obj.co_stacksize, obj.co_flags, obj.co_code,\n obj.co_consts, obj.co_names, obj.co_varnames, obj.co_filename, obj.co_name,\n obj.co_firstlineno, obj.co_lnotab, obj.co_freevars, obj.co_cellvars\n )\n self.save_reduce(types.CodeType, args, obj=obj)" }, { "instruction": "Write or improve a Python function based on this description:\n\nRegistered with the dispatch to handle all function types.\n\n Determines what kind of function obj is (e.g. lambda, defined at\n interactive prompt, etc) and handles the pickling appropriately.", "output": "def save_function(self, obj, name=None):\n \"\"\" Registered with the dispatch to handle all function types.\n\n Determines what kind of function obj is (e.g. lambda, defined at\n interactive prompt, etc) and handles the pickling appropriately.\n \"\"\"\n try:\n should_special_case = obj in _BUILTIN_TYPE_CONSTRUCTORS\n except TypeError:\n # Methods of builtin types aren't hashable in python 2.\n should_special_case = False\n\n if should_special_case:\n # We keep a special-cased cache of built-in type constructors at\n # global scope, because these functions are structured very\n # differently in different python versions and implementations (for\n # example, they're instances of types.BuiltinFunctionType in\n # CPython, but they're ordinary types.FunctionType instances in\n # PyPy).\n #\n # If the function we've received is in that cache, we just\n # serialize it as a lookup into the cache.\n return self.save_reduce(_BUILTIN_TYPE_CONSTRUCTORS[obj], (), obj=obj)\n\n write = self.write\n\n if name is None:\n name = obj.__name__\n try:\n # whichmodule() could fail, see\n # https://bitbucket.org/gutworth/six/issues/63/importing-six-breaks-pickling\n modname = pickle.whichmodule(obj, name)\n except Exception:\n modname = None\n # print('which gives %s %s %s' % (modname, obj, name))\n try:\n themodule = sys.modules[modname]\n except KeyError:\n # eval'd items such as namedtuple give invalid items for their function __module__\n modname = '__main__'\n\n if modname == '__main__':\n themodule = None\n\n try:\n lookedup_by_name = getattr(themodule, name, None)\n except Exception:\n lookedup_by_name = None\n\n if themodule:\n if lookedup_by_name is obj:\n return self.save_global(obj, name)\n\n # a builtin_function_or_method which comes in as an attribute of some\n # object (e.g., itertools.chain.from_iterable) will end\n # up with modname \"__main__\" and so end up here. But these functions\n # have no __code__ attribute in CPython, so the handling for\n # user-defined functions below will fail.\n # So we pickle them here using save_reduce; have to do it differently\n # for different python versions.\n if not hasattr(obj, '__code__'):\n if PY3: # pragma: no branch\n rv = obj.__reduce_ex__(self.proto)\n else:\n if hasattr(obj, '__self__'):\n rv = (getattr, (obj.__self__, name))\n else:\n raise pickle.PicklingError(\"Can't pickle %r\" % obj)\n return self.save_reduce(obj=obj, *rv)\n\n # if func is lambda, def'ed at prompt, is in main, or is nested, then\n # we'll pickle the actual function object rather than simply saving a\n # reference (as is done in default pickler), via save_function_tuple.\n if (islambda(obj)\n or getattr(obj.__code__, 'co_filename', None) == ''\n or themodule is None):\n self.save_function_tuple(obj)\n return\n else:\n # func is nested\n if lookedup_by_name is None or lookedup_by_name is not obj:\n self.save_function_tuple(obj)\n return\n\n if obj.__dict__:\n # essentially save_reduce, but workaround needed to avoid recursion\n self.save(_restore_attr)\n write(pickle.MARK + pickle.GLOBAL + modname + '\\n' + name + '\\n')\n self.memoize(obj)\n self.save(obj.__dict__)\n write(pickle.TUPLE + pickle.REDUCE)\n else:\n write(pickle.GLOBAL + modname + '\\n' + name + '\\n')\n self.memoize(obj)" }, { "instruction": "Write or improve a Python function based on this description:\n\nSave a class that can't be stored as module global.\n\n This method is used to serialize classes that are defined inside\n functions, or that otherwise can't be serialized as attribute lookups\n from global modules.", "output": "def save_dynamic_class(self, obj):\n \"\"\"\n Save a class that can't be stored as module global.\n\n This method is used to serialize classes that are defined inside\n functions, or that otherwise can't be serialized as attribute lookups\n from global modules.\n \"\"\"\n clsdict = dict(obj.__dict__) # copy dict proxy to a dict\n clsdict.pop('__weakref__', None)\n\n # For ABCMeta in python3.7+, remove _abc_impl as it is not picklable.\n # This is a fix which breaks the cache but this only makes the first\n # calls to issubclass slower.\n if \"_abc_impl\" in clsdict:\n import abc\n (registry, _, _, _) = abc._get_dump(obj)\n clsdict[\"_abc_impl\"] = [subclass_weakref()\n for subclass_weakref in registry]\n\n # On PyPy, __doc__ is a readonly attribute, so we need to include it in\n # the initial skeleton class. This is safe because we know that the\n # doc can't participate in a cycle with the original class.\n type_kwargs = {'__doc__': clsdict.pop('__doc__', None)}\n\n if hasattr(obj, \"__slots__\"):\n type_kwargs['__slots__'] = obj.__slots__\n # pickle string length optimization: member descriptors of obj are\n # created automatically from obj's __slots__ attribute, no need to\n # save them in obj's state\n if isinstance(obj.__slots__, string_types):\n clsdict.pop(obj.__slots__)\n else:\n for k in obj.__slots__:\n clsdict.pop(k, None)\n\n # If type overrides __dict__ as a property, include it in the type kwargs.\n # In Python 2, we can't set this attribute after construction.\n __dict__ = clsdict.pop('__dict__', None)\n if isinstance(__dict__, property):\n type_kwargs['__dict__'] = __dict__\n\n save = self.save\n write = self.write\n\n # We write pickle instructions explicitly here to handle the\n # possibility that the type object participates in a cycle with its own\n # __dict__. We first write an empty \"skeleton\" version of the class and\n # memoize it before writing the class' __dict__ itself. We then write\n # instructions to \"rehydrate\" the skeleton class by restoring the\n # attributes from the __dict__.\n #\n # A type can appear in a cycle with its __dict__ if an instance of the\n # type appears in the type's __dict__ (which happens for the stdlib\n # Enum class), or if the type defines methods that close over the name\n # of the type, (which is common for Python 2-style super() calls).\n\n # Push the rehydration function.\n save(_rehydrate_skeleton_class)\n\n # Mark the start of the args tuple for the rehydration function.\n write(pickle.MARK)\n\n # Create and memoize an skeleton class with obj's name and bases.\n tp = type(obj)\n self.save_reduce(tp, (obj.__name__, obj.__bases__, type_kwargs), obj=obj)\n\n # Now save the rest of obj's __dict__. Any references to obj\n # encountered while saving will point to the skeleton class.\n save(clsdict)\n\n # Write a tuple of (skeleton_class, clsdict).\n write(pickle.TUPLE)\n\n # Call _rehydrate_skeleton_class(skeleton_class, clsdict)\n write(pickle.REDUCE)" }, { "instruction": "Write or improve a Python function based on this description:\n\nPickles an actual func object.\n\n A func comprises: code, globals, defaults, closure, and dict. We\n extract and save these, injecting reducing functions at certain points\n to recreate the func object. Keep in mind that some of these pieces\n can contain a ref to the func itself. Thus, a naive save on these\n pieces could trigger an infinite loop of save's. To get around that,\n we first create a skeleton func object using just the code (this is\n safe, since this won't contain a ref to the func), and memoize it as\n soon as it's created. The other stuff can then be filled in later.", "output": "def save_function_tuple(self, func):\n \"\"\" Pickles an actual func object.\n\n A func comprises: code, globals, defaults, closure, and dict. We\n extract and save these, injecting reducing functions at certain points\n to recreate the func object. Keep in mind that some of these pieces\n can contain a ref to the func itself. Thus, a naive save on these\n pieces could trigger an infinite loop of save's. To get around that,\n we first create a skeleton func object using just the code (this is\n safe, since this won't contain a ref to the func), and memoize it as\n soon as it's created. The other stuff can then be filled in later.\n \"\"\"\n if is_tornado_coroutine(func):\n self.save_reduce(_rebuild_tornado_coroutine, (func.__wrapped__,),\n obj=func)\n return\n\n save = self.save\n write = self.write\n\n code, f_globals, defaults, closure_values, dct, base_globals = self.extract_func_data(func)\n\n save(_fill_function) # skeleton function updater\n write(pickle.MARK) # beginning of tuple that _fill_function expects\n\n self._save_subimports(\n code,\n itertools.chain(f_globals.values(), closure_values or ()),\n )\n\n # create a skeleton function object and memoize it\n save(_make_skel_func)\n save((\n code,\n len(closure_values) if closure_values is not None else -1,\n base_globals,\n ))\n write(pickle.REDUCE)\n self.memoize(func)\n\n # save the rest of the func data needed by _fill_function\n state = {\n 'globals': f_globals,\n 'defaults': defaults,\n 'dict': dct,\n 'closure_values': closure_values,\n 'module': func.__module__,\n 'name': func.__name__,\n 'doc': func.__doc__,\n }\n if hasattr(func, '__annotations__') and sys.version_info >= (3, 7):\n state['annotations'] = func.__annotations__\n if hasattr(func, '__qualname__'):\n state['qualname'] = func.__qualname__\n save(state)\n write(pickle.TUPLE)\n write(pickle.REDUCE)" }, { "instruction": "Write or improve a Python function based on this description:\n\nSave a \"global\".\n\n The name of this method is somewhat misleading: all types get\n dispatched here.", "output": "def save_global(self, obj, name=None, pack=struct.pack):\n \"\"\"\n Save a \"global\".\n\n The name of this method is somewhat misleading: all types get\n dispatched here.\n \"\"\"\n if obj is type(None):\n return self.save_reduce(type, (None,), obj=obj)\n elif obj is type(Ellipsis):\n return self.save_reduce(type, (Ellipsis,), obj=obj)\n elif obj is type(NotImplemented):\n return self.save_reduce(type, (NotImplemented,), obj=obj)\n\n if obj.__module__ == \"__main__\":\n return self.save_dynamic_class(obj)\n\n try:\n return Pickler.save_global(self, obj, name=name)\n except Exception:\n if obj.__module__ == \"__builtin__\" or obj.__module__ == \"builtins\":\n if obj in _BUILTIN_TYPE_NAMES:\n return self.save_reduce(\n _builtin_type, (_BUILTIN_TYPE_NAMES[obj],), obj=obj)\n\n typ = type(obj)\n if typ is not obj and isinstance(obj, (type, types.ClassType)):\n return self.save_dynamic_class(obj)\n\n raise" }, { "instruction": "Write or improve a Python function based on this description:\n\nInner logic to save instance. Based off pickle.save_inst", "output": "def save_inst(self, obj):\n \"\"\"Inner logic to save instance. Based off pickle.save_inst\"\"\"\n cls = obj.__class__\n\n # Try the dispatch table (pickle module doesn't do it)\n f = self.dispatch.get(cls)\n if f:\n f(self, obj) # Call unbound method with explicit self\n return\n\n memo = self.memo\n write = self.write\n save = self.save\n\n if hasattr(obj, '__getinitargs__'):\n args = obj.__getinitargs__()\n len(args) # XXX Assert it's a sequence\n pickle._keep_alive(args, memo)\n else:\n args = ()\n\n write(pickle.MARK)\n\n if self.bin:\n save(cls)\n for arg in args:\n save(arg)\n write(pickle.OBJ)\n else:\n for arg in args:\n save(arg)\n write(pickle.INST + cls.__module__ + '\\n' + cls.__name__ + '\\n')\n\n self.memoize(obj)\n\n try:\n getstate = obj.__getstate__\n except AttributeError:\n stuff = obj.__dict__\n else:\n stuff = getstate()\n pickle._keep_alive(stuff, memo)\n save(stuff)\n write(pickle.BUILD)" }, { "instruction": "Write or improve a Python function based on this description:\n\nitemgetter serializer (needed for namedtuple support)", "output": "def save_itemgetter(self, obj):\n \"\"\"itemgetter serializer (needed for namedtuple support)\"\"\"\n class Dummy:\n def __getitem__(self, item):\n return item\n items = obj(Dummy())\n if not isinstance(items, tuple):\n items = (items,)\n return self.save_reduce(operator.itemgetter, items)" }, { "instruction": "Write or improve a Python function based on this description:\n\nattrgetter serializer", "output": "def save_attrgetter(self, obj):\n \"\"\"attrgetter serializer\"\"\"\n class Dummy(object):\n def __init__(self, attrs, index=None):\n self.attrs = attrs\n self.index = index\n def __getattribute__(self, item):\n attrs = object.__getattribute__(self, \"attrs\")\n index = object.__getattribute__(self, \"index\")\n if index is None:\n index = len(attrs)\n attrs.append(item)\n else:\n attrs[index] = \".\".join([attrs[index], item])\n return type(self)(attrs, index)\n attrs = []\n obj(Dummy(attrs))\n return self.save_reduce(operator.attrgetter, tuple(attrs))" }, { "instruction": "Write or improve a Python function based on this description:\n\nCopy the current param to a new parent, must be a dummy param.", "output": "def _copy_new_parent(self, parent):\n \"\"\"Copy the current param to a new parent, must be a dummy param.\"\"\"\n if self.parent == \"undefined\":\n param = copy.copy(self)\n param.parent = parent.uid\n return param\n else:\n raise ValueError(\"Cannot copy from non-dummy parent %s.\" % parent)" }, { "instruction": "Write or improve a Python function based on this description:\n\nConvert a value to a list, if possible.", "output": "def toList(value):\n \"\"\"\n Convert a value to a list, if possible.\n \"\"\"\n if type(value) == list:\n return value\n elif type(value) in [np.ndarray, tuple, xrange, array.array]:\n return list(value)\n elif isinstance(value, Vector):\n return list(value.toArray())\n else:\n raise TypeError(\"Could not convert %s to list\" % value)" }, { "instruction": "Write or improve a Python function based on this description:\n\nConvert a value to list of floats, if possible.", "output": "def toListFloat(value):\n \"\"\"\n Convert a value to list of floats, if possible.\n \"\"\"\n if TypeConverters._can_convert_to_list(value):\n value = TypeConverters.toList(value)\n if all(map(lambda v: TypeConverters._is_numeric(v), value)):\n return [float(v) for v in value]\n raise TypeError(\"Could not convert %s to list of floats\" % value)" }, { "instruction": "Write or improve a Python function based on this description:\n\nConvert a value to list of ints, if possible.", "output": "def toListInt(value):\n \"\"\"\n Convert a value to list of ints, if possible.\n \"\"\"\n if TypeConverters._can_convert_to_list(value):\n value = TypeConverters.toList(value)\n if all(map(lambda v: TypeConverters._is_integer(v), value)):\n return [int(v) for v in value]\n raise TypeError(\"Could not convert %s to list of ints\" % value)" }, { "instruction": "Write or improve a Python function based on this description:\n\nConvert a value to list of strings, if possible.", "output": "def toListString(value):\n \"\"\"\n Convert a value to list of strings, if possible.\n \"\"\"\n if TypeConverters._can_convert_to_list(value):\n value = TypeConverters.toList(value)\n if all(map(lambda v: TypeConverters._can_convert_to_string(v), value)):\n return [TypeConverters.toString(v) for v in value]\n raise TypeError(\"Could not convert %s to list of strings\" % value)" }, { "instruction": "Write or improve a Python function based on this description:\n\nConvert a value to a MLlib Vector, if possible.", "output": "def toVector(value):\n \"\"\"\n Convert a value to a MLlib Vector, if possible.\n \"\"\"\n if isinstance(value, Vector):\n return value\n elif TypeConverters._can_convert_to_list(value):\n value = TypeConverters.toList(value)\n if all(map(lambda v: TypeConverters._is_numeric(v), value)):\n return DenseVector(value)\n raise TypeError(\"Could not convert %s to vector\" % value)" }, { "instruction": "Write or improve a Python function based on this description:\n\nConvert a value to a string, if possible.", "output": "def toString(value):\n \"\"\"\n Convert a value to a string, if possible.\n \"\"\"\n if isinstance(value, basestring):\n return value\n elif type(value) in [np.string_, np.str_]:\n return str(value)\n elif type(value) == np.unicode_:\n return unicode(value)\n else:\n raise TypeError(\"Could not convert %s to string type\" % type(value))" }, { "instruction": "Write or improve a Python function based on this description:\n\nCopy all params defined on the class to current object.", "output": "def _copy_params(self):\n \"\"\"\n Copy all params defined on the class to current object.\n \"\"\"\n cls = type(self)\n src_name_attrs = [(x, getattr(cls, x)) for x in dir(cls)]\n src_params = list(filter(lambda nameAttr: isinstance(nameAttr[1], Param), src_name_attrs))\n for name, param in src_params:\n setattr(self, name, param._copy_new_parent(self))" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns all params ordered by name. The default implementation\n uses :py:func:`dir` to get all attributes of type\n :py:class:`Param`.", "output": "def params(self):\n \"\"\"\n Returns all params ordered by name. The default implementation\n uses :py:func:`dir` to get all attributes of type\n :py:class:`Param`.\n \"\"\"\n if self._params is None:\n self._params = list(filter(lambda attr: isinstance(attr, Param),\n [getattr(self, x) for x in dir(self) if x != \"params\" and\n not isinstance(getattr(type(self), x, None), property)]))\n return self._params" }, { "instruction": "Write or improve a Python function based on this description:\n\nExplains a single param and returns its name, doc, and optional\n default value and user-supplied value in a string.", "output": "def explainParam(self, param):\n \"\"\"\n Explains a single param and returns its name, doc, and optional\n default value and user-supplied value in a string.\n \"\"\"\n param = self._resolveParam(param)\n values = []\n if self.isDefined(param):\n if param in self._defaultParamMap:\n values.append(\"default: %s\" % self._defaultParamMap[param])\n if param in self._paramMap:\n values.append(\"current: %s\" % self._paramMap[param])\n else:\n values.append(\"undefined\")\n valueStr = \"(\" + \", \".join(values) + \")\"\n return \"%s: %s %s\" % (param.name, param.doc, valueStr)" }, { "instruction": "Write or improve a Python function based on this description:\n\nGets a param by its name.", "output": "def getParam(self, paramName):\n \"\"\"\n Gets a param by its name.\n \"\"\"\n param = getattr(self, paramName)\n if isinstance(param, Param):\n return param\n else:\n raise ValueError(\"Cannot find param with name %s.\" % paramName)" }, { "instruction": "Write or improve a Python function based on this description:\n\nChecks whether a param is explicitly set by user.", "output": "def isSet(self, param):\n \"\"\"\n Checks whether a param is explicitly set by user.\n \"\"\"\n param = self._resolveParam(param)\n return param in self._paramMap" }, { "instruction": "Write or improve a Python function based on this description:\n\nChecks whether a param has a default value.", "output": "def hasDefault(self, param):\n \"\"\"\n Checks whether a param has a default value.\n \"\"\"\n param = self._resolveParam(param)\n return param in self._defaultParamMap" }, { "instruction": "Write or improve a Python function based on this description:\n\nTests whether this instance contains a param with a given\n (string) name.", "output": "def hasParam(self, paramName):\n \"\"\"\n Tests whether this instance contains a param with a given\n (string) name.\n \"\"\"\n if isinstance(paramName, basestring):\n p = getattr(self, paramName, None)\n return isinstance(p, Param)\n else:\n raise TypeError(\"hasParam(): paramName must be a string\")" }, { "instruction": "Write or improve a Python function based on this description:\n\nGets the value of a param in the user-supplied param map or its\n default value. Raises an error if neither is set.", "output": "def getOrDefault(self, param):\n \"\"\"\n Gets the value of a param in the user-supplied param map or its\n default value. Raises an error if neither is set.\n \"\"\"\n param = self._resolveParam(param)\n if param in self._paramMap:\n return self._paramMap[param]\n else:\n return self._defaultParamMap[param]" }, { "instruction": "Write or improve a Python function based on this description:\n\nExtracts the embedded default param values and user-supplied\n values, and then merges them with extra values from input into\n a flat param map, where the latter value is used if there exist\n conflicts, i.e., with ordering: default param values <\n user-supplied values < extra.\n\n :param extra: extra param values\n :return: merged param map", "output": "def extractParamMap(self, extra=None):\n \"\"\"\n Extracts the embedded default param values and user-supplied\n values, and then merges them with extra values from input into\n a flat param map, where the latter value is used if there exist\n conflicts, i.e., with ordering: default param values <\n user-supplied values < extra.\n\n :param extra: extra param values\n :return: merged param map\n \"\"\"\n if extra is None:\n extra = dict()\n paramMap = self._defaultParamMap.copy()\n paramMap.update(self._paramMap)\n paramMap.update(extra)\n return paramMap" }, { "instruction": "Write or improve a Python function based on this description:\n\nCreates a copy of this instance with the same uid and some\n extra params. The default implementation creates a\n shallow copy using :py:func:`copy.copy`, and then copies the\n embedded and extra parameters over and returns the copy.\n Subclasses should override this method if the default approach\n is not sufficient.\n\n :param extra: Extra parameters to copy to the new instance\n :return: Copy of this instance", "output": "def copy(self, extra=None):\n \"\"\"\n Creates a copy of this instance with the same uid and some\n extra params. The default implementation creates a\n shallow copy using :py:func:`copy.copy`, and then copies the\n embedded and extra parameters over and returns the copy.\n Subclasses should override this method if the default approach\n is not sufficient.\n\n :param extra: Extra parameters to copy to the new instance\n :return: Copy of this instance\n \"\"\"\n if extra is None:\n extra = dict()\n that = copy.copy(self)\n that._paramMap = {}\n that._defaultParamMap = {}\n return self._copyValues(that, extra)" }, { "instruction": "Write or improve a Python function based on this description:\n\nSets a parameter in the embedded param map.", "output": "def set(self, param, value):\n \"\"\"\n Sets a parameter in the embedded param map.\n \"\"\"\n self._shouldOwn(param)\n try:\n value = param.typeConverter(value)\n except ValueError as e:\n raise ValueError('Invalid param value given for param \"%s\". %s' % (param.name, e))\n self._paramMap[param] = value" }, { "instruction": "Write or improve a Python function based on this description:\n\nValidates that the input param belongs to this Params instance.", "output": "def _shouldOwn(self, param):\n \"\"\"\n Validates that the input param belongs to this Params instance.\n \"\"\"\n if not (self.uid == param.parent and self.hasParam(param.name)):\n raise ValueError(\"Param %r does not belong to %r.\" % (param, self))" }, { "instruction": "Write or improve a Python function based on this description:\n\nResolves a param and validates the ownership.\n\n :param param: param name or the param instance, which must\n belong to this Params instance\n :return: resolved param instance", "output": "def _resolveParam(self, param):\n \"\"\"\n Resolves a param and validates the ownership.\n\n :param param: param name or the param instance, which must\n belong to this Params instance\n :return: resolved param instance\n \"\"\"\n if isinstance(param, Param):\n self._shouldOwn(param)\n return param\n elif isinstance(param, basestring):\n return self.getParam(param)\n else:\n raise ValueError(\"Cannot resolve %r as a param.\" % param)" }, { "instruction": "Write or improve a Python function based on this description:\n\nSets user-supplied params.", "output": "def _set(self, **kwargs):\n \"\"\"\n Sets user-supplied params.\n \"\"\"\n for param, value in kwargs.items():\n p = getattr(self, param)\n if value is not None:\n try:\n value = p.typeConverter(value)\n except TypeError as e:\n raise TypeError('Invalid param value given for param \"%s\". %s' % (p.name, e))\n self._paramMap[p] = value\n return self" }, { "instruction": "Write or improve a Python function based on this description:\n\nSets default params.", "output": "def _setDefault(self, **kwargs):\n \"\"\"\n Sets default params.\n \"\"\"\n for param, value in kwargs.items():\n p = getattr(self, param)\n if value is not None and not isinstance(value, JavaObject):\n try:\n value = p.typeConverter(value)\n except TypeError as e:\n raise TypeError('Invalid default param value given for param \"%s\". %s'\n % (p.name, e))\n self._defaultParamMap[p] = value\n return self" }, { "instruction": "Write or improve a Python function based on this description:\n\nCopies param values from this instance to another instance for\n params shared by them.\n\n :param to: the target instance\n :param extra: extra params to be copied\n :return: the target instance with param values copied", "output": "def _copyValues(self, to, extra=None):\n \"\"\"\n Copies param values from this instance to another instance for\n params shared by them.\n\n :param to: the target instance\n :param extra: extra params to be copied\n :return: the target instance with param values copied\n \"\"\"\n paramMap = self._paramMap.copy()\n if extra is not None:\n paramMap.update(extra)\n for param in self.params:\n # copy default params\n if param in self._defaultParamMap and to.hasParam(param.name):\n to._defaultParamMap[to.getParam(param.name)] = self._defaultParamMap[param]\n # copy explicitly set params\n if param in paramMap and to.hasParam(param.name):\n to._set(**{param.name: paramMap[param]})\n return to" }, { "instruction": "Write or improve a Python function based on this description:\n\nChanges the uid of this instance. This updates both\n the stored uid and the parent uid of params and param maps.\n This is used by persistence (loading).\n :param newUid: new uid to use, which is converted to unicode\n :return: same instance, but with the uid and Param.parent values\n updated, including within param maps", "output": "def _resetUid(self, newUid):\n \"\"\"\n Changes the uid of this instance. This updates both\n the stored uid and the parent uid of params and param maps.\n This is used by persistence (loading).\n :param newUid: new uid to use, which is converted to unicode\n :return: same instance, but with the uid and Param.parent values\n updated, including within param maps\n \"\"\"\n newUid = unicode(newUid)\n self.uid = newUid\n newDefaultParamMap = dict()\n newParamMap = dict()\n for param in self.params:\n newParam = copy.copy(param)\n newParam.parent = newUid\n if param in self._defaultParamMap:\n newDefaultParamMap[newParam] = self._defaultParamMap[param]\n if param in self._paramMap:\n newParamMap[newParam] = self._paramMap[param]\n param.parent = newUid\n self._defaultParamMap = newDefaultParamMap\n self._paramMap = newParamMap\n return self" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn an JavaRDD of Object by unpickling\n\n It will convert each Python object into Java object by Pyrolite, whenever the\n RDD is serialized in batch or not.", "output": "def _to_java_object_rdd(rdd):\n \"\"\" Return an JavaRDD of Object by unpickling\n\n It will convert each Python object into Java object by Pyrolite, whenever the\n RDD is serialized in batch or not.\n \"\"\"\n rdd = rdd._reserialize(AutoBatchedSerializer(PickleSerializer()))\n return rdd.ctx._jvm.org.apache.spark.ml.python.MLSerDe.pythonToJava(rdd._jrdd, True)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn the broadcasted value", "output": "def value(self):\n \"\"\" Return the broadcasted value\n \"\"\"\n if not hasattr(self, \"_value\") and self._path is not None:\n # we only need to decrypt it here when encryption is enabled and\n # if its on the driver, since executor decryption is handled already\n if self._sc is not None and self._sc._encryption_enabled:\n port, auth_secret = self._python_broadcast.setupDecryptionServer()\n (decrypted_sock_file, _) = local_connect_and_auth(port, auth_secret)\n self._python_broadcast.waitTillBroadcastDataSent()\n return self.load(decrypted_sock_file)\n else:\n self._value = self.load_from_path(self._path)\n return self._value" }, { "instruction": "Write or improve a Python function based on this description:\n\nDelete cached copies of this broadcast on the executors. If the\n broadcast is used after this is called, it will need to be\n re-sent to each executor.\n\n :param blocking: Whether to block until unpersisting has completed", "output": "def unpersist(self, blocking=False):\n \"\"\"\n Delete cached copies of this broadcast on the executors. If the\n broadcast is used after this is called, it will need to be\n re-sent to each executor.\n\n :param blocking: Whether to block until unpersisting has completed\n \"\"\"\n if self._jbroadcast is None:\n raise Exception(\"Broadcast can only be unpersisted in driver\")\n self._jbroadcast.unpersist(blocking)" }, { "instruction": "Write or improve a Python function based on this description:\n\nDestroy all data and metadata related to this broadcast variable.\n Use this with caution; once a broadcast variable has been destroyed,\n it cannot be used again.\n\n .. versionchanged:: 3.0.0\n Added optional argument `blocking` to specify whether to block until all\n blocks are deleted.", "output": "def destroy(self, blocking=False):\n \"\"\"\n Destroy all data and metadata related to this broadcast variable.\n Use this with caution; once a broadcast variable has been destroyed,\n it cannot be used again.\n\n .. versionchanged:: 3.0.0\n Added optional argument `blocking` to specify whether to block until all\n blocks are deleted.\n \"\"\"\n if self._jbroadcast is None:\n raise Exception(\"Broadcast can only be destroyed in driver\")\n self._jbroadcast.destroy(blocking)\n os.unlink(self._path)" }, { "instruction": "Write or improve a Python function based on this description:\n\nWrap this udf with a function and attach docstring from func", "output": "def _wrapped(self):\n \"\"\"\n Wrap this udf with a function and attach docstring from func\n \"\"\"\n\n # It is possible for a callable instance without __name__ attribute or/and\n # __module__ attribute to be wrapped here. For example, functools.partial. In this case,\n # we should avoid wrapping the attributes from the wrapped function to the wrapper\n # function. So, we take out these attribute names from the default names to set and\n # then manually assign it after being wrapped.\n assignments = tuple(\n a for a in functools.WRAPPER_ASSIGNMENTS if a != '__name__' and a != '__module__')\n\n @functools.wraps(self.func, assigned=assignments)\n def wrapper(*args):\n return self(*args)\n\n wrapper.__name__ = self._name\n wrapper.__module__ = (self.func.__module__ if hasattr(self.func, '__module__')\n else self.func.__class__.__module__)\n\n wrapper.func = self.func\n wrapper.returnType = self.returnType\n wrapper.evalType = self.evalType\n wrapper.deterministic = self.deterministic\n wrapper.asNondeterministic = functools.wraps(\n self.asNondeterministic)(lambda: self.asNondeterministic()._wrapped())\n return wrapper" }, { "instruction": "Write or improve a Python function based on this description:\n\nRegister a Python function (including lambda function) or a user-defined function\n as a SQL function.\n\n :param name: name of the user-defined function in SQL statements.\n :param f: a Python function, or a user-defined function. The user-defined function can\n be either row-at-a-time or vectorized. See :meth:`pyspark.sql.functions.udf` and\n :meth:`pyspark.sql.functions.pandas_udf`.\n :param returnType: the return type of the registered user-defined function. The value can\n be either a :class:`pyspark.sql.types.DataType` object or a DDL-formatted type string.\n :return: a user-defined function.\n\n To register a nondeterministic Python function, users need to first build\n a nondeterministic user-defined function for the Python function and then register it\n as a SQL function.\n\n `returnType` can be optionally specified when `f` is a Python function but not\n when `f` is a user-defined function. Please see below.\n\n 1. When `f` is a Python function:\n\n `returnType` defaults to string type and can be optionally specified. The produced\n object must match the specified type. In this case, this API works as if\n `register(name, f, returnType=StringType())`.\n\n >>> strlen = spark.udf.register(\"stringLengthString\", lambda x: len(x))\n >>> spark.sql(\"SELECT stringLengthString('test')\").collect()\n [Row(stringLengthString(test)=u'4')]\n\n >>> spark.sql(\"SELECT 'foo' AS text\").select(strlen(\"text\")).collect()\n [Row(stringLengthString(text)=u'3')]\n\n >>> from pyspark.sql.types import IntegerType\n >>> _ = spark.udf.register(\"stringLengthInt\", lambda x: len(x), IntegerType())\n >>> spark.sql(\"SELECT stringLengthInt('test')\").collect()\n [Row(stringLengthInt(test)=4)]\n\n >>> from pyspark.sql.types import IntegerType\n >>> _ = spark.udf.register(\"stringLengthInt\", lambda x: len(x), IntegerType())\n >>> spark.sql(\"SELECT stringLengthInt('test')\").collect()\n [Row(stringLengthInt(test)=4)]\n\n 2. When `f` is a user-defined function:\n\n Spark uses the return type of the given user-defined function as the return type of\n the registered user-defined function. `returnType` should not be specified.\n In this case, this API works as if `register(name, f)`.\n\n >>> from pyspark.sql.types import IntegerType\n >>> from pyspark.sql.functions import udf\n >>> slen = udf(lambda s: len(s), IntegerType())\n >>> _ = spark.udf.register(\"slen\", slen)\n >>> spark.sql(\"SELECT slen('test')\").collect()\n [Row(slen(test)=4)]\n\n >>> import random\n >>> from pyspark.sql.functions import udf\n >>> from pyspark.sql.types import IntegerType\n >>> random_udf = udf(lambda: random.randint(0, 100), IntegerType()).asNondeterministic()\n >>> new_random_udf = spark.udf.register(\"random_udf\", random_udf)\n >>> spark.sql(\"SELECT random_udf()\").collect() # doctest: +SKIP\n [Row(random_udf()=82)]\n\n >>> from pyspark.sql.functions import pandas_udf, PandasUDFType\n >>> @pandas_udf(\"integer\", PandasUDFType.SCALAR) # doctest: +SKIP\n ... def add_one(x):\n ... return x + 1\n ...\n >>> _ = spark.udf.register(\"add_one\", add_one) # doctest: +SKIP\n >>> spark.sql(\"SELECT add_one(id) FROM range(3)\").collect() # doctest: +SKIP\n [Row(add_one(id)=1), Row(add_one(id)=2), Row(add_one(id)=3)]\n\n >>> @pandas_udf(\"integer\", PandasUDFType.GROUPED_AGG) # doctest: +SKIP\n ... def sum_udf(v):\n ... return v.sum()\n ...\n >>> _ = spark.udf.register(\"sum_udf\", sum_udf) # doctest: +SKIP\n >>> q = \"SELECT sum_udf(v1) FROM VALUES (3, 0), (2, 0), (1, 1) tbl(v1, v2) GROUP BY v2\"\n >>> spark.sql(q).collect() # doctest: +SKIP\n [Row(sum_udf(v1)=1), Row(sum_udf(v1)=5)]\n\n .. note:: Registration for a user-defined function (case 2.) was added from\n Spark 2.3.0.", "output": "def register(self, name, f, returnType=None):\n \"\"\"Register a Python function (including lambda function) or a user-defined function\n as a SQL function.\n\n :param name: name of the user-defined function in SQL statements.\n :param f: a Python function, or a user-defined function. The user-defined function can\n be either row-at-a-time or vectorized. See :meth:`pyspark.sql.functions.udf` and\n :meth:`pyspark.sql.functions.pandas_udf`.\n :param returnType: the return type of the registered user-defined function. The value can\n be either a :class:`pyspark.sql.types.DataType` object or a DDL-formatted type string.\n :return: a user-defined function.\n\n To register a nondeterministic Python function, users need to first build\n a nondeterministic user-defined function for the Python function and then register it\n as a SQL function.\n\n `returnType` can be optionally specified when `f` is a Python function but not\n when `f` is a user-defined function. Please see below.\n\n 1. When `f` is a Python function:\n\n `returnType` defaults to string type and can be optionally specified. The produced\n object must match the specified type. In this case, this API works as if\n `register(name, f, returnType=StringType())`.\n\n >>> strlen = spark.udf.register(\"stringLengthString\", lambda x: len(x))\n >>> spark.sql(\"SELECT stringLengthString('test')\").collect()\n [Row(stringLengthString(test)=u'4')]\n\n >>> spark.sql(\"SELECT 'foo' AS text\").select(strlen(\"text\")).collect()\n [Row(stringLengthString(text)=u'3')]\n\n >>> from pyspark.sql.types import IntegerType\n >>> _ = spark.udf.register(\"stringLengthInt\", lambda x: len(x), IntegerType())\n >>> spark.sql(\"SELECT stringLengthInt('test')\").collect()\n [Row(stringLengthInt(test)=4)]\n\n >>> from pyspark.sql.types import IntegerType\n >>> _ = spark.udf.register(\"stringLengthInt\", lambda x: len(x), IntegerType())\n >>> spark.sql(\"SELECT stringLengthInt('test')\").collect()\n [Row(stringLengthInt(test)=4)]\n\n 2. When `f` is a user-defined function:\n\n Spark uses the return type of the given user-defined function as the return type of\n the registered user-defined function. `returnType` should not be specified.\n In this case, this API works as if `register(name, f)`.\n\n >>> from pyspark.sql.types import IntegerType\n >>> from pyspark.sql.functions import udf\n >>> slen = udf(lambda s: len(s), IntegerType())\n >>> _ = spark.udf.register(\"slen\", slen)\n >>> spark.sql(\"SELECT slen('test')\").collect()\n [Row(slen(test)=4)]\n\n >>> import random\n >>> from pyspark.sql.functions import udf\n >>> from pyspark.sql.types import IntegerType\n >>> random_udf = udf(lambda: random.randint(0, 100), IntegerType()).asNondeterministic()\n >>> new_random_udf = spark.udf.register(\"random_udf\", random_udf)\n >>> spark.sql(\"SELECT random_udf()\").collect() # doctest: +SKIP\n [Row(random_udf()=82)]\n\n >>> from pyspark.sql.functions import pandas_udf, PandasUDFType\n >>> @pandas_udf(\"integer\", PandasUDFType.SCALAR) # doctest: +SKIP\n ... def add_one(x):\n ... return x + 1\n ...\n >>> _ = spark.udf.register(\"add_one\", add_one) # doctest: +SKIP\n >>> spark.sql(\"SELECT add_one(id) FROM range(3)\").collect() # doctest: +SKIP\n [Row(add_one(id)=1), Row(add_one(id)=2), Row(add_one(id)=3)]\n\n >>> @pandas_udf(\"integer\", PandasUDFType.GROUPED_AGG) # doctest: +SKIP\n ... def sum_udf(v):\n ... return v.sum()\n ...\n >>> _ = spark.udf.register(\"sum_udf\", sum_udf) # doctest: +SKIP\n >>> q = \"SELECT sum_udf(v1) FROM VALUES (3, 0), (2, 0), (1, 1) tbl(v1, v2) GROUP BY v2\"\n >>> spark.sql(q).collect() # doctest: +SKIP\n [Row(sum_udf(v1)=1), Row(sum_udf(v1)=5)]\n\n .. note:: Registration for a user-defined function (case 2.) was added from\n Spark 2.3.0.\n \"\"\"\n\n # This is to check whether the input function is from a user-defined function or\n # Python function.\n if hasattr(f, 'asNondeterministic'):\n if returnType is not None:\n raise TypeError(\n \"Invalid returnType: data type can not be specified when f is\"\n \"a user-defined function, but got %s.\" % returnType)\n if f.evalType not in [PythonEvalType.SQL_BATCHED_UDF,\n PythonEvalType.SQL_SCALAR_PANDAS_UDF,\n PythonEvalType.SQL_GROUPED_AGG_PANDAS_UDF]:\n raise ValueError(\n \"Invalid f: f must be SQL_BATCHED_UDF, SQL_SCALAR_PANDAS_UDF or \"\n \"SQL_GROUPED_AGG_PANDAS_UDF\")\n register_udf = UserDefinedFunction(f.func, returnType=f.returnType, name=name,\n evalType=f.evalType,\n deterministic=f.deterministic)\n return_udf = f\n else:\n if returnType is None:\n returnType = StringType()\n register_udf = UserDefinedFunction(f, returnType=returnType, name=name,\n evalType=PythonEvalType.SQL_BATCHED_UDF)\n return_udf = register_udf._wrapped()\n self.sparkSession._jsparkSession.udf().registerPython(name, register_udf._judf)\n return return_udf" }, { "instruction": "Write or improve a Python function based on this description:\n\nRegister a Java user-defined function as a SQL function.\n\n In addition to a name and the function itself, the return type can be optionally specified.\n When the return type is not specified we would infer it via reflection.\n\n :param name: name of the user-defined function\n :param javaClassName: fully qualified name of java class\n :param returnType: the return type of the registered Java function. The value can be either\n a :class:`pyspark.sql.types.DataType` object or a DDL-formatted type string.\n\n >>> from pyspark.sql.types import IntegerType\n >>> spark.udf.registerJavaFunction(\n ... \"javaStringLength\", \"test.org.apache.spark.sql.JavaStringLength\", IntegerType())\n >>> spark.sql(\"SELECT javaStringLength('test')\").collect()\n [Row(UDF:javaStringLength(test)=4)]\n\n >>> spark.udf.registerJavaFunction(\n ... \"javaStringLength2\", \"test.org.apache.spark.sql.JavaStringLength\")\n >>> spark.sql(\"SELECT javaStringLength2('test')\").collect()\n [Row(UDF:javaStringLength2(test)=4)]\n\n >>> spark.udf.registerJavaFunction(\n ... \"javaStringLength3\", \"test.org.apache.spark.sql.JavaStringLength\", \"integer\")\n >>> spark.sql(\"SELECT javaStringLength3('test')\").collect()\n [Row(UDF:javaStringLength3(test)=4)]", "output": "def registerJavaFunction(self, name, javaClassName, returnType=None):\n \"\"\"Register a Java user-defined function as a SQL function.\n\n In addition to a name and the function itself, the return type can be optionally specified.\n When the return type is not specified we would infer it via reflection.\n\n :param name: name of the user-defined function\n :param javaClassName: fully qualified name of java class\n :param returnType: the return type of the registered Java function. The value can be either\n a :class:`pyspark.sql.types.DataType` object or a DDL-formatted type string.\n\n >>> from pyspark.sql.types import IntegerType\n >>> spark.udf.registerJavaFunction(\n ... \"javaStringLength\", \"test.org.apache.spark.sql.JavaStringLength\", IntegerType())\n >>> spark.sql(\"SELECT javaStringLength('test')\").collect()\n [Row(UDF:javaStringLength(test)=4)]\n\n >>> spark.udf.registerJavaFunction(\n ... \"javaStringLength2\", \"test.org.apache.spark.sql.JavaStringLength\")\n >>> spark.sql(\"SELECT javaStringLength2('test')\").collect()\n [Row(UDF:javaStringLength2(test)=4)]\n\n >>> spark.udf.registerJavaFunction(\n ... \"javaStringLength3\", \"test.org.apache.spark.sql.JavaStringLength\", \"integer\")\n >>> spark.sql(\"SELECT javaStringLength3('test')\").collect()\n [Row(UDF:javaStringLength3(test)=4)]\n \"\"\"\n\n jdt = None\n if returnType is not None:\n if not isinstance(returnType, DataType):\n returnType = _parse_datatype_string(returnType)\n jdt = self.sparkSession._jsparkSession.parseDataType(returnType.json())\n self.sparkSession._jsparkSession.udf().registerJava(name, javaClassName, jdt)" }, { "instruction": "Write or improve a Python function based on this description:\n\nRegister a Java user-defined aggregate function as a SQL function.\n\n :param name: name of the user-defined aggregate function\n :param javaClassName: fully qualified name of java class\n\n >>> spark.udf.registerJavaUDAF(\"javaUDAF\", \"test.org.apache.spark.sql.MyDoubleAvg\")\n >>> df = spark.createDataFrame([(1, \"a\"),(2, \"b\"), (3, \"a\")],[\"id\", \"name\"])\n >>> df.createOrReplaceTempView(\"df\")\n >>> spark.sql(\"SELECT name, javaUDAF(id) as avg from df group by name\").collect()\n [Row(name=u'b', avg=102.0), Row(name=u'a', avg=102.0)]", "output": "def registerJavaUDAF(self, name, javaClassName):\n \"\"\"Register a Java user-defined aggregate function as a SQL function.\n\n :param name: name of the user-defined aggregate function\n :param javaClassName: fully qualified name of java class\n\n >>> spark.udf.registerJavaUDAF(\"javaUDAF\", \"test.org.apache.spark.sql.MyDoubleAvg\")\n >>> df = spark.createDataFrame([(1, \"a\"),(2, \"b\"), (3, \"a\")],[\"id\", \"name\"])\n >>> df.createOrReplaceTempView(\"df\")\n >>> spark.sql(\"SELECT name, javaUDAF(id) as avg from df group by name\").collect()\n [Row(name=u'b', avg=102.0), Row(name=u'a', avg=102.0)]\n \"\"\"\n\n self.sparkSession._jsparkSession.udf().registerJavaUDAF(name, javaClassName)" }, { "instruction": "Write or improve a Python function based on this description:\n\nEither recreate a StreamingContext from checkpoint data or create a new StreamingContext.\n If checkpoint data exists in the provided `checkpointPath`, then StreamingContext will be\n recreated from the checkpoint data. If the data does not exist, then the provided setupFunc\n will be used to create a new context.\n\n @param checkpointPath: Checkpoint directory used in an earlier streaming program\n @param setupFunc: Function to create a new context and setup DStreams", "output": "def getOrCreate(cls, checkpointPath, setupFunc):\n \"\"\"\n Either recreate a StreamingContext from checkpoint data or create a new StreamingContext.\n If checkpoint data exists in the provided `checkpointPath`, then StreamingContext will be\n recreated from the checkpoint data. If the data does not exist, then the provided setupFunc\n will be used to create a new context.\n\n @param checkpointPath: Checkpoint directory used in an earlier streaming program\n @param setupFunc: Function to create a new context and setup DStreams\n \"\"\"\n cls._ensure_initialized()\n gw = SparkContext._gateway\n\n # Check whether valid checkpoint information exists in the given path\n ssc_option = gw.jvm.StreamingContextPythonHelper().tryRecoverFromCheckpoint(checkpointPath)\n if ssc_option.isEmpty():\n ssc = setupFunc()\n ssc.checkpoint(checkpointPath)\n return ssc\n\n jssc = gw.jvm.JavaStreamingContext(ssc_option.get())\n\n # If there is already an active instance of Python SparkContext use it, or create a new one\n if not SparkContext._active_spark_context:\n jsc = jssc.sparkContext()\n conf = SparkConf(_jconf=jsc.getConf())\n SparkContext(conf=conf, gateway=gw, jsc=jsc)\n\n sc = SparkContext._active_spark_context\n\n # update ctx in serializer\n cls._transformerSerializer.ctx = sc\n return StreamingContext(sc, None, jssc)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn either the currently active StreamingContext (i.e., if there is a context started\n but not stopped) or None.", "output": "def getActive(cls):\n \"\"\"\n Return either the currently active StreamingContext (i.e., if there is a context started\n but not stopped) or None.\n \"\"\"\n activePythonContext = cls._activeContext\n if activePythonContext is not None:\n # Verify that the current running Java StreamingContext is active and is the same one\n # backing the supposedly active Python context\n activePythonContextJavaId = activePythonContext._jssc.ssc().hashCode()\n activeJvmContextOption = activePythonContext._jvm.StreamingContext.getActive()\n\n if activeJvmContextOption.isEmpty():\n cls._activeContext = None\n elif activeJvmContextOption.get().hashCode() != activePythonContextJavaId:\n cls._activeContext = None\n raise Exception(\"JVM's active JavaStreamingContext is not the JavaStreamingContext \"\n \"backing the action Python StreamingContext. This is unexpected.\")\n return cls._activeContext" }, { "instruction": "Write or improve a Python function based on this description:\n\nEither return the active StreamingContext (i.e. currently started but not stopped),\n or recreate a StreamingContext from checkpoint data or create a new StreamingContext\n using the provided setupFunc function. If the checkpointPath is None or does not contain\n valid checkpoint data, then setupFunc will be called to create a new context and setup\n DStreams.\n\n @param checkpointPath: Checkpoint directory used in an earlier streaming program. Can be\n None if the intention is to always create a new context when there\n is no active context.\n @param setupFunc: Function to create a new JavaStreamingContext and setup DStreams", "output": "def getActiveOrCreate(cls, checkpointPath, setupFunc):\n \"\"\"\n Either return the active StreamingContext (i.e. currently started but not stopped),\n or recreate a StreamingContext from checkpoint data or create a new StreamingContext\n using the provided setupFunc function. If the checkpointPath is None or does not contain\n valid checkpoint data, then setupFunc will be called to create a new context and setup\n DStreams.\n\n @param checkpointPath: Checkpoint directory used in an earlier streaming program. Can be\n None if the intention is to always create a new context when there\n is no active context.\n @param setupFunc: Function to create a new JavaStreamingContext and setup DStreams\n \"\"\"\n\n if setupFunc is None:\n raise Exception(\"setupFunc cannot be None\")\n activeContext = cls.getActive()\n if activeContext is not None:\n return activeContext\n elif checkpointPath is not None:\n return cls.getOrCreate(checkpointPath, setupFunc)\n else:\n return setupFunc()" }, { "instruction": "Write or improve a Python function based on this description:\n\nWait for the execution to stop.\n\n @param timeout: time to wait in seconds", "output": "def awaitTermination(self, timeout=None):\n \"\"\"\n Wait for the execution to stop.\n\n @param timeout: time to wait in seconds\n \"\"\"\n if timeout is None:\n self._jssc.awaitTermination()\n else:\n self._jssc.awaitTerminationOrTimeout(int(timeout * 1000))" }, { "instruction": "Write or improve a Python function based on this description:\n\nStop the execution of the streams, with option of ensuring all\n received data has been processed.\n\n @param stopSparkContext: Stop the associated SparkContext or not\n @param stopGracefully: Stop gracefully by waiting for the processing\n of all received data to be completed", "output": "def stop(self, stopSparkContext=True, stopGraceFully=False):\n \"\"\"\n Stop the execution of the streams, with option of ensuring all\n received data has been processed.\n\n @param stopSparkContext: Stop the associated SparkContext or not\n @param stopGracefully: Stop gracefully by waiting for the processing\n of all received data to be completed\n \"\"\"\n self._jssc.stop(stopSparkContext, stopGraceFully)\n StreamingContext._activeContext = None\n if stopSparkContext:\n self._sc.stop()" }, { "instruction": "Write or improve a Python function based on this description:\n\nCreate an input from TCP source hostname:port. Data is received using\n a TCP socket and receive byte is interpreted as UTF8 encoded ``\\\\n`` delimited\n lines.\n\n @param hostname: Hostname to connect to for receiving data\n @param port: Port to connect to for receiving data\n @param storageLevel: Storage level to use for storing the received objects", "output": "def socketTextStream(self, hostname, port, storageLevel=StorageLevel.MEMORY_AND_DISK_2):\n \"\"\"\n Create an input from TCP source hostname:port. Data is received using\n a TCP socket and receive byte is interpreted as UTF8 encoded ``\\\\n`` delimited\n lines.\n\n @param hostname: Hostname to connect to for receiving data\n @param port: Port to connect to for receiving data\n @param storageLevel: Storage level to use for storing the received objects\n \"\"\"\n jlevel = self._sc._getJavaStorageLevel(storageLevel)\n return DStream(self._jssc.socketTextStream(hostname, port, jlevel), self,\n UTF8Deserializer())" }, { "instruction": "Write or improve a Python function based on this description:\n\nCreate an input stream that monitors a Hadoop-compatible file system\n for new files and reads them as text files. Files must be wrriten to the\n monitored directory by \"moving\" them from another location within the same\n file system. File names starting with . are ignored.\n The text files must be encoded as UTF-8.", "output": "def textFileStream(self, directory):\n \"\"\"\n Create an input stream that monitors a Hadoop-compatible file system\n for new files and reads them as text files. Files must be wrriten to the\n monitored directory by \"moving\" them from another location within the same\n file system. File names starting with . are ignored.\n The text files must be encoded as UTF-8.\n \"\"\"\n return DStream(self._jssc.textFileStream(directory), self, UTF8Deserializer())" }, { "instruction": "Write or improve a Python function based on this description:\n\nCreate an input stream that monitors a Hadoop-compatible file system\n for new files and reads them as flat binary files with records of\n fixed length. Files must be written to the monitored directory by \"moving\"\n them from another location within the same file system.\n File names starting with . are ignored.\n\n @param directory: Directory to load data from\n @param recordLength: Length of each record in bytes", "output": "def binaryRecordsStream(self, directory, recordLength):\n \"\"\"\n Create an input stream that monitors a Hadoop-compatible file system\n for new files and reads them as flat binary files with records of\n fixed length. Files must be written to the monitored directory by \"moving\"\n them from another location within the same file system.\n File names starting with . are ignored.\n\n @param directory: Directory to load data from\n @param recordLength: Length of each record in bytes\n \"\"\"\n return DStream(self._jssc.binaryRecordsStream(directory, recordLength), self,\n NoOpSerializer())" }, { "instruction": "Write or improve a Python function based on this description:\n\nCreate an input stream from a queue of RDDs or list. In each batch,\n it will process either one or all of the RDDs returned by the queue.\n\n .. note:: Changes to the queue after the stream is created will not be recognized.\n\n @param rdds: Queue of RDDs\n @param oneAtATime: pick one rdd each time or pick all of them once.\n @param default: The default rdd if no more in rdds", "output": "def queueStream(self, rdds, oneAtATime=True, default=None):\n \"\"\"\n Create an input stream from a queue of RDDs or list. In each batch,\n it will process either one or all of the RDDs returned by the queue.\n\n .. note:: Changes to the queue after the stream is created will not be recognized.\n\n @param rdds: Queue of RDDs\n @param oneAtATime: pick one rdd each time or pick all of them once.\n @param default: The default rdd if no more in rdds\n \"\"\"\n if default and not isinstance(default, RDD):\n default = self._sc.parallelize(default)\n\n if not rdds and default:\n rdds = [rdds]\n\n if rdds and not isinstance(rdds[0], RDD):\n rdds = [self._sc.parallelize(input) for input in rdds]\n self._check_serializers(rdds)\n\n queue = self._jvm.PythonDStream.toRDDQueue([r._jrdd for r in rdds])\n if default:\n default = default._reserialize(rdds[0]._jrdd_deserializer)\n jdstream = self._jssc.queueStream(queue, oneAtATime, default._jrdd)\n else:\n jdstream = self._jssc.queueStream(queue, oneAtATime)\n return DStream(jdstream, self, rdds[0]._jrdd_deserializer)" }, { "instruction": "Write or improve a Python function based on this description:\n\nCreate a new DStream in which each RDD is generated by applying\n a function on RDDs of the DStreams. The order of the JavaRDDs in\n the transform function parameter will be the same as the order\n of corresponding DStreams in the list.", "output": "def transform(self, dstreams, transformFunc):\n \"\"\"\n Create a new DStream in which each RDD is generated by applying\n a function on RDDs of the DStreams. The order of the JavaRDDs in\n the transform function parameter will be the same as the order\n of corresponding DStreams in the list.\n \"\"\"\n jdstreams = [d._jdstream for d in dstreams]\n # change the final serializer to sc.serializer\n func = TransformFunction(self._sc,\n lambda t, *rdds: transformFunc(rdds),\n *[d._jrdd_deserializer for d in dstreams])\n jfunc = self._jvm.TransformFunction(func)\n jdstream = self._jssc.transform(jdstreams, jfunc)\n return DStream(jdstream, self, self._sc.serializer)" }, { "instruction": "Write or improve a Python function based on this description:\n\nCreate a unified DStream from multiple DStreams of the same\n type and same slide duration.", "output": "def union(self, *dstreams):\n \"\"\"\n Create a unified DStream from multiple DStreams of the same\n type and same slide duration.\n \"\"\"\n if not dstreams:\n raise ValueError(\"should have at least one DStream to union\")\n if len(dstreams) == 1:\n return dstreams[0]\n if len(set(s._jrdd_deserializer for s in dstreams)) > 1:\n raise ValueError(\"All DStreams should have same serializer\")\n if len(set(s._slideDuration for s in dstreams)) > 1:\n raise ValueError(\"All DStreams should have same slide duration\")\n cls = SparkContext._jvm.org.apache.spark.streaming.api.java.JavaDStream\n jdstreams = SparkContext._gateway.new_array(cls, len(dstreams))\n for i in range(0, len(dstreams)):\n jdstreams[i] = dstreams[i]._jdstream\n return DStream(self._jssc.union(jdstreams), self, dstreams[0]._jrdd_deserializer)" }, { "instruction": "Write or improve a Python function based on this description:\n\nAdd a [[org.apache.spark.streaming.scheduler.StreamingListener]] object for\n receiving system events related to streaming.", "output": "def addStreamingListener(self, streamingListener):\n \"\"\"\n Add a [[org.apache.spark.streaming.scheduler.StreamingListener]] object for\n receiving system events related to streaming.\n \"\"\"\n self._jssc.addStreamingListener(self._jvm.JavaStreamingListenerWrapper(\n self._jvm.PythonStreamingListenerWrapper(streamingListener)))" }, { "instruction": "Write or improve a Python function based on this description:\n\nLoad tf checkpoints in a pytorch model", "output": "def load_tf_weights_in_gpt2(model, gpt2_checkpoint_path):\n \"\"\" Load tf checkpoints in a pytorch model\n \"\"\"\n try:\n import re\n import numpy as np\n import tensorflow as tf\n except ImportError:\n print(\"Loading a TensorFlow models in PyTorch, requires TensorFlow to be installed. Please see \"\n \"https://www.tensorflow.org/install/ for installation instructions.\")\n raise\n tf_path = os.path.abspath(gpt2_checkpoint_path)\n print(\"Converting TensorFlow checkpoint from {}\".format(tf_path))\n # Load weights from TF model\n init_vars = tf.train.list_variables(tf_path)\n names = []\n arrays = []\n for name, shape in init_vars:\n print(\"Loading TF weight {} with shape {}\".format(name, shape))\n array = tf.train.load_variable(tf_path, name)\n names.append(name)\n arrays.append(array.squeeze())\n\n for name, array in zip(names, arrays):\n name = name[6:] # skip \"model/\"\n name = name.split('/')\n pointer = model\n for m_name in name:\n if re.fullmatch(r'[A-Za-z]+\\d+', m_name):\n l = re.split(r'(\\d+)', m_name)\n else:\n l = [m_name]\n if l[0] == 'w' or l[0] == 'g':\n pointer = getattr(pointer, 'weight')\n elif l[0] == 'b':\n pointer = getattr(pointer, 'bias')\n elif l[0] == 'wpe' or l[0] == 'wte':\n pointer = getattr(pointer, l[0])\n pointer = getattr(pointer, 'weight')\n else:\n pointer = getattr(pointer, l[0])\n if len(l) >= 2:\n num = int(l[1])\n pointer = pointer[num]\n try:\n assert pointer.shape == array.shape\n except AssertionError as e:\n e.args += (pointer.shape, array.shape)\n raise\n print(\"Initialize PyTorch weight {}\".format(name))\n pointer.data = torch.from_numpy(array)\n return model" }, { "instruction": "Write or improve a Python function based on this description:\n\nConstructs a `GPT2Config` from a json file of parameters.", "output": "def from_json_file(cls, json_file):\n \"\"\"Constructs a `GPT2Config` from a json file of parameters.\"\"\"\n with open(json_file, \"r\", encoding=\"utf-8\") as reader:\n text = reader.read()\n return cls.from_dict(json.loads(text))" }, { "instruction": "Write or improve a Python function based on this description:\n\nSave this instance to a json file.", "output": "def to_json_file(self, json_file_path):\n \"\"\" Save this instance to a json file.\"\"\"\n with open(json_file_path, \"w\", encoding='utf-8') as writer:\n writer.write(self.to_json_string())" }, { "instruction": "Write or improve a Python function based on this description:\n\nInitialize the weights.", "output": "def init_weights(self, module):\n \"\"\" Initialize the weights.\n \"\"\"\n if isinstance(module, (nn.Linear, nn.Embedding)):\n # Slightly different from the TF version which uses truncated_normal for initialization\n # cf https://github.com/pytorch/pytorch/pull/5617\n module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)\n elif isinstance(module, LayerNorm):\n module.bias.data.zero_()\n module.weight.data.fill_(1.0)\n if isinstance(module, nn.Linear) and module.bias is not None:\n module.bias.data.zero_()" }, { "instruction": "Write or improve a Python function based on this description:\n\nInstantiate a GPT2PreTrainedModel from a pre-trained model file or a pytorch state dict.\n Download and cache the pre-trained model file if needed.\n\n Params:\n pretrained_model_name_or_path: either:\n - a str with the name of a pre-trained model to load selected in the list of:\n . `gpt2`\n - a path or url to a pretrained model archive containing:\n . `gpt2_config.json` a configuration file for the model\n . `pytorch_model.bin` a PyTorch dump of a GPT2Model instance\n - a path or url to a pretrained model archive containing:\n . `gpt2_config.json` a configuration file for the model\n . a TensorFlow checkpoint with trained weights\n from_tf: should we load the weights from a locally saved TensorFlow checkpoint\n cache_dir: an optional path to a folder in which the pre-trained models will be cached.\n state_dict: an optional state dictionary (collections.OrderedDict object) to use instead of pre-trained models\n *inputs, **kwargs: additional input for the specific GPT class", "output": "def from_pretrained(\n cls, pretrained_model_name_or_path, state_dict=None, cache_dir=None, from_tf=False, *inputs, **kwargs\n ):\n \"\"\"\n Instantiate a GPT2PreTrainedModel from a pre-trained model file or a pytorch state dict.\n Download and cache the pre-trained model file if needed.\n\n Params:\n pretrained_model_name_or_path: either:\n - a str with the name of a pre-trained model to load selected in the list of:\n . `gpt2`\n - a path or url to a pretrained model archive containing:\n . `gpt2_config.json` a configuration file for the model\n . `pytorch_model.bin` a PyTorch dump of a GPT2Model instance\n - a path or url to a pretrained model archive containing:\n . `gpt2_config.json` a configuration file for the model\n . a TensorFlow checkpoint with trained weights\n from_tf: should we load the weights from a locally saved TensorFlow checkpoint\n cache_dir: an optional path to a folder in which the pre-trained models will be cached.\n state_dict: an optional state dictionary (collections.OrderedDict object) to use instead of pre-trained models\n *inputs, **kwargs: additional input for the specific GPT class\n \"\"\"\n if pretrained_model_name_or_path in PRETRAINED_MODEL_ARCHIVE_MAP:\n archive_file = PRETRAINED_MODEL_ARCHIVE_MAP[pretrained_model_name_or_path]\n config_file = PRETRAINED_CONFIG_ARCHIVE_MAP[pretrained_model_name_or_path]\n else:\n archive_file = os.path.join(pretrained_model_name_or_path, WEIGHTS_NAME)\n config_file = os.path.join(pretrained_model_name_or_path, CONFIG_NAME)\n # redirect to the cache, if necessary\n try:\n resolved_archive_file = cached_path(archive_file, cache_dir=cache_dir)\n resolved_config_file = cached_path(config_file, cache_dir=cache_dir)\n except EnvironmentError:\n logger.error(\n \"Model name '{}' was not found in model name list ({}). \"\n \"We assumed '{}' was a path or url but couldn't find files {} and {} \"\n \"at this path or url.\".format(\n pretrained_model_name_or_path, \", \".join(PRETRAINED_MODEL_ARCHIVE_MAP.keys()), pretrained_model_name_or_path,\n archive_file, config_file\n )\n )\n return None\n if resolved_archive_file == archive_file and resolved_config_file == config_file:\n logger.info(\"loading weights file {}\".format(archive_file))\n logger.info(\"loading configuration file {}\".format(config_file))\n else:\n logger.info(\"loading weights file {} from cache at {}\".format(\n archive_file, resolved_archive_file))\n logger.info(\"loading configuration file {} from cache at {}\".format(\n config_file, resolved_config_file))\n # Load config\n config = GPT2Config.from_json_file(resolved_config_file)\n logger.info(\"Model config {}\".format(config))\n # Instantiate model.\n model = cls(config, *inputs, **kwargs)\n if state_dict is None and not from_tf:\n state_dict = torch.load(resolved_archive_file, map_location='cpu')\n if from_tf:\n # Directly load from a TensorFlow checkpoint (stored as NumPy array)\n return load_tf_weights_in_gpt2(model, resolved_archive_file)\n\n old_keys = []\n new_keys = []\n for key in state_dict.keys():\n new_key = None\n if key.endswith(\".g\"):\n new_key = key[:-2] + \".weight\"\n elif key.endswith(\".b\"):\n new_key = key[:-2] + \".bias\"\n elif key.endswith(\".w\"):\n new_key = key[:-2] + \".weight\"\n if new_key:\n old_keys.append(key)\n new_keys.append(new_key)\n for old_key, new_key in zip(old_keys, new_keys):\n state_dict[new_key] = state_dict.pop(old_key)\n\n missing_keys = []\n unexpected_keys = []\n error_msgs = []\n # copy state_dict so _load_from_state_dict can modify it\n metadata = getattr(state_dict, \"_metadata\", None)\n state_dict = state_dict.copy()\n if metadata is not None:\n state_dict._metadata = metadata\n\n def load(module, prefix=\"\"):\n local_metadata = {} if metadata is None else metadata.get(prefix[:-1], {})\n module._load_from_state_dict(\n state_dict, prefix, local_metadata, True, missing_keys, unexpected_keys, error_msgs\n )\n for name, child in module._modules.items():\n if child is not None:\n load(child, prefix + name + \".\")\n\n start_model = model\n if hasattr(model, \"transformer\") and all(not s.startswith('transformer.') for s in state_dict.keys()):\n start_model = model.transformer\n load(start_model, prefix=\"\")\n\n if len(missing_keys) > 0:\n logger.info(\n \"Weights of {} not initialized from pretrained model: {}\".format(model.__class__.__name__, missing_keys)\n )\n if len(unexpected_keys) > 0:\n logger.info(\n \"Weights from pretrained model not used in {}: {}\".format(model.__class__.__name__, unexpected_keys)\n )\n if len(error_msgs) > 0:\n raise RuntimeError(\n \"Error(s) in loading state_dict for {}:\\n\\t{}\".format(model.__class__.__name__, \"\\n\\t\".join(error_msgs))\n )\n\n # Make sure we are still sharing the output and input embeddings after loading weights\n model.set_tied()\n return model" }, { "instruction": "Write or improve a Python function based on this description:\n\nLoads a data file into a list of `InputFeature`s.", "output": "def convert_examples_to_features(examples, seq_length, tokenizer):\n \"\"\"Loads a data file into a list of `InputFeature`s.\"\"\"\n\n features = []\n for (ex_index, example) in enumerate(examples):\n tokens_a = tokenizer.tokenize(example.text_a)\n\n tokens_b = None\n if example.text_b:\n tokens_b = tokenizer.tokenize(example.text_b)\n\n if tokens_b:\n # Modifies `tokens_a` and `tokens_b` in place so that the total\n # length is less than the specified length.\n # Account for [CLS], [SEP], [SEP] with \"- 3\"\n _truncate_seq_pair(tokens_a, tokens_b, seq_length - 3)\n else:\n # Account for [CLS] and [SEP] with \"- 2\"\n if len(tokens_a) > seq_length - 2:\n tokens_a = tokens_a[0:(seq_length - 2)]\n\n # The convention in BERT is:\n # (a) For sequence pairs:\n # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]\n # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1\n # (b) For single sequences:\n # tokens: [CLS] the dog is hairy . [SEP]\n # type_ids: 0 0 0 0 0 0 0\n #\n # Where \"type_ids\" are used to indicate whether this is the first\n # sequence or the second sequence. The embedding vectors for `type=0` and\n # `type=1` were learned during pre-training and are added to the wordpiece\n # embedding vector (and position vector). This is not *strictly* necessary\n # since the [SEP] token unambigiously separates the sequences, but it makes\n # it easier for the model to learn the concept of sequences.\n #\n # For classification tasks, the first vector (corresponding to [CLS]) is\n # used as as the \"sentence vector\". Note that this only makes sense because\n # the entire model is fine-tuned.\n tokens = []\n input_type_ids = []\n tokens.append(\"[CLS]\")\n input_type_ids.append(0)\n for token in tokens_a:\n tokens.append(token)\n input_type_ids.append(0)\n tokens.append(\"[SEP]\")\n input_type_ids.append(0)\n\n if tokens_b:\n for token in tokens_b:\n tokens.append(token)\n input_type_ids.append(1)\n tokens.append(\"[SEP]\")\n input_type_ids.append(1)\n\n input_ids = tokenizer.convert_tokens_to_ids(tokens)\n\n # The mask has 1 for real tokens and 0 for padding tokens. Only real\n # tokens are attended to.\n input_mask = [1] * len(input_ids)\n\n # Zero-pad up to the sequence length.\n while len(input_ids) < seq_length:\n input_ids.append(0)\n input_mask.append(0)\n input_type_ids.append(0)\n\n assert len(input_ids) == seq_length\n assert len(input_mask) == seq_length\n assert len(input_type_ids) == seq_length\n\n if ex_index < 5:\n logger.info(\"*** Example ***\")\n logger.info(\"unique_id: %s\" % (example.unique_id))\n logger.info(\"tokens: %s\" % \" \".join([str(x) for x in tokens]))\n logger.info(\"input_ids: %s\" % \" \".join([str(x) for x in input_ids]))\n logger.info(\"input_mask: %s\" % \" \".join([str(x) for x in input_mask]))\n logger.info(\n \"input_type_ids: %s\" % \" \".join([str(x) for x in input_type_ids]))\n\n features.append(\n InputFeatures(\n unique_id=example.unique_id,\n tokens=tokens,\n input_ids=input_ids,\n input_mask=input_mask,\n input_type_ids=input_type_ids))\n return features" }, { "instruction": "Write or improve a Python function based on this description:\n\nRead a list of `InputExample`s from an input file.", "output": "def read_examples(input_file):\n \"\"\"Read a list of `InputExample`s from an input file.\"\"\"\n examples = []\n unique_id = 0\n with open(input_file, \"r\", encoding='utf-8') as reader:\n while True:\n line = reader.readline()\n if not line:\n break\n line = line.strip()\n text_a = None\n text_b = None\n m = re.match(r\"^(.*) \\|\\|\\| (.*)$\", line)\n if m is None:\n text_a = line\n else:\n text_a = m.group(1)\n text_b = m.group(2)\n examples.append(\n InputExample(unique_id=unique_id, text_a=text_a, text_b=text_b))\n unique_id += 1\n return examples" }, { "instruction": "Write or improve a Python function based on this description:\n\nRead a SQuAD json file into a list of SquadExample.", "output": "def read_squad_examples(input_file, is_training, version_2_with_negative):\n \"\"\"Read a SQuAD json file into a list of SquadExample.\"\"\"\n with open(input_file, \"r\", encoding='utf-8') as reader:\n input_data = json.load(reader)[\"data\"]\n\n def is_whitespace(c):\n if c == \" \" or c == \"\\t\" or c == \"\\r\" or c == \"\\n\" or ord(c) == 0x202F:\n return True\n return False\n\n examples = []\n for entry in input_data:\n for paragraph in entry[\"paragraphs\"]:\n paragraph_text = paragraph[\"context\"]\n doc_tokens = []\n char_to_word_offset = []\n prev_is_whitespace = True\n for c in paragraph_text:\n if is_whitespace(c):\n prev_is_whitespace = True\n else:\n if prev_is_whitespace:\n doc_tokens.append(c)\n else:\n doc_tokens[-1] += c\n prev_is_whitespace = False\n char_to_word_offset.append(len(doc_tokens) - 1)\n\n for qa in paragraph[\"qas\"]:\n qas_id = qa[\"id\"]\n question_text = qa[\"question\"]\n start_position = None\n end_position = None\n orig_answer_text = None\n is_impossible = False\n if is_training:\n if version_2_with_negative:\n is_impossible = qa[\"is_impossible\"]\n if (len(qa[\"answers\"]) != 1) and (not is_impossible):\n raise ValueError(\n \"For training, each question should have exactly 1 answer.\")\n if not is_impossible:\n answer = qa[\"answers\"][0]\n orig_answer_text = answer[\"text\"]\n answer_offset = answer[\"answer_start\"]\n answer_length = len(orig_answer_text)\n start_position = char_to_word_offset[answer_offset]\n end_position = char_to_word_offset[answer_offset + answer_length - 1]\n # Only add answers where the text can be exactly recovered from the\n # document. If this CAN'T happen it's likely due to weird Unicode\n # stuff so we will just skip the example.\n #\n # Note that this means for training mode, every example is NOT\n # guaranteed to be preserved.\n actual_text = \" \".join(doc_tokens[start_position:(end_position + 1)])\n cleaned_answer_text = \" \".join(\n whitespace_tokenize(orig_answer_text))\n if actual_text.find(cleaned_answer_text) == -1:\n logger.warning(\"Could not find answer: '%s' vs. '%s'\",\n actual_text, cleaned_answer_text)\n continue\n else:\n start_position = -1\n end_position = -1\n orig_answer_text = \"\"\n\n example = SquadExample(\n qas_id=qas_id,\n question_text=question_text,\n doc_tokens=doc_tokens,\n orig_answer_text=orig_answer_text,\n start_position=start_position,\n end_position=end_position,\n is_impossible=is_impossible)\n examples.append(example)\n return examples" }, { "instruction": "Write or improve a Python function based on this description:\n\nLoads a data file into a list of `InputBatch`s.", "output": "def convert_examples_to_features(examples, tokenizer, max_seq_length,\n doc_stride, max_query_length, is_training):\n \"\"\"Loads a data file into a list of `InputBatch`s.\"\"\"\n\n unique_id = 1000000000\n\n features = []\n for (example_index, example) in enumerate(examples):\n query_tokens = tokenizer.tokenize(example.question_text)\n\n if len(query_tokens) > max_query_length:\n query_tokens = query_tokens[0:max_query_length]\n\n tok_to_orig_index = []\n orig_to_tok_index = []\n all_doc_tokens = []\n for (i, token) in enumerate(example.doc_tokens):\n orig_to_tok_index.append(len(all_doc_tokens))\n sub_tokens = tokenizer.tokenize(token)\n for sub_token in sub_tokens:\n tok_to_orig_index.append(i)\n all_doc_tokens.append(sub_token)\n\n tok_start_position = None\n tok_end_position = None\n if is_training and example.is_impossible:\n tok_start_position = -1\n tok_end_position = -1\n if is_training and not example.is_impossible:\n tok_start_position = orig_to_tok_index[example.start_position]\n if example.end_position < len(example.doc_tokens) - 1:\n tok_end_position = orig_to_tok_index[example.end_position + 1] - 1\n else:\n tok_end_position = len(all_doc_tokens) - 1\n (tok_start_position, tok_end_position) = _improve_answer_span(\n all_doc_tokens, tok_start_position, tok_end_position, tokenizer,\n example.orig_answer_text)\n\n # The -3 accounts for [CLS], [SEP] and [SEP]\n max_tokens_for_doc = max_seq_length - len(query_tokens) - 3\n\n # We can have documents that are longer than the maximum sequence length.\n # To deal with this we do a sliding window approach, where we take chunks\n # of the up to our max length with a stride of `doc_stride`.\n _DocSpan = collections.namedtuple( # pylint: disable=invalid-name\n \"DocSpan\", [\"start\", \"length\"])\n doc_spans = []\n start_offset = 0\n while start_offset < len(all_doc_tokens):\n length = len(all_doc_tokens) - start_offset\n if length > max_tokens_for_doc:\n length = max_tokens_for_doc\n doc_spans.append(_DocSpan(start=start_offset, length=length))\n if start_offset + length == len(all_doc_tokens):\n break\n start_offset += min(length, doc_stride)\n\n for (doc_span_index, doc_span) in enumerate(doc_spans):\n tokens = []\n token_to_orig_map = {}\n token_is_max_context = {}\n segment_ids = []\n tokens.append(\"[CLS]\")\n segment_ids.append(0)\n for token in query_tokens:\n tokens.append(token)\n segment_ids.append(0)\n tokens.append(\"[SEP]\")\n segment_ids.append(0)\n\n for i in range(doc_span.length):\n split_token_index = doc_span.start + i\n token_to_orig_map[len(tokens)] = tok_to_orig_index[split_token_index]\n\n is_max_context = _check_is_max_context(doc_spans, doc_span_index,\n split_token_index)\n token_is_max_context[len(tokens)] = is_max_context\n tokens.append(all_doc_tokens[split_token_index])\n segment_ids.append(1)\n tokens.append(\"[SEP]\")\n segment_ids.append(1)\n\n input_ids = tokenizer.convert_tokens_to_ids(tokens)\n\n # The mask has 1 for real tokens and 0 for padding tokens. Only real\n # tokens are attended to.\n input_mask = [1] * len(input_ids)\n\n # Zero-pad up to the sequence length.\n while len(input_ids) < max_seq_length:\n input_ids.append(0)\n input_mask.append(0)\n segment_ids.append(0)\n\n assert len(input_ids) == max_seq_length\n assert len(input_mask) == max_seq_length\n assert len(segment_ids) == max_seq_length\n\n start_position = None\n end_position = None\n if is_training and not example.is_impossible:\n # For training, if our document chunk does not contain an annotation\n # we throw it out, since there is nothing to predict.\n doc_start = doc_span.start\n doc_end = doc_span.start + doc_span.length - 1\n out_of_span = False\n if not (tok_start_position >= doc_start and\n tok_end_position <= doc_end):\n out_of_span = True\n if out_of_span:\n start_position = 0\n end_position = 0\n else:\n doc_offset = len(query_tokens) + 2\n start_position = tok_start_position - doc_start + doc_offset\n end_position = tok_end_position - doc_start + doc_offset\n if is_training and example.is_impossible:\n start_position = 0\n end_position = 0\n if example_index < 20:\n logger.info(\"*** Example ***\")\n logger.info(\"unique_id: %s\" % (unique_id))\n logger.info(\"example_index: %s\" % (example_index))\n logger.info(\"doc_span_index: %s\" % (doc_span_index))\n logger.info(\"tokens: %s\" % \" \".join(tokens))\n logger.info(\"token_to_orig_map: %s\" % \" \".join([\n \"%d:%d\" % (x, y) for (x, y) in token_to_orig_map.items()]))\n logger.info(\"token_is_max_context: %s\" % \" \".join([\n \"%d:%s\" % (x, y) for (x, y) in token_is_max_context.items()\n ]))\n logger.info(\"input_ids: %s\" % \" \".join([str(x) for x in input_ids]))\n logger.info(\n \"input_mask: %s\" % \" \".join([str(x) for x in input_mask]))\n logger.info(\n \"segment_ids: %s\" % \" \".join([str(x) for x in segment_ids]))\n if is_training and example.is_impossible:\n logger.info(\"impossible example\")\n if is_training and not example.is_impossible:\n answer_text = \" \".join(tokens[start_position:(end_position + 1)])\n logger.info(\"start_position: %d\" % (start_position))\n logger.info(\"end_position: %d\" % (end_position))\n logger.info(\n \"answer: %s\" % (answer_text))\n\n features.append(\n InputFeatures(\n unique_id=unique_id,\n example_index=example_index,\n doc_span_index=doc_span_index,\n tokens=tokens,\n token_to_orig_map=token_to_orig_map,\n token_is_max_context=token_is_max_context,\n input_ids=input_ids,\n input_mask=input_mask,\n segment_ids=segment_ids,\n start_position=start_position,\n end_position=end_position,\n is_impossible=example.is_impossible))\n unique_id += 1\n\n return features" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns tokenized answer spans that better match the annotated answer.", "output": "def _improve_answer_span(doc_tokens, input_start, input_end, tokenizer,\n orig_answer_text):\n \"\"\"Returns tokenized answer spans that better match the annotated answer.\"\"\"\n\n # The SQuAD annotations are character based. We first project them to\n # whitespace-tokenized words. But then after WordPiece tokenization, we can\n # often find a \"better match\". For example:\n #\n # Question: What year was John Smith born?\n # Context: The leader was John Smith (1895-1943).\n # Answer: 1895\n #\n # The original whitespace-tokenized answer will be \"(1895-1943).\". However\n # after tokenization, our tokens will be \"( 1895 - 1943 ) .\". So we can match\n # the exact answer, 1895.\n #\n # However, this is not always possible. Consider the following:\n #\n # Question: What country is the top exporter of electornics?\n # Context: The Japanese electronics industry is the lagest in the world.\n # Answer: Japan\n #\n # In this case, the annotator chose \"Japan\" as a character sub-span of\n # the word \"Japanese\". Since our WordPiece tokenizer does not split\n # \"Japanese\", we just use \"Japanese\" as the annotation. This is fairly rare\n # in SQuAD, but does happen.\n tok_answer_text = \" \".join(tokenizer.tokenize(orig_answer_text))\n\n for new_start in range(input_start, input_end + 1):\n for new_end in range(input_end, new_start - 1, -1):\n text_span = \" \".join(doc_tokens[new_start:(new_end + 1)])\n if text_span == tok_answer_text:\n return (new_start, new_end)\n\n return (input_start, input_end)" }, { "instruction": "Write or improve a Python function based on this description:\n\nCheck if this is the 'max context' doc span for the token.", "output": "def _check_is_max_context(doc_spans, cur_span_index, position):\n \"\"\"Check if this is the 'max context' doc span for the token.\"\"\"\n\n # Because of the sliding window approach taken to scoring documents, a single\n # token can appear in multiple documents. E.g.\n # Doc: the man went to the store and bought a gallon of milk\n # Span A: the man went to the\n # Span B: to the store and bought\n # Span C: and bought a gallon of\n # ...\n #\n # Now the word 'bought' will have two scores from spans B and C. We only\n # want to consider the score with \"maximum context\", which we define as\n # the *minimum* of its left and right context (the *sum* of left and\n # right context will always be the same, of course).\n #\n # In the example the maximum context for 'bought' would be span C since\n # it has 1 left context and 3 right context, while span B has 4 left context\n # and 0 right context.\n best_score = None\n best_span_index = None\n for (span_index, doc_span) in enumerate(doc_spans):\n end = doc_span.start + doc_span.length - 1\n if position < doc_span.start:\n continue\n if position > end:\n continue\n num_left_context = position - doc_span.start\n num_right_context = end - position\n score = min(num_left_context, num_right_context) + 0.01 * doc_span.length\n if best_score is None or score > best_score:\n best_score = score\n best_span_index = span_index\n\n return cur_span_index == best_span_index" }, { "instruction": "Write or improve a Python function based on this description:\n\nWrite final predictions to the json file and log-odds of null if needed.", "output": "def write_predictions(all_examples, all_features, all_results, n_best_size,\n max_answer_length, do_lower_case, output_prediction_file,\n output_nbest_file, output_null_log_odds_file, verbose_logging,\n version_2_with_negative, null_score_diff_threshold):\n \"\"\"Write final predictions to the json file and log-odds of null if needed.\"\"\"\n logger.info(\"Writing predictions to: %s\" % (output_prediction_file))\n logger.info(\"Writing nbest to: %s\" % (output_nbest_file))\n\n example_index_to_features = collections.defaultdict(list)\n for feature in all_features:\n example_index_to_features[feature.example_index].append(feature)\n\n unique_id_to_result = {}\n for result in all_results:\n unique_id_to_result[result.unique_id] = result\n\n _PrelimPrediction = collections.namedtuple( # pylint: disable=invalid-name\n \"PrelimPrediction\",\n [\"feature_index\", \"start_index\", \"end_index\", \"start_logit\", \"end_logit\"])\n\n all_predictions = collections.OrderedDict()\n all_nbest_json = collections.OrderedDict()\n scores_diff_json = collections.OrderedDict()\n\n for (example_index, example) in enumerate(all_examples):\n features = example_index_to_features[example_index]\n\n prelim_predictions = []\n # keep track of the minimum score of null start+end of position 0\n score_null = 1000000 # large and positive\n min_null_feature_index = 0 # the paragraph slice with min null score\n null_start_logit = 0 # the start logit at the slice with min null score\n null_end_logit = 0 # the end logit at the slice with min null score\n for (feature_index, feature) in enumerate(features):\n result = unique_id_to_result[feature.unique_id]\n start_indexes = _get_best_indexes(result.start_logits, n_best_size)\n end_indexes = _get_best_indexes(result.end_logits, n_best_size)\n # if we could have irrelevant answers, get the min score of irrelevant\n if version_2_with_negative:\n feature_null_score = result.start_logits[0] + result.end_logits[0]\n if feature_null_score < score_null:\n score_null = feature_null_score\n min_null_feature_index = feature_index\n null_start_logit = result.start_logits[0]\n null_end_logit = result.end_logits[0]\n for start_index in start_indexes:\n for end_index in end_indexes:\n # We could hypothetically create invalid predictions, e.g., predict\n # that the start of the span is in the question. We throw out all\n # invalid predictions.\n if start_index >= len(feature.tokens):\n continue\n if end_index >= len(feature.tokens):\n continue\n if start_index not in feature.token_to_orig_map:\n continue\n if end_index not in feature.token_to_orig_map:\n continue\n if not feature.token_is_max_context.get(start_index, False):\n continue\n if end_index < start_index:\n continue\n length = end_index - start_index + 1\n if length > max_answer_length:\n continue\n prelim_predictions.append(\n _PrelimPrediction(\n feature_index=feature_index,\n start_index=start_index,\n end_index=end_index,\n start_logit=result.start_logits[start_index],\n end_logit=result.end_logits[end_index]))\n if version_2_with_negative:\n prelim_predictions.append(\n _PrelimPrediction(\n feature_index=min_null_feature_index,\n start_index=0,\n end_index=0,\n start_logit=null_start_logit,\n end_logit=null_end_logit))\n prelim_predictions = sorted(\n prelim_predictions,\n key=lambda x: (x.start_logit + x.end_logit),\n reverse=True)\n\n _NbestPrediction = collections.namedtuple( # pylint: disable=invalid-name\n \"NbestPrediction\", [\"text\", \"start_logit\", \"end_logit\"])\n\n seen_predictions = {}\n nbest = []\n for pred in prelim_predictions:\n if len(nbest) >= n_best_size:\n break\n feature = features[pred.feature_index]\n if pred.start_index > 0: # this is a non-null prediction\n tok_tokens = feature.tokens[pred.start_index:(pred.end_index + 1)]\n orig_doc_start = feature.token_to_orig_map[pred.start_index]\n orig_doc_end = feature.token_to_orig_map[pred.end_index]\n orig_tokens = example.doc_tokens[orig_doc_start:(orig_doc_end + 1)]\n tok_text = \" \".join(tok_tokens)\n\n # De-tokenize WordPieces that have been split off.\n tok_text = tok_text.replace(\" ##\", \"\")\n tok_text = tok_text.replace(\"##\", \"\")\n\n # Clean whitespace\n tok_text = tok_text.strip()\n tok_text = \" \".join(tok_text.split())\n orig_text = \" \".join(orig_tokens)\n\n final_text = get_final_text(tok_text, orig_text, do_lower_case, verbose_logging)\n if final_text in seen_predictions:\n continue\n\n seen_predictions[final_text] = True\n else:\n final_text = \"\"\n seen_predictions[final_text] = True\n\n nbest.append(\n _NbestPrediction(\n text=final_text,\n start_logit=pred.start_logit,\n end_logit=pred.end_logit))\n # if we didn't include the empty option in the n-best, include it\n if version_2_with_negative:\n if \"\" not in seen_predictions:\n nbest.append(\n _NbestPrediction(\n text=\"\",\n start_logit=null_start_logit,\n end_logit=null_end_logit))\n \n # In very rare edge cases we could only have single null prediction.\n # So we just create a nonce prediction in this case to avoid failure.\n if len(nbest)==1:\n nbest.insert(0,\n _NbestPrediction(text=\"empty\", start_logit=0.0, end_logit=0.0))\n \n # In very rare edge cases we could have no valid predictions. So we\n # just create a nonce prediction in this case to avoid failure.\n if not nbest:\n nbest.append(\n _NbestPrediction(text=\"empty\", start_logit=0.0, end_logit=0.0))\n\n assert len(nbest) >= 1\n\n total_scores = []\n best_non_null_entry = None\n for entry in nbest:\n total_scores.append(entry.start_logit + entry.end_logit)\n if not best_non_null_entry:\n if entry.text:\n best_non_null_entry = entry\n\n probs = _compute_softmax(total_scores)\n\n nbest_json = []\n for (i, entry) in enumerate(nbest):\n output = collections.OrderedDict()\n output[\"text\"] = entry.text\n output[\"probability\"] = probs[i]\n output[\"start_logit\"] = entry.start_logit\n output[\"end_logit\"] = entry.end_logit\n nbest_json.append(output)\n\n assert len(nbest_json) >= 1\n\n if not version_2_with_negative:\n all_predictions[example.qas_id] = nbest_json[0][\"text\"]\n else:\n # predict \"\" iff the null score - the score of best non-null > threshold\n score_diff = score_null - best_non_null_entry.start_logit - (\n best_non_null_entry.end_logit)\n scores_diff_json[example.qas_id] = score_diff\n if score_diff > null_score_diff_threshold:\n all_predictions[example.qas_id] = \"\"\n else:\n all_predictions[example.qas_id] = best_non_null_entry.text\n all_nbest_json[example.qas_id] = nbest_json\n\n with open(output_prediction_file, \"w\") as writer:\n writer.write(json.dumps(all_predictions, indent=4) + \"\\n\")\n\n with open(output_nbest_file, \"w\") as writer:\n writer.write(json.dumps(all_nbest_json, indent=4) + \"\\n\")\n\n if version_2_with_negative:\n with open(output_null_log_odds_file, \"w\") as writer:\n writer.write(json.dumps(scores_diff_json, indent=4) + \"\\n\")" }, { "instruction": "Write or improve a Python function based on this description:\n\nProject the tokenized prediction back to the original text.", "output": "def get_final_text(pred_text, orig_text, do_lower_case, verbose_logging=False):\n \"\"\"Project the tokenized prediction back to the original text.\"\"\"\n\n # When we created the data, we kept track of the alignment between original\n # (whitespace tokenized) tokens and our WordPiece tokenized tokens. So\n # now `orig_text` contains the span of our original text corresponding to the\n # span that we predicted.\n #\n # However, `orig_text` may contain extra characters that we don't want in\n # our prediction.\n #\n # For example, let's say:\n # pred_text = steve smith\n # orig_text = Steve Smith's\n #\n # We don't want to return `orig_text` because it contains the extra \"'s\".\n #\n # We don't want to return `pred_text` because it's already been normalized\n # (the SQuAD eval script also does punctuation stripping/lower casing but\n # our tokenizer does additional normalization like stripping accent\n # characters).\n #\n # What we really want to return is \"Steve Smith\".\n #\n # Therefore, we have to apply a semi-complicated alignment heuristic between\n # `pred_text` and `orig_text` to get a character-to-character alignment. This\n # can fail in certain cases in which case we just return `orig_text`.\n\n def _strip_spaces(text):\n ns_chars = []\n ns_to_s_map = collections.OrderedDict()\n for (i, c) in enumerate(text):\n if c == \" \":\n continue\n ns_to_s_map[len(ns_chars)] = i\n ns_chars.append(c)\n ns_text = \"\".join(ns_chars)\n return (ns_text, ns_to_s_map)\n\n # We first tokenize `orig_text`, strip whitespace from the result\n # and `pred_text`, and check if they are the same length. If they are\n # NOT the same length, the heuristic has failed. If they are the same\n # length, we assume the characters are one-to-one aligned.\n tokenizer = BasicTokenizer(do_lower_case=do_lower_case)\n\n tok_text = \" \".join(tokenizer.tokenize(orig_text))\n\n start_position = tok_text.find(pred_text)\n if start_position == -1:\n if verbose_logging:\n logger.info(\n \"Unable to find text: '%s' in '%s'\" % (pred_text, orig_text))\n return orig_text\n end_position = start_position + len(pred_text) - 1\n\n (orig_ns_text, orig_ns_to_s_map) = _strip_spaces(orig_text)\n (tok_ns_text, tok_ns_to_s_map) = _strip_spaces(tok_text)\n\n if len(orig_ns_text) != len(tok_ns_text):\n if verbose_logging:\n logger.info(\"Length not equal after stripping spaces: '%s' vs '%s'\",\n orig_ns_text, tok_ns_text)\n return orig_text\n\n # We then project the characters in `pred_text` back to `orig_text` using\n # the character-to-character alignment.\n tok_s_to_ns_map = {}\n for (i, tok_index) in tok_ns_to_s_map.items():\n tok_s_to_ns_map[tok_index] = i\n\n orig_start_position = None\n if start_position in tok_s_to_ns_map:\n ns_start_position = tok_s_to_ns_map[start_position]\n if ns_start_position in orig_ns_to_s_map:\n orig_start_position = orig_ns_to_s_map[ns_start_position]\n\n if orig_start_position is None:\n if verbose_logging:\n logger.info(\"Couldn't map start position\")\n return orig_text\n\n orig_end_position = None\n if end_position in tok_s_to_ns_map:\n ns_end_position = tok_s_to_ns_map[end_position]\n if ns_end_position in orig_ns_to_s_map:\n orig_end_position = orig_ns_to_s_map[ns_end_position]\n\n if orig_end_position is None:\n if verbose_logging:\n logger.info(\"Couldn't map end position\")\n return orig_text\n\n output_text = orig_text[orig_start_position:(orig_end_position + 1)]\n return output_text" }, { "instruction": "Write or improve a Python function based on this description:\n\nGet the n-best logits from a list.", "output": "def _get_best_indexes(logits, n_best_size):\n \"\"\"Get the n-best logits from a list.\"\"\"\n index_and_score = sorted(enumerate(logits), key=lambda x: x[1], reverse=True)\n\n best_indexes = []\n for i in range(len(index_and_score)):\n if i >= n_best_size:\n break\n best_indexes.append(index_and_score[i][0])\n return best_indexes" }, { "instruction": "Write or improve a Python function based on this description:\n\nCompute softmax probability over raw logits.", "output": "def _compute_softmax(scores):\n \"\"\"Compute softmax probability over raw logits.\"\"\"\n if not scores:\n return []\n\n max_score = None\n for score in scores:\n if max_score is None or score > max_score:\n max_score = score\n\n exp_scores = []\n total_sum = 0.0\n for score in scores:\n x = math.exp(score - max_score)\n exp_scores.append(x)\n total_sum += x\n\n probs = []\n for score in exp_scores:\n probs.append(score / total_sum)\n return probs" }, { "instruction": "Write or improve a Python function based on this description:\n\nLoads a data file into a list of `InputBatch`s.", "output": "def convert_examples_to_features(examples, tokenizer, max_seq_length,\n is_training):\n \"\"\"Loads a data file into a list of `InputBatch`s.\"\"\"\n\n # Swag is a multiple choice task. To perform this task using Bert,\n # we will use the formatting proposed in \"Improving Language\n # Understanding by Generative Pre-Training\" and suggested by\n # @jacobdevlin-google in this issue\n # https://github.com/google-research/bert/issues/38.\n #\n # Each choice will correspond to a sample on which we run the\n # inference. For a given Swag example, we will create the 4\n # following inputs:\n # - [CLS] context [SEP] choice_1 [SEP]\n # - [CLS] context [SEP] choice_2 [SEP]\n # - [CLS] context [SEP] choice_3 [SEP]\n # - [CLS] context [SEP] choice_4 [SEP]\n # The model will output a single value for each input. To get the\n # final decision of the model, we will run a softmax over these 4\n # outputs.\n features = []\n for example_index, example in enumerate(examples):\n context_tokens = tokenizer.tokenize(example.context_sentence)\n start_ending_tokens = tokenizer.tokenize(example.start_ending)\n\n choices_features = []\n for ending_index, ending in enumerate(example.endings):\n # We create a copy of the context tokens in order to be\n # able to shrink it according to ending_tokens\n context_tokens_choice = context_tokens[:]\n ending_tokens = start_ending_tokens + tokenizer.tokenize(ending)\n # Modifies `context_tokens_choice` and `ending_tokens` in\n # place so that the total length is less than the\n # specified length. Account for [CLS], [SEP], [SEP] with\n # \"- 3\"\n _truncate_seq_pair(context_tokens_choice, ending_tokens, max_seq_length - 3)\n\n tokens = [\"[CLS]\"] + context_tokens_choice + [\"[SEP]\"] + ending_tokens + [\"[SEP]\"]\n segment_ids = [0] * (len(context_tokens_choice) + 2) + [1] * (len(ending_tokens) + 1)\n\n input_ids = tokenizer.convert_tokens_to_ids(tokens)\n input_mask = [1] * len(input_ids)\n\n # Zero-pad up to the sequence length.\n padding = [0] * (max_seq_length - len(input_ids))\n input_ids += padding\n input_mask += padding\n segment_ids += padding\n\n assert len(input_ids) == max_seq_length\n assert len(input_mask) == max_seq_length\n assert len(segment_ids) == max_seq_length\n\n choices_features.append((tokens, input_ids, input_mask, segment_ids))\n\n label = example.label\n if example_index < 5:\n logger.info(\"*** Example ***\")\n logger.info(\"swag_id: {}\".format(example.swag_id))\n for choice_idx, (tokens, input_ids, input_mask, segment_ids) in enumerate(choices_features):\n logger.info(\"choice: {}\".format(choice_idx))\n logger.info(\"tokens: {}\".format(' '.join(tokens)))\n logger.info(\"input_ids: {}\".format(' '.join(map(str, input_ids))))\n logger.info(\"input_mask: {}\".format(' '.join(map(str, input_mask))))\n logger.info(\"segment_ids: {}\".format(' '.join(map(str, segment_ids))))\n if is_training:\n logger.info(\"label: {}\".format(label))\n\n features.append(\n InputFeatures(\n example_id = example.swag_id,\n choices_features = choices_features,\n label = label\n )\n )\n\n return features" }, { "instruction": "Write or improve a Python function based on this description:\n\nLoads a data file into a list of `InputBatch`s.", "output": "def convert_examples_to_features(examples, label_list, max_seq_length,\n tokenizer, output_mode):\n \"\"\"Loads a data file into a list of `InputBatch`s.\"\"\"\n\n label_map = {label : i for i, label in enumerate(label_list)}\n\n features = []\n for (ex_index, example) in enumerate(examples):\n if ex_index % 10000 == 0:\n logger.info(\"Writing example %d of %d\" % (ex_index, len(examples)))\n\n tokens_a = tokenizer.tokenize(example.text_a)\n\n tokens_b = None\n if example.text_b:\n tokens_b = tokenizer.tokenize(example.text_b)\n # Modifies `tokens_a` and `tokens_b` in place so that the total\n # length is less than the specified length.\n # Account for [CLS], [SEP], [SEP] with \"- 3\"\n _truncate_seq_pair(tokens_a, tokens_b, max_seq_length - 3)\n else:\n # Account for [CLS] and [SEP] with \"- 2\"\n if len(tokens_a) > max_seq_length - 2:\n tokens_a = tokens_a[:(max_seq_length - 2)]\n\n # The convention in BERT is:\n # (a) For sequence pairs:\n # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]\n # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1\n # (b) For single sequences:\n # tokens: [CLS] the dog is hairy . [SEP]\n # type_ids: 0 0 0 0 0 0 0\n #\n # Where \"type_ids\" are used to indicate whether this is the first\n # sequence or the second sequence. The embedding vectors for `type=0` and\n # `type=1` were learned during pre-training and are added to the wordpiece\n # embedding vector (and position vector). This is not *strictly* necessary\n # since the [SEP] token unambiguously separates the sequences, but it makes\n # it easier for the model to learn the concept of sequences.\n #\n # For classification tasks, the first vector (corresponding to [CLS]) is\n # used as as the \"sentence vector\". Note that this only makes sense because\n # the entire model is fine-tuned.\n tokens = [\"[CLS]\"] + tokens_a + [\"[SEP]\"]\n segment_ids = [0] * len(tokens)\n\n if tokens_b:\n tokens += tokens_b + [\"[SEP]\"]\n segment_ids += [1] * (len(tokens_b) + 1)\n\n input_ids = tokenizer.convert_tokens_to_ids(tokens)\n\n # The mask has 1 for real tokens and 0 for padding tokens. Only real\n # tokens are attended to.\n input_mask = [1] * len(input_ids)\n\n # Zero-pad up to the sequence length.\n padding = [0] * (max_seq_length - len(input_ids))\n input_ids += padding\n input_mask += padding\n segment_ids += padding\n\n assert len(input_ids) == max_seq_length\n assert len(input_mask) == max_seq_length\n assert len(segment_ids) == max_seq_length\n\n if output_mode == \"classification\":\n label_id = label_map[example.label]\n elif output_mode == \"regression\":\n label_id = float(example.label)\n else:\n raise KeyError(output_mode)\n\n if ex_index < 5:\n logger.info(\"*** Example ***\")\n logger.info(\"guid: %s\" % (example.guid))\n logger.info(\"tokens: %s\" % \" \".join(\n [str(x) for x in tokens]))\n logger.info(\"input_ids: %s\" % \" \".join([str(x) for x in input_ids]))\n logger.info(\"input_mask: %s\" % \" \".join([str(x) for x in input_mask]))\n logger.info(\n \"segment_ids: %s\" % \" \".join([str(x) for x in segment_ids]))\n logger.info(\"label: %s (id = %d)\" % (example.label, label_id))\n\n features.append(\n InputFeatures(input_ids=input_ids,\n input_mask=input_mask,\n segment_ids=segment_ids,\n label_id=label_id))\n return features" }, { "instruction": "Write or improve a Python function based on this description:\n\nReads a tab separated value file.", "output": "def _read_tsv(cls, input_file, quotechar=None):\n \"\"\"Reads a tab separated value file.\"\"\"\n with open(input_file, \"r\", encoding=\"utf-8\") as f:\n reader = csv.reader(f, delimiter=\"\\t\", quotechar=quotechar)\n lines = []\n for line in reader:\n if sys.version_info[0] == 2:\n line = list(unicode(cell, 'utf-8') for cell in line)\n lines.append(line)\n return lines" }, { "instruction": "Write or improve a Python function based on this description:\n\nSee base class.", "output": "def get_train_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n logger.info(\"LOOKING AT {}\".format(os.path.join(data_dir, \"train.tsv\")))\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"train.tsv\")), \"train\")" }, { "instruction": "Write or improve a Python function based on this description:\n\nCreates examples for the training and dev sets.", "output": "def _create_examples(self, lines, set_type):\n \"\"\"Creates examples for the training and dev sets.\"\"\"\n examples = []\n for (i, line) in enumerate(lines):\n if i == 0:\n continue\n guid = \"%s-%s\" % (set_type, i)\n text_a = line[3]\n text_b = line[4]\n label = line[0]\n examples.append(\n InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))\n return examples" }, { "instruction": "Write or improve a Python function based on this description:\n\nSee base class.", "output": "def get_train_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"train.tsv\")), \"train\")" }, { "instruction": "Write or improve a Python function based on this description:\n\nSee base class.", "output": "def get_dev_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"dev_matched.tsv\")),\n \"dev_matched\")" }, { "instruction": "Write or improve a Python function based on this description:\n\nMasks everything but the k top entries as -infinity (1e10).\n Used to mask logits such that e^-infinity -> 0 won't contribute to the\n sum of the denominator.", "output": "def top_k_logits(logits, k):\n \"\"\"\n Masks everything but the k top entries as -infinity (1e10).\n Used to mask logits such that e^-infinity -> 0 won't contribute to the\n sum of the denominator.\n \"\"\"\n if k == 0:\n return logits\n else:\n values = torch.topk(logits, k)[0]\n batch_mins = values[:, -1].view(-1, 1).expand_as(logits)\n return torch.where(logits < batch_mins, torch.ones_like(logits) * -1e10, logits)" }, { "instruction": "Write or improve a Python function based on this description:\n\nLoad tf checkpoints in a pytorch model", "output": "def load_tf_weights_in_bert(model, tf_checkpoint_path):\n \"\"\" Load tf checkpoints in a pytorch model\n \"\"\"\n try:\n import re\n import numpy as np\n import tensorflow as tf\n except ImportError:\n print(\"Loading a TensorFlow models in PyTorch, requires TensorFlow to be installed. Please see \"\n \"https://www.tensorflow.org/install/ for installation instructions.\")\n raise\n tf_path = os.path.abspath(tf_checkpoint_path)\n print(\"Converting TensorFlow checkpoint from {}\".format(tf_path))\n # Load weights from TF model\n init_vars = tf.train.list_variables(tf_path)\n names = []\n arrays = []\n for name, shape in init_vars:\n print(\"Loading TF weight {} with shape {}\".format(name, shape))\n array = tf.train.load_variable(tf_path, name)\n names.append(name)\n arrays.append(array)\n\n for name, array in zip(names, arrays):\n name = name.split('/')\n # adam_v and adam_m are variables used in AdamWeightDecayOptimizer to calculated m and v\n # which are not required for using pretrained model\n if any(n in [\"adam_v\", \"adam_m\", \"global_step\"] for n in name):\n print(\"Skipping {}\".format(\"/\".join(name)))\n continue\n pointer = model\n for m_name in name:\n if re.fullmatch(r'[A-Za-z]+_\\d+', m_name):\n l = re.split(r'_(\\d+)', m_name)\n else:\n l = [m_name]\n if l[0] == 'kernel' or l[0] == 'gamma':\n pointer = getattr(pointer, 'weight')\n elif l[0] == 'output_bias' or l[0] == 'beta':\n pointer = getattr(pointer, 'bias')\n elif l[0] == 'output_weights':\n pointer = getattr(pointer, 'weight')\n elif l[0] == 'squad':\n pointer = getattr(pointer, 'classifier')\n else:\n try:\n pointer = getattr(pointer, l[0])\n except AttributeError:\n print(\"Skipping {}\".format(\"/\".join(name)))\n continue\n if len(l) >= 2:\n num = int(l[1])\n pointer = pointer[num]\n if m_name[-11:] == '_embeddings':\n pointer = getattr(pointer, 'weight')\n elif m_name == 'kernel':\n array = np.transpose(array)\n try:\n assert pointer.shape == array.shape\n except AssertionError as e:\n e.args += (pointer.shape, array.shape)\n raise\n print(\"Initialize PyTorch weight {}\".format(name))\n pointer.data = torch.from_numpy(array)\n return model" }, { "instruction": "Write or improve a Python function based on this description:\n\nInstantiate a BertPreTrainedModel from a pre-trained model file or a pytorch state dict.\n Download and cache the pre-trained model file if needed.\n\n Params:\n pretrained_model_name_or_path: either:\n - a str with the name of a pre-trained model to load selected in the list of:\n . `bert-base-uncased`\n . `bert-large-uncased`\n . `bert-base-cased`\n . `bert-large-cased`\n . `bert-base-multilingual-uncased`\n . `bert-base-multilingual-cased`\n . `bert-base-chinese`\n - a path or url to a pretrained model archive containing:\n . `bert_config.json` a configuration file for the model\n . `pytorch_model.bin` a PyTorch dump of a BertForPreTraining instance\n - a path or url to a pretrained model archive containing:\n . `bert_config.json` a configuration file for the model\n . `model.chkpt` a TensorFlow checkpoint\n from_tf: should we load the weights from a locally saved TensorFlow checkpoint\n cache_dir: an optional path to a folder in which the pre-trained models will be cached.\n state_dict: an optional state dictionnary (collections.OrderedDict object) to use instead of Google pre-trained models\n *inputs, **kwargs: additional input for the specific Bert class\n (ex: num_labels for BertForSequenceClassification)", "output": "def from_pretrained(cls, pretrained_model_name_or_path, *inputs, **kwargs):\n \"\"\"\n Instantiate a BertPreTrainedModel from a pre-trained model file or a pytorch state dict.\n Download and cache the pre-trained model file if needed.\n\n Params:\n pretrained_model_name_or_path: either:\n - a str with the name of a pre-trained model to load selected in the list of:\n . `bert-base-uncased`\n . `bert-large-uncased`\n . `bert-base-cased`\n . `bert-large-cased`\n . `bert-base-multilingual-uncased`\n . `bert-base-multilingual-cased`\n . `bert-base-chinese`\n - a path or url to a pretrained model archive containing:\n . `bert_config.json` a configuration file for the model\n . `pytorch_model.bin` a PyTorch dump of a BertForPreTraining instance\n - a path or url to a pretrained model archive containing:\n . `bert_config.json` a configuration file for the model\n . `model.chkpt` a TensorFlow checkpoint\n from_tf: should we load the weights from a locally saved TensorFlow checkpoint\n cache_dir: an optional path to a folder in which the pre-trained models will be cached.\n state_dict: an optional state dictionnary (collections.OrderedDict object) to use instead of Google pre-trained models\n *inputs, **kwargs: additional input for the specific Bert class\n (ex: num_labels for BertForSequenceClassification)\n \"\"\"\n state_dict = kwargs.get('state_dict', None)\n kwargs.pop('state_dict', None)\n cache_dir = kwargs.get('cache_dir', None)\n kwargs.pop('cache_dir', None)\n from_tf = kwargs.get('from_tf', False)\n kwargs.pop('from_tf', None)\n\n if pretrained_model_name_or_path in PRETRAINED_MODEL_ARCHIVE_MAP:\n archive_file = PRETRAINED_MODEL_ARCHIVE_MAP[pretrained_model_name_or_path]\n else:\n archive_file = pretrained_model_name_or_path\n # redirect to the cache, if necessary\n try:\n resolved_archive_file = cached_path(archive_file, cache_dir=cache_dir)\n except EnvironmentError:\n logger.error(\n \"Model name '{}' was not found in model name list ({}). \"\n \"We assumed '{}' was a path or url but couldn't find any file \"\n \"associated to this path or url.\".format(\n pretrained_model_name_or_path,\n ', '.join(PRETRAINED_MODEL_ARCHIVE_MAP.keys()),\n archive_file))\n return None\n if resolved_archive_file == archive_file:\n logger.info(\"loading archive file {}\".format(archive_file))\n else:\n logger.info(\"loading archive file {} from cache at {}\".format(\n archive_file, resolved_archive_file))\n tempdir = None\n if os.path.isdir(resolved_archive_file) or from_tf:\n serialization_dir = resolved_archive_file\n else:\n # Extract archive to temp dir\n tempdir = tempfile.mkdtemp()\n logger.info(\"extracting archive file {} to temp dir {}\".format(\n resolved_archive_file, tempdir))\n with tarfile.open(resolved_archive_file, 'r:gz') as archive:\n archive.extractall(tempdir)\n serialization_dir = tempdir\n # Load config\n config_file = os.path.join(serialization_dir, CONFIG_NAME)\n if not os.path.exists(config_file):\n # Backward compatibility with old naming format\n config_file = os.path.join(serialization_dir, BERT_CONFIG_NAME)\n config = BertConfig.from_json_file(config_file)\n logger.info(\"Model config {}\".format(config))\n # Instantiate model.\n model = cls(config, *inputs, **kwargs)\n if state_dict is None and not from_tf:\n weights_path = os.path.join(serialization_dir, WEIGHTS_NAME)\n state_dict = torch.load(weights_path, map_location='cpu')\n if tempdir:\n # Clean up temp dir\n shutil.rmtree(tempdir)\n if from_tf:\n # Directly load from a TensorFlow checkpoint\n weights_path = os.path.join(serialization_dir, TF_WEIGHTS_NAME)\n return load_tf_weights_in_bert(model, weights_path)\n # Load from a PyTorch state_dict\n old_keys = []\n new_keys = []\n for key in state_dict.keys():\n new_key = None\n if 'gamma' in key:\n new_key = key.replace('gamma', 'weight')\n if 'beta' in key:\n new_key = key.replace('beta', 'bias')\n if new_key:\n old_keys.append(key)\n new_keys.append(new_key)\n for old_key, new_key in zip(old_keys, new_keys):\n state_dict[new_key] = state_dict.pop(old_key)\n\n missing_keys = []\n unexpected_keys = []\n error_msgs = []\n # copy state_dict so _load_from_state_dict can modify it\n metadata = getattr(state_dict, '_metadata', None)\n state_dict = state_dict.copy()\n if metadata is not None:\n state_dict._metadata = metadata\n\n def load(module, prefix=''):\n local_metadata = {} if metadata is None else metadata.get(prefix[:-1], {})\n module._load_from_state_dict(\n state_dict, prefix, local_metadata, True, missing_keys, unexpected_keys, error_msgs)\n for name, child in module._modules.items():\n if child is not None:\n load(child, prefix + name + '.')\n start_prefix = ''\n if not hasattr(model, 'bert') and any(s.startswith('bert.') for s in state_dict.keys()):\n start_prefix = 'bert.'\n load(model, prefix=start_prefix)\n if len(missing_keys) > 0:\n logger.info(\"Weights of {} not initialized from pretrained model: {}\".format(\n model.__class__.__name__, missing_keys))\n if len(unexpected_keys) > 0:\n logger.info(\"Weights from pretrained model not used in {}: {}\".format(\n model.__class__.__name__, unexpected_keys))\n if len(error_msgs) > 0:\n raise RuntimeError('Error(s) in loading state_dict for {}:\\n\\t{}'.format(\n model.__class__.__name__, \"\\n\\t\".join(error_msgs)))\n return model" }, { "instruction": "Write or improve a Python function based on this description:\n\nLoad tf pre-trained weights in a pytorch model (from NumPy arrays here)", "output": "def load_tf_weights_in_openai_gpt(model, openai_checkpoint_folder_path):\n \"\"\" Load tf pre-trained weights in a pytorch model (from NumPy arrays here)\n \"\"\"\n import re\n import numpy as np\n print(\"Loading weights...\")\n names = json.load(open(openai_checkpoint_folder_path + '/parameters_names.json', \"r\", encoding='utf-8'))\n shapes = json.load(open(openai_checkpoint_folder_path + '/params_shapes.json', \"r\", encoding='utf-8'))\n offsets = np.cumsum([np.prod(shape) for shape in shapes])\n init_params = [np.load(openai_checkpoint_folder_path + '/params_{}.npy'.format(n)) for n in range(10)]\n init_params = np.split(np.concatenate(init_params, 0), offsets)[:-1]\n init_params = [param.reshape(shape) for param, shape in zip(init_params, shapes)]\n\n # This was used when we had a single embedding matrix for positions and tokens\n # init_params[0] = np.concatenate([init_params[1], init_params[0]], 0)\n # del init_params[1]\n init_params = [arr.squeeze() for arr in init_params]\n\n try:\n assert model.tokens_embed.weight.shape == init_params[1].shape\n assert model.positions_embed.weight.shape == init_params[0].shape\n except AssertionError as e:\n e.args += (model.tokens_embed.weight.shape, init_params[1].shape)\n e.args += (model.positions_embed.weight.shape, init_params[0].shape)\n raise\n\n model.tokens_embed.weight.data = torch.from_numpy(init_params[1])\n model.positions_embed.weight.data = torch.from_numpy(init_params[0])\n names.pop(0)\n # Pop position and token embedding arrays\n init_params.pop(0)\n init_params.pop(0)\n\n for name, array in zip(names, init_params): # names[1:n_transfer], init_params[1:n_transfer]):\n name = name[6:] # skip \"model/\"\n assert name[-2:] == \":0\"\n name = name[:-2]\n name = name.split('/')\n pointer = model\n for m_name in name:\n if re.fullmatch(r'[A-Za-z]+\\d+', m_name):\n l = re.split(r'(\\d+)', m_name)\n else:\n l = [m_name]\n if l[0] == 'g':\n pointer = getattr(pointer, 'weight')\n elif l[0] == 'b':\n pointer = getattr(pointer, 'bias')\n elif l[0] == 'w':\n pointer = getattr(pointer, 'weight')\n else:\n pointer = getattr(pointer, l[0])\n if len(l) >= 2:\n num = int(l[1])\n pointer = pointer[num]\n try:\n assert pointer.shape == array.shape\n except AssertionError as e:\n e.args += (pointer.shape, array.shape)\n raise\n try:\n assert pointer.shape == array.shape\n except AssertionError as e:\n e.args += (pointer.shape, array.shape)\n raise\n print(\"Initialize PyTorch weight {}\".format(name))\n pointer.data = torch.from_numpy(array)\n return model" }, { "instruction": "Write or improve a Python function based on this description:\n\nConstructs a `OpenAIGPTConfig` from a Python dictionary of parameters.", "output": "def from_dict(cls, json_object):\n \"\"\"Constructs a `OpenAIGPTConfig` from a Python dictionary of parameters.\"\"\"\n config = OpenAIGPTConfig(vocab_size_or_config_json_file=-1)\n for key, value in json_object.items():\n config.__dict__[key] = value\n return config" }, { "instruction": "Write or improve a Python function based on this description:\n\nUpdate input embeddings with new embedding matrice if needed", "output": "def set_num_special_tokens(self, num_special_tokens):\n \" Update input embeddings with new embedding matrice if needed \"\n if self.config.n_special == num_special_tokens:\n return\n # Update config\n self.config.n_special = num_special_tokens\n # Build new embeddings and initialize all new embeddings (in particular the special tokens)\n old_embed = self.tokens_embed\n self.tokens_embed = nn.Embedding(self.config.total_tokens_embeddings, self.config.n_embd)\n self.tokens_embed.to(old_embed.weight.device)\n self.init_weights(self.tokens_embed)\n # Copy word embeddings from the previous weights\n self.tokens_embed.weight.data[:self.config.vocab_size, :] = old_embed.weight.data[:self.config.vocab_size, :]" }, { "instruction": "Write or improve a Python function based on this description:\n\nUpdate input and output embeddings with new embedding matrice\n Make sure we are sharing the embeddings", "output": "def set_num_special_tokens(self, num_special_tokens):\n \"\"\" Update input and output embeddings with new embedding matrice\n Make sure we are sharing the embeddings\n \"\"\"\n self.transformer.set_num_special_tokens(num_special_tokens)\n self.lm_head.set_embeddings_weights(self.transformer.tokens_embed.weight)" }, { "instruction": "Write or improve a Python function based on this description:\n\nPerforms a single optimization step.\n\n Arguments:\n closure (callable, optional): A closure that reevaluates the model\n and returns the loss.", "output": "def step(self, closure=None):\n \"\"\"Performs a single optimization step.\n\n Arguments:\n closure (callable, optional): A closure that reevaluates the model\n and returns the loss.\n \"\"\"\n loss = None\n if closure is not None:\n loss = closure()\n\n for group in self.param_groups:\n for p in group['params']:\n if p.grad is None:\n continue\n grad = p.grad.data\n if grad.is_sparse:\n raise RuntimeError('Adam does not support sparse gradients, please consider SparseAdam instead')\n\n state = self.state[p]\n\n # State initialization\n if len(state) == 0:\n state['step'] = 0\n # Exponential moving average of gradient values\n state['exp_avg'] = torch.zeros_like(p.data)\n # Exponential moving average of squared gradient values\n state['exp_avg_sq'] = torch.zeros_like(p.data)\n\n exp_avg, exp_avg_sq = state['exp_avg'], state['exp_avg_sq']\n beta1, beta2 = group['b1'], group['b2']\n\n state['step'] += 1\n\n # Add grad clipping\n if group['max_grad_norm'] > 0:\n clip_grad_norm_(p, group['max_grad_norm'])\n\n # Decay the first and second moment running average coefficient\n exp_avg.mul_(beta1).add_(1 - beta1, grad)\n exp_avg_sq.mul_(beta2).addcmul_(1 - beta2, grad, grad)\n denom = exp_avg_sq.sqrt().add_(group['e'])\n\n bias_correction1 = 1 - beta1 ** state['step']\n bias_correction2 = 1 - beta2 ** state['step']\n\n lr_scheduled = group['lr']\n lr_scheduled *= group['schedule'].get_lr(state['step'])\n\n step_size = lr_scheduled * math.sqrt(bias_correction2) / bias_correction1\n\n p.data.addcdiv_(-step_size, exp_avg, denom)\n\n # Add weight decay at the end (fixed version)\n if (len(p.size()) > 1 or group['vector_l2']) and group['weight_decay'] > 0:\n p.data.add_(-lr_scheduled * group['weight_decay'], p.data)\n\n return loss" }, { "instruction": "Write or improve a Python function based on this description:\n\n:param step: which of t_total steps we're on\n :param nowarn: set to True to suppress warning regarding training beyond specified 't_total' steps\n :return: learning rate multiplier for current update", "output": "def get_lr(self, step, nowarn=False):\n \"\"\"\n :param step: which of t_total steps we're on\n :param nowarn: set to True to suppress warning regarding training beyond specified 't_total' steps\n :return: learning rate multiplier for current update\n \"\"\"\n if self.t_total < 0:\n return 1.\n progress = float(step) / self.t_total\n ret = self.get_lr_(progress)\n # warning for exceeding t_total (only active with warmup_linear\n if not nowarn and self.warn_t_total and progress > 1. and progress > self.warned_for_t_total_at_progress:\n logger.warning(\n \"Training beyond specified 't_total'. Learning rate multiplier set to {}. Please set 't_total' of {} correctly.\"\n .format(ret, self.__class__.__name__))\n self.warned_for_t_total_at_progress = progress\n # end warning\n return ret" }, { "instruction": "Write or improve a Python function based on this description:\n\nPerforms a single optimization step.\n\n Arguments:\n closure (callable, optional): A closure that reevaluates the model\n and returns the loss.", "output": "def step(self, closure=None):\n \"\"\"Performs a single optimization step.\n\n Arguments:\n closure (callable, optional): A closure that reevaluates the model\n and returns the loss.\n \"\"\"\n loss = None\n if closure is not None:\n loss = closure()\n\n for group in self.param_groups:\n for p in group['params']:\n if p.grad is None:\n continue\n grad = p.grad.data\n if grad.is_sparse:\n raise RuntimeError('Adam does not support sparse gradients, please consider SparseAdam instead')\n\n state = self.state[p]\n\n # State initialization\n if len(state) == 0:\n state['step'] = 0\n # Exponential moving average of gradient values\n state['next_m'] = torch.zeros_like(p.data)\n # Exponential moving average of squared gradient values\n state['next_v'] = torch.zeros_like(p.data)\n\n next_m, next_v = state['next_m'], state['next_v']\n beta1, beta2 = group['b1'], group['b2']\n\n # Add grad clipping\n if group['max_grad_norm'] > 0:\n clip_grad_norm_(p, group['max_grad_norm'])\n\n # Decay the first and second moment running average coefficient\n # In-place operations to update the averages at the same time\n next_m.mul_(beta1).add_(1 - beta1, grad)\n next_v.mul_(beta2).addcmul_(1 - beta2, grad, grad)\n update = next_m / (next_v.sqrt() + group['e'])\n\n # Just adding the square of the weights to the loss function is *not*\n # the correct way of using L2 regularization/weight decay with Adam,\n # since that will interact with the m and v parameters in strange ways.\n #\n # Instead we want to decay the weights in a manner that doesn't interact\n # with the m/v parameters. This is equivalent to adding the square\n # of the weights to the loss with plain (non-momentum) SGD.\n if group['weight_decay'] > 0.0:\n update += group['weight_decay'] * p.data\n\n lr_scheduled = group['lr']\n lr_scheduled *= group['schedule'].get_lr(state['step'])\n\n update_with_lr = lr_scheduled * update\n p.data.add_(-update_with_lr)\n\n state['step'] += 1\n\n # step_size = lr_scheduled * math.sqrt(bias_correction2) / bias_correction1\n # No bias correction\n # bias_correction1 = 1 - beta1 ** state['step']\n # bias_correction2 = 1 - beta2 ** state['step']\n\n return loss" }, { "instruction": "Write or improve a Python function based on this description:\n\nRuns basic whitespace cleaning and splitting on a piece of text.", "output": "def whitespace_tokenize(text):\n \"\"\"Runs basic whitespace cleaning and splitting on a piece of text.\"\"\"\n text = text.strip()\n if not text:\n return []\n tokens = text.split()\n return tokens" }, { "instruction": "Write or improve a Python function based on this description:\n\nChecks whether `chars` is a punctuation character.", "output": "def _is_punctuation(char):\n \"\"\"Checks whether `chars` is a punctuation character.\"\"\"\n cp = ord(char)\n # We treat all non-letter/number ASCII as punctuation.\n # Characters such as \"^\", \"$\", and \"`\" are not in the Unicode\n # Punctuation class but we treat them as punctuation anyways, for\n # consistency.\n if ((cp >= 33 and cp <= 47) or (cp >= 58 and cp <= 64) or\n (cp >= 91 and cp <= 96) or (cp >= 123 and cp <= 126)):\n return True\n cat = unicodedata.category(char)\n if cat.startswith(\"P\"):\n return True\n return False" }, { "instruction": "Write or improve a Python function based on this description:\n\nConverts a sequence of tokens into ids using the vocab.", "output": "def convert_tokens_to_ids(self, tokens):\n \"\"\"Converts a sequence of tokens into ids using the vocab.\"\"\"\n ids = []\n for token in tokens:\n ids.append(self.vocab[token])\n if len(ids) > self.max_len:\n logger.warning(\n \"Token indices sequence length is longer than the specified maximum \"\n \" sequence length for this BERT model ({} > {}). Running this\"\n \" sequence through BERT will result in indexing errors\".format(len(ids), self.max_len)\n )\n return ids" }, { "instruction": "Write or improve a Python function based on this description:\n\nConverts a sequence of ids in wordpiece tokens using the vocab.", "output": "def convert_ids_to_tokens(self, ids):\n \"\"\"Converts a sequence of ids in wordpiece tokens using the vocab.\"\"\"\n tokens = []\n for i in ids:\n tokens.append(self.ids_to_tokens[i])\n return tokens" }, { "instruction": "Write or improve a Python function based on this description:\n\nSave the tokenizer vocabulary to a directory or file.", "output": "def save_vocabulary(self, vocab_path):\n \"\"\"Save the tokenizer vocabulary to a directory or file.\"\"\"\n index = 0\n if os.path.isdir(vocab_path):\n vocab_file = os.path.join(vocab_path, VOCAB_NAME)\n with open(vocab_file, \"w\", encoding=\"utf-8\") as writer:\n for token, token_index in sorted(self.vocab.items(), key=lambda kv: kv[1]):\n if index != token_index:\n logger.warning(\"Saving vocabulary to {}: vocabulary indices are not consecutive.\"\n \" Please check that the vocabulary is not corrupted!\".format(vocab_file))\n index = token_index\n writer.write(token + u'\\n')\n index += 1\n return vocab_file" }, { "instruction": "Write or improve a Python function based on this description:\n\nInstantiate a PreTrainedBertModel from a pre-trained model file.\n Download and cache the pre-trained model file if needed.", "output": "def from_pretrained(cls, pretrained_model_name_or_path, cache_dir=None, *inputs, **kwargs):\n \"\"\"\n Instantiate a PreTrainedBertModel from a pre-trained model file.\n Download and cache the pre-trained model file if needed.\n \"\"\"\n if pretrained_model_name_or_path in PRETRAINED_VOCAB_ARCHIVE_MAP:\n vocab_file = PRETRAINED_VOCAB_ARCHIVE_MAP[pretrained_model_name_or_path]\n if '-cased' in pretrained_model_name_or_path and kwargs.get('do_lower_case', True):\n logger.warning(\"The pre-trained model you are loading is a cased model but you have not set \"\n \"`do_lower_case` to False. We are setting `do_lower_case=False` for you but \"\n \"you may want to check this behavior.\")\n kwargs['do_lower_case'] = False\n elif '-cased' not in pretrained_model_name_or_path and not kwargs.get('do_lower_case', True):\n logger.warning(\"The pre-trained model you are loading is an uncased model but you have set \"\n \"`do_lower_case` to False. We are setting `do_lower_case=True` for you \"\n \"but you may want to check this behavior.\")\n kwargs['do_lower_case'] = True\n else:\n vocab_file = pretrained_model_name_or_path\n if os.path.isdir(vocab_file):\n vocab_file = os.path.join(vocab_file, VOCAB_NAME)\n # redirect to the cache, if necessary\n try:\n resolved_vocab_file = cached_path(vocab_file, cache_dir=cache_dir)\n except EnvironmentError:\n logger.error(\n \"Model name '{}' was not found in model name list ({}). \"\n \"We assumed '{}' was a path or url but couldn't find any file \"\n \"associated to this path or url.\".format(\n pretrained_model_name_or_path,\n ', '.join(PRETRAINED_VOCAB_ARCHIVE_MAP.keys()),\n vocab_file))\n return None\n if resolved_vocab_file == vocab_file:\n logger.info(\"loading vocabulary file {}\".format(vocab_file))\n else:\n logger.info(\"loading vocabulary file {} from cache at {}\".format(\n vocab_file, resolved_vocab_file))\n if pretrained_model_name_or_path in PRETRAINED_VOCAB_POSITIONAL_EMBEDDINGS_SIZE_MAP:\n # if we're using a pretrained model, ensure the tokenizer wont index sequences longer\n # than the number of positional embeddings\n max_len = PRETRAINED_VOCAB_POSITIONAL_EMBEDDINGS_SIZE_MAP[pretrained_model_name_or_path]\n kwargs['max_len'] = min(kwargs.get('max_len', int(1e12)), max_len)\n # Instantiate tokenizer.\n tokenizer = cls(resolved_vocab_file, *inputs, **kwargs)\n return tokenizer" }, { "instruction": "Write or improve a Python function based on this description:\n\nTokenizes a piece of text.", "output": "def tokenize(self, text):\n \"\"\"Tokenizes a piece of text.\"\"\"\n text = self._clean_text(text)\n # This was added on November 1st, 2018 for the multilingual and Chinese\n # models. This is also applied to the English models now, but it doesn't\n # matter since the English models were not trained on any Chinese data\n # and generally don't have any Chinese data in them (there are Chinese\n # characters in the vocabulary because Wikipedia does have some Chinese\n # words in the English Wikipedia.).\n text = self._tokenize_chinese_chars(text)\n orig_tokens = whitespace_tokenize(text)\n split_tokens = []\n for token in orig_tokens:\n if self.do_lower_case and token not in self.never_split:\n token = token.lower()\n token = self._run_strip_accents(token)\n split_tokens.extend(self._run_split_on_punc(token))\n\n output_tokens = whitespace_tokenize(\" \".join(split_tokens))\n return output_tokens" }, { "instruction": "Write or improve a Python function based on this description:\n\nStrips accents from a piece of text.", "output": "def _run_strip_accents(self, text):\n \"\"\"Strips accents from a piece of text.\"\"\"\n text = unicodedata.normalize(\"NFD\", text)\n output = []\n for char in text:\n cat = unicodedata.category(char)\n if cat == \"Mn\":\n continue\n output.append(char)\n return \"\".join(output)" }, { "instruction": "Write or improve a Python function based on this description:\n\nAdds whitespace around any CJK character.", "output": "def _tokenize_chinese_chars(self, text):\n \"\"\"Adds whitespace around any CJK character.\"\"\"\n output = []\n for char in text:\n cp = ord(char)\n if self._is_chinese_char(cp):\n output.append(\" \")\n output.append(char)\n output.append(\" \")\n else:\n output.append(char)\n return \"\".join(output)" }, { "instruction": "Write or improve a Python function based on this description:\n\nChecks whether CP is the codepoint of a CJK character.", "output": "def _is_chinese_char(self, cp):\n \"\"\"Checks whether CP is the codepoint of a CJK character.\"\"\"\n # This defines a \"chinese character\" as anything in the CJK Unicode block:\n # https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)\n #\n # Note that the CJK Unicode block is NOT all Japanese and Korean characters,\n # despite its name. The modern Korean Hangul alphabet is a different block,\n # as is Japanese Hiragana and Katakana. Those alphabets are used to write\n # space-separated words, so they are not treated specially and handled\n # like the all of the other languages.\n if ((cp >= 0x4E00 and cp <= 0x9FFF) or #\n (cp >= 0x3400 and cp <= 0x4DBF) or #\n (cp >= 0x20000 and cp <= 0x2A6DF) or #\n (cp >= 0x2A700 and cp <= 0x2B73F) or #\n (cp >= 0x2B740 and cp <= 0x2B81F) or #\n (cp >= 0x2B820 and cp <= 0x2CEAF) or\n (cp >= 0xF900 and cp <= 0xFAFF) or #\n (cp >= 0x2F800 and cp <= 0x2FA1F)): #\n return True\n\n return False" }, { "instruction": "Write or improve a Python function based on this description:\n\nTokenizes a piece of text into its word pieces.\n\n This uses a greedy longest-match-first algorithm to perform tokenization\n using the given vocabulary.\n\n For example:\n input = \"unaffable\"\n output = [\"un\", \"##aff\", \"##able\"]\n\n Args:\n text: A single token or whitespace separated tokens. This should have\n already been passed through `BasicTokenizer`.\n\n Returns:\n A list of wordpiece tokens.", "output": "def tokenize(self, text):\n \"\"\"Tokenizes a piece of text into its word pieces.\n\n This uses a greedy longest-match-first algorithm to perform tokenization\n using the given vocabulary.\n\n For example:\n input = \"unaffable\"\n output = [\"un\", \"##aff\", \"##able\"]\n\n Args:\n text: A single token or whitespace separated tokens. This should have\n already been passed through `BasicTokenizer`.\n\n Returns:\n A list of wordpiece tokens.\n \"\"\"\n\n output_tokens = []\n for token in whitespace_tokenize(text):\n chars = list(token)\n if len(chars) > self.max_input_chars_per_word:\n output_tokens.append(self.unk_token)\n continue\n\n is_bad = False\n start = 0\n sub_tokens = []\n while start < len(chars):\n end = len(chars)\n cur_substr = None\n while start < end:\n substr = \"\".join(chars[start:end])\n if start > 0:\n substr = \"##\" + substr\n if substr in self.vocab:\n cur_substr = substr\n break\n end -= 1\n if cur_substr is None:\n is_bad = True\n break\n sub_tokens.append(cur_substr)\n start = end\n\n if is_bad:\n output_tokens.append(self.unk_token)\n else:\n output_tokens.extend(sub_tokens)\n return output_tokens" }, { "instruction": "Write or improve a Python function based on this description:\n\nOutput a list of tuples(story, 1st continuation, 2nd continuation, label)", "output": "def load_rocstories_dataset(dataset_path):\n \"\"\" Output a list of tuples(story, 1st continuation, 2nd continuation, label) \"\"\"\n with open(dataset_path, encoding='utf_8') as f:\n f = csv.reader(f)\n output = []\n next(f) # skip the first line\n for line in tqdm(f):\n output.append((' '.join(line[1:5]), line[5], line[6], int(line[-1])-1))\n return output" }, { "instruction": "Write or improve a Python function based on this description:\n\nPre-process datasets containing lists of tuples(story, 1st continuation, 2nd continuation, label)\n\n To Transformer inputs of shape (n_batch, n_alternative, length) comprising for each batch, continuation:\n input_ids[batch, alternative, :] = [start_token] + story[:cap_length] + [delimiter_token] + cont1[:cap_length] + [clf_token]", "output": "def pre_process_datasets(encoded_datasets, input_len, cap_length, start_token, delimiter_token, clf_token):\n \"\"\" Pre-process datasets containing lists of tuples(story, 1st continuation, 2nd continuation, label)\n\n To Transformer inputs of shape (n_batch, n_alternative, length) comprising for each batch, continuation:\n input_ids[batch, alternative, :] = [start_token] + story[:cap_length] + [delimiter_token] + cont1[:cap_length] + [clf_token]\n \"\"\"\n tensor_datasets = []\n for dataset in encoded_datasets:\n n_batch = len(dataset)\n input_ids = np.zeros((n_batch, 2, input_len), dtype=np.int64)\n mc_token_ids = np.zeros((n_batch, 2), dtype=np.int64)\n lm_labels = np.full((n_batch, 2, input_len), fill_value=-1, dtype=np.int64)\n mc_labels = np.zeros((n_batch,), dtype=np.int64)\n for i, (story, cont1, cont2, mc_label), in enumerate(dataset):\n with_cont1 = [start_token] + story[:cap_length] + [delimiter_token] + cont1[:cap_length] + [clf_token]\n with_cont2 = [start_token] + story[:cap_length] + [delimiter_token] + cont2[:cap_length] + [clf_token]\n input_ids[i, 0, :len(with_cont1)] = with_cont1\n input_ids[i, 1, :len(with_cont2)] = with_cont2\n mc_token_ids[i, 0] = len(with_cont1) - 1\n mc_token_ids[i, 1] = len(with_cont2) - 1\n lm_labels[i, 0, :len(with_cont1)-1] = with_cont1[1:]\n lm_labels[i, 1, :len(with_cont2)-1] = with_cont2[1:]\n mc_labels[i] = mc_label\n all_inputs = (input_ids, mc_token_ids, lm_labels, mc_labels)\n tensor_datasets.append(tuple(torch.tensor(t) for t in all_inputs))\n return tensor_datasets" }, { "instruction": "Write or improve a Python function based on this description:\n\nMasking some random tokens for Language Model task with probabilities as in the original BERT paper.\n :param tokens: list of str, tokenized sentence.\n :param tokenizer: Tokenizer, object used for tokenization (we need it's vocab here)\n :return: (list of str, list of int), masked tokens and related labels for LM prediction", "output": "def random_word(tokens, tokenizer):\n \"\"\"\n Masking some random tokens for Language Model task with probabilities as in the original BERT paper.\n :param tokens: list of str, tokenized sentence.\n :param tokenizer: Tokenizer, object used for tokenization (we need it's vocab here)\n :return: (list of str, list of int), masked tokens and related labels for LM prediction\n \"\"\"\n output_label = []\n\n for i, token in enumerate(tokens):\n prob = random.random()\n # mask token with 15% probability\n if prob < 0.15:\n prob /= 0.15\n\n # 80% randomly change token to mask token\n if prob < 0.8:\n tokens[i] = \"[MASK]\"\n\n # 10% randomly change token to random token\n elif prob < 0.9:\n tokens[i] = random.choice(list(tokenizer.vocab.items()))[0]\n\n # -> rest 10% randomly keep current token\n\n # append current token to output (we will predict these later)\n try:\n output_label.append(tokenizer.vocab[token])\n except KeyError:\n # For unknown words (should not occur with BPE vocab)\n output_label.append(tokenizer.vocab[\"[UNK]\"])\n logger.warning(\"Cannot find token '{}' in vocab. Using [UNK] insetad\".format(token))\n else:\n # no masking token (will be ignored by loss function later)\n output_label.append(-1)\n\n return tokens, output_label" }, { "instruction": "Write or improve a Python function based on this description:\n\nConvert a raw sample (pair of sentences as tokenized strings) into a proper training sample with\n IDs, LM labels, input_mask, CLS and SEP tokens etc.\n :param example: InputExample, containing sentence input as strings and is_next label\n :param max_seq_length: int, maximum length of sequence.\n :param tokenizer: Tokenizer\n :return: InputFeatures, containing all inputs and labels of one sample as IDs (as used for model training)", "output": "def convert_example_to_features(example, max_seq_length, tokenizer):\n \"\"\"\n Convert a raw sample (pair of sentences as tokenized strings) into a proper training sample with\n IDs, LM labels, input_mask, CLS and SEP tokens etc.\n :param example: InputExample, containing sentence input as strings and is_next label\n :param max_seq_length: int, maximum length of sequence.\n :param tokenizer: Tokenizer\n :return: InputFeatures, containing all inputs and labels of one sample as IDs (as used for model training)\n \"\"\"\n tokens_a = example.tokens_a\n tokens_b = example.tokens_b\n # Modifies `tokens_a` and `tokens_b` in place so that the total\n # length is less than the specified length.\n # Account for [CLS], [SEP], [SEP] with \"- 3\"\n _truncate_seq_pair(tokens_a, tokens_b, max_seq_length - 3)\n\n tokens_a, t1_label = random_word(tokens_a, tokenizer)\n tokens_b, t2_label = random_word(tokens_b, tokenizer)\n # concatenate lm labels and account for CLS, SEP, SEP\n lm_label_ids = ([-1] + t1_label + [-1] + t2_label + [-1])\n\n # The convention in BERT is:\n # (a) For sequence pairs:\n # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]\n # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1\n # (b) For single sequences:\n # tokens: [CLS] the dog is hairy . [SEP]\n # type_ids: 0 0 0 0 0 0 0\n #\n # Where \"type_ids\" are used to indicate whether this is the first\n # sequence or the second sequence. The embedding vectors for `type=0` and\n # `type=1` were learned during pre-training and are added to the wordpiece\n # embedding vector (and position vector). This is not *strictly* necessary\n # since the [SEP] token unambigiously separates the sequences, but it makes\n # it easier for the model to learn the concept of sequences.\n #\n # For classification tasks, the first vector (corresponding to [CLS]) is\n # used as as the \"sentence vector\". Note that this only makes sense because\n # the entire model is fine-tuned.\n tokens = []\n segment_ids = []\n tokens.append(\"[CLS]\")\n segment_ids.append(0)\n for token in tokens_a:\n tokens.append(token)\n segment_ids.append(0)\n tokens.append(\"[SEP]\")\n segment_ids.append(0)\n\n assert len(tokens_b) > 0\n for token in tokens_b:\n tokens.append(token)\n segment_ids.append(1)\n tokens.append(\"[SEP]\")\n segment_ids.append(1)\n\n input_ids = tokenizer.convert_tokens_to_ids(tokens)\n\n # The mask has 1 for real tokens and 0 for padding tokens. Only real\n # tokens are attended to.\n input_mask = [1] * len(input_ids)\n\n # Zero-pad up to the sequence length.\n while len(input_ids) < max_seq_length:\n input_ids.append(0)\n input_mask.append(0)\n segment_ids.append(0)\n lm_label_ids.append(-1)\n\n assert len(input_ids) == max_seq_length\n assert len(input_mask) == max_seq_length\n assert len(segment_ids) == max_seq_length\n assert len(lm_label_ids) == max_seq_length\n\n if example.guid < 5:\n logger.info(\"*** Example ***\")\n logger.info(\"guid: %s\" % (example.guid))\n logger.info(\"tokens: %s\" % \" \".join(\n [str(x) for x in tokens]))\n logger.info(\"input_ids: %s\" % \" \".join([str(x) for x in input_ids]))\n logger.info(\"input_mask: %s\" % \" \".join([str(x) for x in input_mask]))\n logger.info(\n \"segment_ids: %s\" % \" \".join([str(x) for x in segment_ids]))\n logger.info(\"LM label: %s \" % (lm_label_ids))\n logger.info(\"Is next sentence label: %s \" % (example.is_next))\n\n features = InputFeatures(input_ids=input_ids,\n input_mask=input_mask,\n segment_ids=segment_ids,\n lm_label_ids=lm_label_ids,\n is_next=example.is_next)\n return features" }, { "instruction": "Write or improve a Python function based on this description:\n\nGet one sample from corpus consisting of two sentences. With prob. 50% these are two subsequent sentences\n from one doc. With 50% the second sentence will be a random one from another doc.\n :param index: int, index of sample.\n :return: (str, str, int), sentence 1, sentence 2, isNextSentence Label", "output": "def random_sent(self, index):\n \"\"\"\n Get one sample from corpus consisting of two sentences. With prob. 50% these are two subsequent sentences\n from one doc. With 50% the second sentence will be a random one from another doc.\n :param index: int, index of sample.\n :return: (str, str, int), sentence 1, sentence 2, isNextSentence Label\n \"\"\"\n t1, t2 = self.get_corpus_line(index)\n if random.random() > 0.5:\n label = 0\n else:\n t2 = self.get_random_line()\n label = 1\n\n assert len(t1) > 0\n assert len(t2) > 0\n return t1, t2, label" }, { "instruction": "Write or improve a Python function based on this description:\n\nGet one sample from corpus consisting of a pair of two subsequent lines from the same doc.\n :param item: int, index of sample.\n :return: (str, str), two subsequent sentences from corpus", "output": "def get_corpus_line(self, item):\n \"\"\"\n Get one sample from corpus consisting of a pair of two subsequent lines from the same doc.\n :param item: int, index of sample.\n :return: (str, str), two subsequent sentences from corpus\n \"\"\"\n t1 = \"\"\n t2 = \"\"\n assert item < self.corpus_lines\n if self.on_memory:\n sample = self.sample_to_doc[item]\n t1 = self.all_docs[sample[\"doc_id\"]][sample[\"line\"]]\n t2 = self.all_docs[sample[\"doc_id\"]][sample[\"line\"]+1]\n # used later to avoid random nextSentence from same doc\n self.current_doc = sample[\"doc_id\"]\n return t1, t2\n else:\n if self.line_buffer is None:\n # read first non-empty line of file\n while t1 == \"\" :\n t1 = next(self.file).strip()\n t2 = next(self.file).strip()\n else:\n # use t2 from previous iteration as new t1\n t1 = self.line_buffer\n t2 = next(self.file).strip()\n # skip empty rows that are used for separating documents and keep track of current doc id\n while t2 == \"\" or t1 == \"\":\n t1 = next(self.file).strip()\n t2 = next(self.file).strip()\n self.current_doc = self.current_doc+1\n self.line_buffer = t2\n\n assert t1 != \"\"\n assert t2 != \"\"\n return t1, t2" }, { "instruction": "Write or improve a Python function based on this description:\n\nGet random line from another document for nextSentence task.\n :return: str, content of one line", "output": "def get_random_line(self):\n \"\"\"\n Get random line from another document for nextSentence task.\n :return: str, content of one line\n \"\"\"\n # Similar to original tf repo: This outer loop should rarely go for more than one iteration for large\n # corpora. However, just to be careful, we try to make sure that\n # the random document is not the same as the document we're processing.\n for _ in range(10):\n if self.on_memory:\n rand_doc_idx = random.randint(0, len(self.all_docs)-1)\n rand_doc = self.all_docs[rand_doc_idx]\n line = rand_doc[random.randrange(len(rand_doc))]\n else:\n rand_index = random.randint(1, self.corpus_lines if self.corpus_lines < 1000 else 1000)\n #pick random line\n for _ in range(rand_index):\n line = self.get_next_line()\n #check if our picked random line is really from another doc like we want it to be\n if self.current_random_doc != self.current_doc:\n break\n return line" }, { "instruction": "Write or improve a Python function based on this description:\n\nGets next line of random_file and starts over when reaching end of file", "output": "def get_next_line(self):\n \"\"\" Gets next line of random_file and starts over when reaching end of file\"\"\"\n try:\n line = next(self.random_file).strip()\n #keep track of which document we are currently looking at to later avoid having the same doc as t1\n if line == \"\":\n self.current_random_doc = self.current_random_doc + 1\n line = next(self.random_file).strip()\n except StopIteration:\n self.random_file.close()\n self.random_file = open(self.corpus_path, \"r\", encoding=self.encoding)\n line = next(self.random_file).strip()\n return line" }, { "instruction": "Write or improve a Python function based on this description:\n\nCreates the predictions for the masked LM objective. This is mostly copied from the Google BERT repo, but\n with several refactors to clean it up and remove a lot of unnecessary variables.", "output": "def create_masked_lm_predictions(tokens, masked_lm_prob, max_predictions_per_seq, vocab_list):\n \"\"\"Creates the predictions for the masked LM objective. This is mostly copied from the Google BERT repo, but\n with several refactors to clean it up and remove a lot of unnecessary variables.\"\"\"\n cand_indices = []\n for (i, token) in enumerate(tokens):\n if token == \"[CLS]\" or token == \"[SEP]\":\n continue\n cand_indices.append(i)\n\n num_to_mask = min(max_predictions_per_seq,\n max(1, int(round(len(tokens) * masked_lm_prob))))\n shuffle(cand_indices)\n mask_indices = sorted(sample(cand_indices, num_to_mask))\n masked_token_labels = []\n for index in mask_indices:\n # 80% of the time, replace with [MASK]\n if random() < 0.8:\n masked_token = \"[MASK]\"\n else:\n # 10% of the time, keep original\n if random() < 0.5:\n masked_token = tokens[index]\n # 10% of the time, replace with random word\n else:\n masked_token = choice(vocab_list)\n masked_token_labels.append(tokens[index])\n # Once we've saved the true label for that token, we can overwrite it with the masked version\n tokens[index] = masked_token\n\n return tokens, mask_indices, masked_token_labels" }, { "instruction": "Write or improve a Python function based on this description:\n\nThis code is mostly a duplicate of the equivalent function from Google BERT's repo.\n However, we make some changes and improvements. Sampling is improved and no longer requires a loop in this function.\n Also, documents are sampled proportionally to the number of sentences they contain, which means each sentence\n (rather than each document) has an equal chance of being sampled as a false example for the NextSentence task.", "output": "def create_instances_from_document(\n doc_database, doc_idx, max_seq_length, short_seq_prob,\n masked_lm_prob, max_predictions_per_seq, vocab_list):\n \"\"\"This code is mostly a duplicate of the equivalent function from Google BERT's repo.\n However, we make some changes and improvements. Sampling is improved and no longer requires a loop in this function.\n Also, documents are sampled proportionally to the number of sentences they contain, which means each sentence\n (rather than each document) has an equal chance of being sampled as a false example for the NextSentence task.\"\"\"\n document = doc_database[doc_idx]\n # Account for [CLS], [SEP], [SEP]\n max_num_tokens = max_seq_length - 3\n\n # We *usually* want to fill up the entire sequence since we are padding\n # to `max_seq_length` anyways, so short sequences are generally wasted\n # computation. However, we *sometimes*\n # (i.e., short_seq_prob == 0.1 == 10% of the time) want to use shorter\n # sequences to minimize the mismatch between pre-training and fine-tuning.\n # The `target_seq_length` is just a rough target however, whereas\n # `max_seq_length` is a hard limit.\n target_seq_length = max_num_tokens\n if random() < short_seq_prob:\n target_seq_length = randint(2, max_num_tokens)\n\n # We DON'T just concatenate all of the tokens from a document into a long\n # sequence and choose an arbitrary split point because this would make the\n # next sentence prediction task too easy. Instead, we split the input into\n # segments \"A\" and \"B\" based on the actual \"sentences\" provided by the user\n # input.\n instances = []\n current_chunk = []\n current_length = 0\n i = 0\n while i < len(document):\n segment = document[i]\n current_chunk.append(segment)\n current_length += len(segment)\n if i == len(document) - 1 or current_length >= target_seq_length:\n if current_chunk:\n # `a_end` is how many segments from `current_chunk` go into the `A`\n # (first) sentence.\n a_end = 1\n if len(current_chunk) >= 2:\n a_end = randrange(1, len(current_chunk))\n\n tokens_a = []\n for j in range(a_end):\n tokens_a.extend(current_chunk[j])\n\n tokens_b = []\n\n # Random next\n if len(current_chunk) == 1 or random() < 0.5:\n is_random_next = True\n target_b_length = target_seq_length - len(tokens_a)\n\n # Sample a random document, with longer docs being sampled more frequently\n random_document = doc_database.sample_doc(current_idx=doc_idx, sentence_weighted=True)\n\n random_start = randrange(0, len(random_document))\n for j in range(random_start, len(random_document)):\n tokens_b.extend(random_document[j])\n if len(tokens_b) >= target_b_length:\n break\n # We didn't actually use these segments so we \"put them back\" so\n # they don't go to waste.\n num_unused_segments = len(current_chunk) - a_end\n i -= num_unused_segments\n # Actual next\n else:\n is_random_next = False\n for j in range(a_end, len(current_chunk)):\n tokens_b.extend(current_chunk[j])\n truncate_seq_pair(tokens_a, tokens_b, max_num_tokens)\n\n assert len(tokens_a) >= 1\n assert len(tokens_b) >= 1\n\n tokens = [\"[CLS]\"] + tokens_a + [\"[SEP]\"] + tokens_b + [\"[SEP]\"]\n # The segment IDs are 0 for the [CLS] token, the A tokens and the first [SEP]\n # They are 1 for the B tokens and the final [SEP]\n segment_ids = [0 for _ in range(len(tokens_a) + 2)] + [1 for _ in range(len(tokens_b) + 1)]\n\n tokens, masked_lm_positions, masked_lm_labels = create_masked_lm_predictions(\n tokens, masked_lm_prob, max_predictions_per_seq, vocab_list)\n\n instance = {\n \"tokens\": tokens,\n \"segment_ids\": segment_ids,\n \"is_random_next\": is_random_next,\n \"masked_lm_positions\": masked_lm_positions,\n \"masked_lm_labels\": masked_lm_labels}\n instances.append(instance)\n current_chunk = []\n current_length = 0\n i += 1\n\n return instances" }, { "instruction": "Write or improve a Python function based on this description:\n\nembedding: an nn.Embedding layer\n bias: [n_vocab]\n labels: [b1, b2]\n inputs: [b1, b2, n_emb]\n sampler: you may use a LogUniformSampler\n Return\n logits: [b1, b2, 1 + n_sample]", "output": "def sample_logits(embedding, bias, labels, inputs, sampler):\n \"\"\"\n embedding: an nn.Embedding layer\n bias: [n_vocab]\n labels: [b1, b2]\n inputs: [b1, b2, n_emb]\n sampler: you may use a LogUniformSampler\n Return\n logits: [b1, b2, 1 + n_sample]\n \"\"\"\n true_log_probs, samp_log_probs, neg_samples = sampler.sample(labels)\n n_sample = neg_samples.size(0)\n b1, b2 = labels.size(0), labels.size(1)\n all_ids = torch.cat([labels.view(-1), neg_samples])\n all_w = embedding(all_ids)\n true_w = all_w[: -n_sample].view(b1, b2, -1)\n sample_w = all_w[- n_sample:].view(n_sample, -1)\n\n all_b = bias[all_ids]\n true_b = all_b[: -n_sample].view(b1, b2)\n sample_b = all_b[- n_sample:]\n\n hit = (labels[:, :, None] == neg_samples).detach()\n\n true_logits = torch.einsum('ijk,ijk->ij',\n [true_w, inputs]) + true_b - true_log_probs\n sample_logits = torch.einsum('lk,ijk->ijl',\n [sample_w, inputs]) + sample_b - samp_log_probs\n sample_logits.masked_fill_(hit, -1e30)\n logits = torch.cat([true_logits[:, :, None], sample_logits], -1)\n\n return logits" }, { "instruction": "Write or improve a Python function based on this description:\n\nParams:\n hidden :: [len*bsz x d_proj]\n target :: [len*bsz]\n Return:\n if target is None:\n out :: [len*bsz] Negative log likelihood\n else:\n out :: [len*bsz x n_tokens] log probabilities of tokens over the vocabulary\n We could replace this implementation by the native PyTorch one\n if their's had an option to set bias on all clusters in the native one.\n here: https://github.com/pytorch/pytorch/blob/dbe6a7a9ff1a364a8706bf5df58a1ca96d2fd9da/torch/nn/modules/adaptive.py#L138", "output": "def forward(self, hidden, target=None, keep_order=False):\n '''\n Params:\n hidden :: [len*bsz x d_proj]\n target :: [len*bsz]\n Return:\n if target is None:\n out :: [len*bsz] Negative log likelihood\n else:\n out :: [len*bsz x n_tokens] log probabilities of tokens over the vocabulary\n We could replace this implementation by the native PyTorch one\n if their's had an option to set bias on all clusters in the native one.\n here: https://github.com/pytorch/pytorch/blob/dbe6a7a9ff1a364a8706bf5df58a1ca96d2fd9da/torch/nn/modules/adaptive.py#L138\n '''\n\n if target is not None:\n target = target.view(-1)\n if hidden.size(0) != target.size(0):\n raise RuntimeError('Input and target should have the same size '\n 'in the batch dimension.')\n\n if self.n_clusters == 0:\n logit = self._compute_logit(hidden, self.out_layers[0].weight,\n self.out_layers[0].bias, self.out_projs[0])\n if target is not None:\n output = -F.log_softmax(logit, dim=-1) \\\n .gather(1, target.unsqueeze(1)).squeeze(1)\n else:\n output = F.log_softmax(logit, dim=-1)\n else:\n # construct weights and biases\n weights, biases = [], []\n for i in range(len(self.cutoffs)):\n if self.div_val == 1:\n l_idx, r_idx = self.cutoff_ends[i], self.cutoff_ends[i + 1]\n weight_i = self.out_layers[0].weight[l_idx:r_idx]\n bias_i = self.out_layers[0].bias[l_idx:r_idx]\n else:\n weight_i = self.out_layers[i].weight\n bias_i = self.out_layers[i].bias\n\n if i == 0:\n weight_i = torch.cat(\n [weight_i, self.cluster_weight], dim=0)\n bias_i = torch.cat(\n [bias_i, self.cluster_bias], dim=0)\n\n weights.append(weight_i)\n biases.append(bias_i)\n\n head_weight, head_bias, head_proj = weights[0], biases[0], self.out_projs[0]\n\n head_logit = self._compute_logit(hidden, head_weight, head_bias, head_proj)\n head_logprob = F.log_softmax(head_logit, dim=1)\n\n if target is None:\n out = hidden.new_empty((head_logit.size(0), self.n_token))\n else:\n out = torch.zeros_like(target, dtype=hidden.dtype, device=hidden.device)\n\n offset = 0\n cutoff_values = [0] + self.cutoffs\n for i in range(len(cutoff_values) - 1):\n l_idx, r_idx = cutoff_values[i], cutoff_values[i + 1]\n\n if target is not None:\n mask_i = (target >= l_idx) & (target < r_idx)\n indices_i = mask_i.nonzero().squeeze()\n\n if indices_i.numel() == 0:\n continue\n\n target_i = target.index_select(0, indices_i) - l_idx\n head_logprob_i = head_logprob.index_select(0, indices_i)\n hidden_i = hidden.index_select(0, indices_i)\n else:\n hidden_i = hidden\n\n if i == 0:\n if target is not None:\n logprob_i = head_logprob_i.gather(1, target_i[:, None]).squeeze(1)\n else:\n out[:, :self.cutoffs[0]] = head_logprob[:, :self.cutoffs[0]]\n else:\n weight_i, bias_i, proj_i = weights[i], biases[i], self.out_projs[i]\n\n tail_logit_i = self._compute_logit(hidden_i, weight_i, bias_i, proj_i)\n tail_logprob_i = F.log_softmax(tail_logit_i, dim=1)\n cluster_prob_idx = self.cutoffs[0] + i - 1 # No probability for the head cluster\n if target is not None:\n logprob_i = head_logprob_i[:, cluster_prob_idx] \\\n + tail_logprob_i.gather(1, target_i[:, None]).squeeze(1)\n else:\n logprob_i = head_logprob[:, cluster_prob_idx, None] + tail_logprob_i\n out[:, l_idx:r_idx] = logprob_i\n\n if target is not None:\n if (hasattr(self, 'keep_order') and self.keep_order) or keep_order:\n out.index_copy_(0, indices_i, -logprob_i)\n else:\n out[offset:offset+logprob_i.size(0)].copy_(-logprob_i)\n offset += logprob_i.size(0)\n\n return out" }, { "instruction": "Write or improve a Python function based on this description:\n\nr\"\"\" Computes log probabilities for all :math:`n\\_classes`\n From: https://github.com/pytorch/pytorch/blob/master/torch/nn/modules/adaptive.py\n Args:\n hidden (Tensor): a minibatch of examples\n Returns:\n log-probabilities of for each class :math:`c`\n in range :math:`0 <= c <= n\\_classes`, where :math:`n\\_classes` is a\n parameter passed to ``AdaptiveLogSoftmaxWithLoss`` constructor.\n Shape:\n - Input: :math:`(N, in\\_features)`\n - Output: :math:`(N, n\\_classes)`", "output": "def log_prob(self, hidden):\n r\"\"\" Computes log probabilities for all :math:`n\\_classes`\n From: https://github.com/pytorch/pytorch/blob/master/torch/nn/modules/adaptive.py\n Args:\n hidden (Tensor): a minibatch of examples\n Returns:\n log-probabilities of for each class :math:`c`\n in range :math:`0 <= c <= n\\_classes`, where :math:`n\\_classes` is a\n parameter passed to ``AdaptiveLogSoftmaxWithLoss`` constructor.\n Shape:\n - Input: :math:`(N, in\\_features)`\n - Output: :math:`(N, n\\_classes)`\n \"\"\"\n if self.n_clusters == 0:\n logit = self._compute_logit(hidden, self.out_layers[0].weight,\n self.out_layers[0].bias, self.out_projs[0])\n return F.log_softmax(logit, dim=-1)\n else:\n # construct weights and biases\n weights, biases = [], []\n for i in range(len(self.cutoffs)):\n if self.div_val == 1:\n l_idx, r_idx = self.cutoff_ends[i], self.cutoff_ends[i + 1]\n weight_i = self.out_layers[0].weight[l_idx:r_idx]\n bias_i = self.out_layers[0].bias[l_idx:r_idx]\n else:\n weight_i = self.out_layers[i].weight\n bias_i = self.out_layers[i].bias\n\n if i == 0:\n weight_i = torch.cat(\n [weight_i, self.cluster_weight], dim=0)\n bias_i = torch.cat(\n [bias_i, self.cluster_bias], dim=0)\n\n weights.append(weight_i)\n biases.append(bias_i)\n\n head_weight, head_bias, head_proj = weights[0], biases[0], self.out_projs[0]\n head_logit = self._compute_logit(hidden, head_weight, head_bias, head_proj)\n\n out = hidden.new_empty((head_logit.size(0), self.n_token))\n head_logprob = F.log_softmax(head_logit, dim=1)\n\n cutoff_values = [0] + self.cutoffs\n for i in range(len(cutoff_values) - 1):\n start_idx, stop_idx = cutoff_values[i], cutoff_values[i + 1]\n\n if i == 0:\n out[:, :self.cutoffs[0]] = head_logprob[:, :self.cutoffs[0]]\n else:\n weight_i, bias_i, proj_i = weights[i], biases[i], self.out_projs[i]\n\n tail_logit_i = self._compute_logit(hidden, weight_i, bias_i, proj_i)\n tail_logprob_i = F.log_softmax(tail_logit_i, dim=1)\n\n logprob_i = head_logprob[:, -i] + tail_logprob_i\n out[:, start_idx, stop_idx] = logprob_i\n\n return out" }, { "instruction": "Write or improve a Python function based on this description:\n\nlabels: [b1, b2]\n Return\n true_log_probs: [b1, b2]\n samp_log_probs: [n_sample]\n neg_samples: [n_sample]", "output": "def sample(self, labels):\n \"\"\"\n labels: [b1, b2]\n Return\n true_log_probs: [b1, b2]\n samp_log_probs: [n_sample]\n neg_samples: [n_sample]\n \"\"\"\n\n # neg_samples = torch.empty(0).long()\n n_sample = self.n_sample\n n_tries = 2 * n_sample\n\n with torch.no_grad():\n neg_samples = torch.multinomial(self.dist, n_tries, replacement=True).unique()\n device = labels.device\n neg_samples = neg_samples.to(device)\n true_log_probs = self.log_q[labels].to(device)\n samp_log_probs = self.log_q[neg_samples].to(device)\n return true_log_probs, samp_log_probs, neg_samples" }, { "instruction": "Write or improve a Python function based on this description:\n\nA map of modules from TF to PyTorch.\n This time I use a map to keep the PyTorch model as identical to the original PyTorch model as possible.", "output": "def build_tf_to_pytorch_map(model, config):\n \"\"\" A map of modules from TF to PyTorch.\n This time I use a map to keep the PyTorch model as identical to the original PyTorch model as possible.\n \"\"\"\n tf_to_pt_map = {}\n\n if hasattr(model, 'transformer'):\n # We are loading in a TransfoXLLMHeadModel => we will load also the Adaptive Softmax\n tf_to_pt_map.update({\n \"transformer/adaptive_softmax/cutoff_0/cluster_W\": model.crit.cluster_weight,\n \"transformer/adaptive_softmax/cutoff_0/cluster_b\": model.crit.cluster_bias})\n for i, (out_l, proj_l, tie_proj) in enumerate(zip(\n model.crit.out_layers,\n model.crit.out_projs,\n config.tie_projs)):\n layer_str = \"transformer/adaptive_softmax/cutoff_%d/\" % i\n if config.tie_weight:\n tf_to_pt_map.update({\n layer_str + 'b': out_l.bias})\n else:\n raise NotImplementedError\n # I don't think this is implemented in the TF code\n tf_to_pt_map.update({\n layer_str + 'lookup_table': out_l.weight,\n layer_str + 'b': out_l.bias})\n if not tie_proj:\n tf_to_pt_map.update({\n layer_str + 'proj': proj_l\n })\n # Now load the rest of the transformer\n model = model.transformer\n\n # Embeddings\n for i, (embed_l, proj_l) in enumerate(zip(model.word_emb.emb_layers, model.word_emb.emb_projs)):\n layer_str = \"transformer/adaptive_embed/cutoff_%d/\" % i\n tf_to_pt_map.update({\n layer_str + 'lookup_table': embed_l.weight,\n layer_str + 'proj_W': proj_l\n })\n\n # Transformer blocks\n for i, b in enumerate(model.layers):\n layer_str = \"transformer/layer_%d/\" % i\n tf_to_pt_map.update({\n layer_str + \"rel_attn/LayerNorm/gamma\": b.dec_attn.layer_norm.weight,\n layer_str + \"rel_attn/LayerNorm/beta\": b.dec_attn.layer_norm.bias,\n layer_str + \"rel_attn/o/kernel\": b.dec_attn.o_net.weight,\n layer_str + \"rel_attn/qkv/kernel\": b.dec_attn.qkv_net.weight,\n layer_str + \"rel_attn/r/kernel\": b.dec_attn.r_net.weight,\n layer_str + \"ff/LayerNorm/gamma\": b.pos_ff.layer_norm.weight,\n layer_str + \"ff/LayerNorm/beta\": b.pos_ff.layer_norm.bias,\n layer_str + \"ff/layer_1/kernel\": b.pos_ff.CoreNet[0].weight,\n layer_str + \"ff/layer_1/bias\": b.pos_ff.CoreNet[0].bias,\n layer_str + \"ff/layer_2/kernel\": b.pos_ff.CoreNet[3].weight,\n layer_str + \"ff/layer_2/bias\": b.pos_ff.CoreNet[3].bias,\n })\n\n # Relative positioning biases\n if config.untie_r:\n r_r_list = []\n r_w_list = []\n for b in model.layers:\n r_r_list.append(b.dec_attn.r_r_bias)\n r_w_list.append(b.dec_attn.r_w_bias)\n else:\n r_r_list = [model.r_r_bias]\n r_w_list = [model.r_w_bias]\n tf_to_pt_map.update({\n 'transformer/r_r_bias': r_r_list,\n 'transformer/r_w_bias': r_w_list})\n return tf_to_pt_map" }, { "instruction": "Write or improve a Python function based on this description:\n\nLoad tf checkpoints in a pytorch model", "output": "def load_tf_weights_in_transfo_xl(model, config, tf_path):\n \"\"\" Load tf checkpoints in a pytorch model\n \"\"\"\n try:\n import numpy as np\n import tensorflow as tf\n except ImportError:\n print(\"Loading a TensorFlow models in PyTorch, requires TensorFlow to be installed. Please see \"\n \"https://www.tensorflow.org/install/ for installation instructions.\")\n raise\n # Build TF to PyTorch weights loading map\n tf_to_pt_map = build_tf_to_pytorch_map(model, config)\n\n # Load weights from TF model\n init_vars = tf.train.list_variables(tf_path)\n tf_weights = {}\n for name, shape in init_vars:\n print(\"Loading TF weight {} with shape {}\".format(name, shape))\n array = tf.train.load_variable(tf_path, name)\n tf_weights[name] = array\n\n for name, pointer in tf_to_pt_map.items():\n assert name in tf_weights\n array = tf_weights[name]\n # adam_v and adam_m are variables used in AdamWeightDecayOptimizer to calculated m and v\n # which are not required for using pretrained model\n if 'kernel' in name or 'proj' in name:\n array = np.transpose(array)\n if ('r_r_bias' in name or 'r_w_bias' in name) and len(pointer) > 1:\n # Here we will split the TF weigths\n assert len(pointer) == array.shape[0]\n for i, p_i in enumerate(pointer):\n arr_i = array[i, ...]\n try:\n assert p_i.shape == arr_i.shape\n except AssertionError as e:\n e.args += (p_i.shape, arr_i.shape)\n raise\n print(\"Initialize PyTorch weight {} for layer {}\".format(name, i))\n p_i.data = torch.from_numpy(arr_i)\n else:\n try:\n assert pointer.shape == array.shape\n except AssertionError as e:\n e.args += (pointer.shape, array.shape)\n raise\n print(\"Initialize PyTorch weight {}\".format(name))\n pointer.data = torch.from_numpy(array)\n tf_weights.pop(name, None)\n tf_weights.pop(name + '/Adam', None)\n tf_weights.pop(name + '/Adam_1', None)\n\n print(\"Weights not copied to PyTorch model: {}\".format(', '.join(tf_weights.keys())))\n return model" }, { "instruction": "Write or improve a Python function based on this description:\n\nInitialize the weights.", "output": "def init_weights(self, m):\n \"\"\" Initialize the weights.\n \"\"\"\n classname = m.__class__.__name__\n if classname.find('Linear') != -1:\n if hasattr(m, 'weight') and m.weight is not None:\n self.init_weight(m.weight)\n if hasattr(m, 'bias') and m.bias is not None:\n self.init_bias(m.bias)\n elif classname.find('AdaptiveEmbedding') != -1:\n if hasattr(m, 'emb_projs'):\n for i in range(len(m.emb_projs)):\n if m.emb_projs[i] is not None:\n nn.init.normal_(m.emb_projs[i], 0.0, self.config.proj_init_std)\n elif classname.find('Embedding') != -1:\n if hasattr(m, 'weight'):\n self.init_weight(m.weight)\n elif classname.find('ProjectedAdaptiveLogSoftmax') != -1:\n if hasattr(m, 'cluster_weight') and m.cluster_weight is not None:\n self.init_weight(m.cluster_weight)\n if hasattr(m, 'cluster_bias') and m.cluster_bias is not None:\n self.init_bias(m.cluster_bias)\n if hasattr(m, 'out_projs'):\n for i in range(len(m.out_projs)):\n if m.out_projs[i] is not None:\n nn.init.normal_(m.out_projs[i], 0.0, self.config.proj_init_std)\n elif classname.find('LayerNorm') != -1:\n if hasattr(m, 'weight'):\n nn.init.normal_(m.weight, 1.0, self.config.init_std)\n if hasattr(m, 'bias') and m.bias is not None:\n self.init_bias(m.bias)\n elif classname.find('TransformerLM') != -1:\n if hasattr(m, 'r_emb'):\n self.init_weight(m.r_emb)\n if hasattr(m, 'r_w_bias'):\n self.init_weight(m.r_w_bias)\n if hasattr(m, 'r_r_bias'):\n self.init_weight(m.r_r_bias)\n if hasattr(m, 'r_bias'):\n self.init_bias(m.r_bias)" }, { "instruction": "Write or improve a Python function based on this description:\n\nInstantiate a TransfoXLPreTrainedModel from a pre-trained model file or a pytorch state dict.\n Download and cache the pre-trained model file if needed.\n\n Params:\n pretrained_model_name_or_path: either:\n - a str with the name of a pre-trained model to load selected in the list of:\n . `transfo-xl`\n - a path or url to a pretrained model archive containing:\n . `transfo_xl_config.json` a configuration file for the model\n . `pytorch_model.bin` a PyTorch dump of a TransfoXLModel instance\n - a path or url to a pretrained model archive containing:\n . `bert_config.json` a configuration file for the model\n . `model.chkpt` a TensorFlow checkpoint\n from_tf: should we load the weights from a locally saved TensorFlow checkpoint\n cache_dir: an optional path to a folder in which the pre-trained models will be cached.\n state_dict: an optional state dictionnary (collections.OrderedDict object) to use instead of pre-trained models\n *inputs, **kwargs: additional input for the specific Bert class\n (ex: num_labels for BertForSequenceClassification)", "output": "def from_pretrained(cls, pretrained_model_name_or_path, state_dict=None, cache_dir=None,\n from_tf=False, *inputs, **kwargs):\n \"\"\"\n Instantiate a TransfoXLPreTrainedModel from a pre-trained model file or a pytorch state dict.\n Download and cache the pre-trained model file if needed.\n\n Params:\n pretrained_model_name_or_path: either:\n - a str with the name of a pre-trained model to load selected in the list of:\n . `transfo-xl`\n - a path or url to a pretrained model archive containing:\n . `transfo_xl_config.json` a configuration file for the model\n . `pytorch_model.bin` a PyTorch dump of a TransfoXLModel instance\n - a path or url to a pretrained model archive containing:\n . `bert_config.json` a configuration file for the model\n . `model.chkpt` a TensorFlow checkpoint\n from_tf: should we load the weights from a locally saved TensorFlow checkpoint\n cache_dir: an optional path to a folder in which the pre-trained models will be cached.\n state_dict: an optional state dictionnary (collections.OrderedDict object) to use instead of pre-trained models\n *inputs, **kwargs: additional input for the specific Bert class\n (ex: num_labels for BertForSequenceClassification)\n \"\"\"\n if pretrained_model_name_or_path in PRETRAINED_MODEL_ARCHIVE_MAP:\n archive_file = PRETRAINED_MODEL_ARCHIVE_MAP[pretrained_model_name_or_path]\n config_file = PRETRAINED_CONFIG_ARCHIVE_MAP[pretrained_model_name_or_path]\n else:\n archive_file = os.path.join(pretrained_model_name_or_path, WEIGHTS_NAME)\n config_file = os.path.join(pretrained_model_name_or_path, CONFIG_NAME)\n # redirect to the cache, if necessary\n try:\n resolved_archive_file = cached_path(archive_file, cache_dir=cache_dir)\n resolved_config_file = cached_path(config_file, cache_dir=cache_dir)\n except EnvironmentError:\n logger.error(\n \"Model name '{}' was not found in model name list ({}). \"\n \"We assumed '{}' was a path or url but couldn't find files {} and {} \"\n \"at this path or url.\".format(\n pretrained_model_name_or_path,\n ', '.join(PRETRAINED_MODEL_ARCHIVE_MAP.keys()),\n pretrained_model_name_or_path,\n archive_file, config_file))\n return None\n if resolved_archive_file == archive_file and resolved_config_file == config_file:\n logger.info(\"loading weights file {}\".format(archive_file))\n logger.info(\"loading configuration file {}\".format(config_file))\n else:\n logger.info(\"loading weights file {} from cache at {}\".format(\n archive_file, resolved_archive_file))\n logger.info(\"loading configuration file {} from cache at {}\".format(\n config_file, resolved_config_file))\n # Load config\n config = TransfoXLConfig.from_json_file(resolved_config_file)\n logger.info(\"Model config {}\".format(config))\n # Instantiate model.\n model = cls(config, *inputs, **kwargs)\n if state_dict is None and not from_tf:\n state_dict = torch.load(resolved_archive_file, map_location='cpu')\n if from_tf:\n # Directly load from a TensorFlow checkpoint\n return load_tf_weights_in_transfo_xl(model, config, pretrained_model_name_or_path)\n\n missing_keys = []\n unexpected_keys = []\n error_msgs = []\n # copy state_dict so _load_from_state_dict can modify it\n metadata = getattr(state_dict, '_metadata', None)\n state_dict = state_dict.copy()\n if metadata is not None:\n state_dict._metadata = metadata\n\n def load(module, prefix=''):\n local_metadata = {} if metadata is None else metadata.get(prefix[:-1], {})\n module._load_from_state_dict(\n state_dict, prefix, local_metadata, True, missing_keys, unexpected_keys, error_msgs)\n for name, child in module._modules.items():\n if child is not None:\n load(child, prefix + name + '.')\n\n start_prefix = ''\n if not hasattr(model, 'transformer') and any(s.startswith('transformer.') for s in state_dict.keys()):\n start_prefix = 'transformer.'\n load(model, prefix=start_prefix)\n\n if len(missing_keys) > 0:\n logger.info(\"Weights of {} not initialized from pretrained model: {}\".format(\n model.__class__.__name__, missing_keys))\n if len(unexpected_keys) > 0:\n logger.info(\"Weights from pretrained model not used in {}: {}\".format(\n model.__class__.__name__, unexpected_keys))\n if len(error_msgs) > 0:\n raise RuntimeError('Error(s) in loading state_dict for {}:\\n\\t{}'.format(\n model.__class__.__name__, \"\\n\\t\".join(error_msgs)))\n # Make sure we are still sharing the input and output embeddings\n if hasattr(model, 'tie_weights'):\n model.tie_weights()\n return model" }, { "instruction": "Write or improve a Python function based on this description:\n\nParams:\n input_ids :: [bsz, len]\n mems :: optional mems from previous forwar passes (or init_mems)\n list (num layers) of mem states at the entry of each layer\n shape :: [self.config.mem_len, bsz, self.config.d_model]\n Note that the first two dimensions are transposed in `mems` with regards to `input_ids` and `target`\n Returns:\n tuple (last_hidden, new_mems) where:\n new_mems: list (num layers) of mem states at the entry of each layer\n shape :: [self.config.mem_len, bsz, self.config.d_model]\n last_hidden: output of the last layer:\n shape :: [bsz, len, self.config.d_model]", "output": "def forward(self, input_ids, mems=None):\n \"\"\" Params:\n input_ids :: [bsz, len]\n mems :: optional mems from previous forwar passes (or init_mems)\n list (num layers) of mem states at the entry of each layer\n shape :: [self.config.mem_len, bsz, self.config.d_model]\n Note that the first two dimensions are transposed in `mems` with regards to `input_ids` and `target`\n Returns:\n tuple (last_hidden, new_mems) where:\n new_mems: list (num layers) of mem states at the entry of each layer\n shape :: [self.config.mem_len, bsz, self.config.d_model]\n last_hidden: output of the last layer:\n shape :: [bsz, len, self.config.d_model]\n \"\"\"\n # the original code for Transformer-XL used shapes [len, bsz] but we want a unified interface in the library\n # so we transpose here from shape [bsz, len] to shape [len, bsz]\n input_ids = input_ids.transpose(0, 1).contiguous()\n\n if mems is None:\n mems = self.init_mems(input_ids)\n last_hidden, new_mems = self._forward(input_ids, mems=mems)\n\n # We transpose back here to shape [bsz, len, hidden_dim]\n last_hidden = last_hidden.transpose(0, 1).contiguous()\n return (last_hidden, new_mems)" }, { "instruction": "Write or improve a Python function based on this description:\n\nRun this to be sure output and input (adaptive) softmax weights are tied", "output": "def tie_weights(self):\n \"\"\" Run this to be sure output and input (adaptive) softmax weights are tied \"\"\"\n # sampled softmax\n if self.sample_softmax > 0:\n if self.config.tie_weight:\n self.out_layer.weight = self.transformer.word_emb.weight\n # adaptive softmax (including standard softmax)\n else:\n if self.config.tie_weight:\n for i in range(len(self.crit.out_layers)):\n self.crit.out_layers[i].weight = self.transformer.word_emb.emb_layers[i].weight\n if self.config.tie_projs:\n for i, tie_proj in enumerate(self.config.tie_projs):\n if tie_proj and self.config.div_val == 1 and self.config.d_model != self.config.d_embed:\n self.crit.out_projs[i] = self.transformer.word_emb.emb_projs[0]\n elif tie_proj and self.config.div_val != 1:\n self.crit.out_projs[i] = self.transformer.word_emb.emb_projs[i]" }, { "instruction": "Write or improve a Python function based on this description:\n\nParams:\n input_ids :: [bsz, len]\n target :: [bsz, len]\n Returns:\n tuple(softmax_output, new_mems) where:\n new_mems: list (num layers) of hidden states at the entry of each layer\n shape :: [mem_len, bsz, self.config.d_model] :: Warning: shapes are transposed here w. regards to input_ids\n softmax_output: output of the (adaptive) softmax:\n if target is None:\n Negative log likelihood of shape :: [bsz, len] \n else:\n log probabilities of tokens, shape :: [bsz, len, n_tokens]", "output": "def forward(self, input_ids, target=None, mems=None):\n \"\"\" Params:\n input_ids :: [bsz, len]\n target :: [bsz, len]\n Returns:\n tuple(softmax_output, new_mems) where:\n new_mems: list (num layers) of hidden states at the entry of each layer\n shape :: [mem_len, bsz, self.config.d_model] :: Warning: shapes are transposed here w. regards to input_ids\n softmax_output: output of the (adaptive) softmax:\n if target is None:\n Negative log likelihood of shape :: [bsz, len] \n else:\n log probabilities of tokens, shape :: [bsz, len, n_tokens]\n \"\"\"\n bsz = input_ids.size(0)\n tgt_len = input_ids.size(1)\n\n last_hidden, new_mems = self.transformer(input_ids, mems)\n\n pred_hid = last_hidden[:, -tgt_len:]\n if self.sample_softmax > 0 and self.training:\n assert self.config.tie_weight\n logit = sample_logits(self.transformer.word_emb, self.out_layer.bias, target, pred_hid, self.sampler)\n softmax_output = -F.log_softmax(logit, -1)[:, :, 0]\n else:\n softmax_output = self.crit(pred_hid.view(-1, pred_hid.size(-1)), target)\n if target is None:\n softmax_output = softmax_output.view(bsz, tgt_len, -1)\n else:\n softmax_output = softmax_output.view(bsz, tgt_len)\n\n # We transpose back\n return (softmax_output, new_mems)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn DateOffset object from string or tuple representation\n or datetime.timedelta object\n\n Parameters\n ----------\n freq : str, tuple, datetime.timedelta, DateOffset or None\n\n Returns\n -------\n DateOffset\n None if freq is None.\n\n Raises\n ------\n ValueError\n If freq is an invalid frequency\n\n See Also\n --------\n DateOffset\n\n Examples\n --------\n >>> to_offset('5min')\n <5 * Minutes>\n\n >>> to_offset('1D1H')\n <25 * Hours>\n\n >>> to_offset(('W', 2))\n <2 * Weeks: weekday=6>\n\n >>> to_offset((2, 'B'))\n <2 * BusinessDays>\n\n >>> to_offset(datetime.timedelta(days=1))\n \n\n >>> to_offset(Hour())\n ", "output": "def to_offset(freq):\n \"\"\"\n Return DateOffset object from string or tuple representation\n or datetime.timedelta object\n\n Parameters\n ----------\n freq : str, tuple, datetime.timedelta, DateOffset or None\n\n Returns\n -------\n DateOffset\n None if freq is None.\n\n Raises\n ------\n ValueError\n If freq is an invalid frequency\n\n See Also\n --------\n DateOffset\n\n Examples\n --------\n >>> to_offset('5min')\n <5 * Minutes>\n\n >>> to_offset('1D1H')\n <25 * Hours>\n\n >>> to_offset(('W', 2))\n <2 * Weeks: weekday=6>\n\n >>> to_offset((2, 'B'))\n <2 * BusinessDays>\n\n >>> to_offset(datetime.timedelta(days=1))\n \n\n >>> to_offset(Hour())\n \n \"\"\"\n if freq is None:\n return None\n\n if isinstance(freq, DateOffset):\n return freq\n\n if isinstance(freq, tuple):\n name = freq[0]\n stride = freq[1]\n if isinstance(stride, str):\n name, stride = stride, name\n name, _ = libfreqs._base_and_stride(name)\n delta = get_offset(name) * stride\n\n elif isinstance(freq, timedelta):\n delta = None\n freq = Timedelta(freq)\n try:\n for name in freq.components._fields:\n offset = _name_to_offset_map[name]\n stride = getattr(freq.components, name)\n if stride != 0:\n offset = stride * offset\n if delta is None:\n delta = offset\n else:\n delta = delta + offset\n except Exception:\n raise ValueError(libfreqs.INVALID_FREQ_ERR_MSG.format(freq))\n\n else:\n delta = None\n stride_sign = None\n try:\n splitted = re.split(libfreqs.opattern, freq)\n if splitted[-1] != '' and not splitted[-1].isspace():\n # the last element must be blank\n raise ValueError('last element must be blank')\n for sep, stride, name in zip(splitted[0::4], splitted[1::4],\n splitted[2::4]):\n if sep != '' and not sep.isspace():\n raise ValueError('separator must be spaces')\n prefix = libfreqs._lite_rule_alias.get(name) or name\n if stride_sign is None:\n stride_sign = -1 if stride.startswith('-') else 1\n if not stride:\n stride = 1\n if prefix in Resolution._reso_str_bump_map.keys():\n stride, name = Resolution.get_stride_from_decimal(\n float(stride), prefix\n )\n stride = int(stride)\n offset = get_offset(name)\n offset = offset * int(np.fabs(stride) * stride_sign)\n if delta is None:\n delta = offset\n else:\n delta = delta + offset\n except Exception:\n raise ValueError(libfreqs.INVALID_FREQ_ERR_MSG.format(freq))\n\n if delta is None:\n raise ValueError(libfreqs.INVALID_FREQ_ERR_MSG.format(freq))\n\n return delta" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn DateOffset object associated with rule name\n\n Examples\n --------\n get_offset('EOM') --> BMonthEnd(1)", "output": "def get_offset(name):\n \"\"\"\n Return DateOffset object associated with rule name\n\n Examples\n --------\n get_offset('EOM') --> BMonthEnd(1)\n \"\"\"\n if name not in libfreqs._dont_uppercase:\n name = name.upper()\n name = libfreqs._lite_rule_alias.get(name, name)\n name = libfreqs._lite_rule_alias.get(name.lower(), name)\n else:\n name = libfreqs._lite_rule_alias.get(name, name)\n\n if name not in _offset_map:\n try:\n split = name.split('-')\n klass = prefix_mapping[split[0]]\n # handles case where there's no suffix (and will TypeError if too\n # many '-')\n offset = klass._from_name(*split[1:])\n except (ValueError, TypeError, KeyError):\n # bad prefix or suffix\n raise ValueError(libfreqs.INVALID_FREQ_ERR_MSG.format(name))\n # cache\n _offset_map[name] = offset\n\n return _offset_map[name]" }, { "instruction": "Write or improve a Python function based on this description:\n\nInfer the most likely frequency given the input index. If the frequency is\n uncertain, a warning will be printed.\n\n Parameters\n ----------\n index : DatetimeIndex or TimedeltaIndex\n if passed a Series will use the values of the series (NOT THE INDEX)\n warn : boolean, default True\n\n Returns\n -------\n str or None\n None if no discernible frequency\n TypeError if the index is not datetime-like\n ValueError if there are less than three values.", "output": "def infer_freq(index, warn=True):\n \"\"\"\n Infer the most likely frequency given the input index. If the frequency is\n uncertain, a warning will be printed.\n\n Parameters\n ----------\n index : DatetimeIndex or TimedeltaIndex\n if passed a Series will use the values of the series (NOT THE INDEX)\n warn : boolean, default True\n\n Returns\n -------\n str or None\n None if no discernible frequency\n TypeError if the index is not datetime-like\n ValueError if there are less than three values.\n \"\"\"\n import pandas as pd\n\n if isinstance(index, ABCSeries):\n values = index._values\n if not (is_datetime64_dtype(values) or\n is_timedelta64_dtype(values) or\n values.dtype == object):\n raise TypeError(\"cannot infer freq from a non-convertible dtype \"\n \"on a Series of {dtype}\".format(dtype=index.dtype))\n index = values\n\n if is_period_arraylike(index):\n raise TypeError(\"PeriodIndex given. Check the `freq` attribute \"\n \"instead of using infer_freq.\")\n elif is_timedelta64_dtype(index):\n # Allow TimedeltaIndex and TimedeltaArray\n inferer = _TimedeltaFrequencyInferer(index, warn=warn)\n return inferer.get_freq()\n\n if isinstance(index, pd.Index) and not isinstance(index, pd.DatetimeIndex):\n if isinstance(index, (pd.Int64Index, pd.Float64Index)):\n raise TypeError(\"cannot infer freq from a non-convertible index \"\n \"type {type}\".format(type=type(index)))\n index = index.values\n\n if not isinstance(index, pd.DatetimeIndex):\n try:\n index = pd.DatetimeIndex(index)\n except AmbiguousTimeError:\n index = pd.DatetimeIndex(index.asi8)\n\n inferer = _FrequencyInferer(index, warn=warn)\n return inferer.get_freq()" }, { "instruction": "Write or improve a Python function based on this description:\n\nFind the appropriate frequency string to describe the inferred\n frequency of self.values\n\n Returns\n -------\n str or None", "output": "def get_freq(self):\n \"\"\"\n Find the appropriate frequency string to describe the inferred\n frequency of self.values\n\n Returns\n -------\n str or None\n \"\"\"\n if not self.is_monotonic or not self.index._is_unique:\n return None\n\n delta = self.deltas[0]\n if _is_multiple(delta, _ONE_DAY):\n return self._infer_daily_rule()\n\n # Business hourly, maybe. 17: one day / 65: one weekend\n if self.hour_deltas in ([1, 17], [1, 65], [1, 17, 65]):\n return 'BH'\n # Possibly intraday frequency. Here we use the\n # original .asi8 values as the modified values\n # will not work around DST transitions. See #8772\n elif not self.is_unique_asi8:\n return None\n\n delta = self.deltas_asi8[0]\n if _is_multiple(delta, _ONE_HOUR):\n # Hours\n return _maybe_add_count('H', delta / _ONE_HOUR)\n elif _is_multiple(delta, _ONE_MINUTE):\n # Minutes\n return _maybe_add_count('T', delta / _ONE_MINUTE)\n elif _is_multiple(delta, _ONE_SECOND):\n # Seconds\n return _maybe_add_count('S', delta / _ONE_SECOND)\n elif _is_multiple(delta, _ONE_MILLI):\n # Milliseconds\n return _maybe_add_count('L', delta / _ONE_MILLI)\n elif _is_multiple(delta, _ONE_MICRO):\n # Microseconds\n return _maybe_add_count('U', delta / _ONE_MICRO)\n else:\n # Nanoseconds\n return _maybe_add_count('N', delta)" }, { "instruction": "Write or improve a Python function based on this description:\n\nload a pickle, with a provided encoding\n\n if compat is True:\n fake the old class hierarchy\n if it works, then return the new type objects\n\n Parameters\n ----------\n fh : a filelike object\n encoding : an optional encoding\n is_verbose : show exception output", "output": "def load(fh, encoding=None, is_verbose=False):\n \"\"\"load a pickle, with a provided encoding\n\n if compat is True:\n fake the old class hierarchy\n if it works, then return the new type objects\n\n Parameters\n ----------\n fh : a filelike object\n encoding : an optional encoding\n is_verbose : show exception output\n \"\"\"\n\n try:\n fh.seek(0)\n if encoding is not None:\n up = Unpickler(fh, encoding=encoding)\n else:\n up = Unpickler(fh)\n up.is_verbose = is_verbose\n\n return up.load()\n except (ValueError, TypeError):\n raise" }, { "instruction": "Write or improve a Python function based on this description:\n\nThis is called upon unpickling, rather than the default which doesn't\n have arguments and breaks __new__.", "output": "def _new_Index(cls, d):\n \"\"\"\n This is called upon unpickling, rather than the default which doesn't\n have arguments and breaks __new__.\n \"\"\"\n # required for backward compat, because PI can't be instantiated with\n # ordinals through __new__ GH #13277\n if issubclass(cls, ABCPeriodIndex):\n from pandas.core.indexes.period import _new_PeriodIndex\n return _new_PeriodIndex(cls, **d)\n return cls.__new__(cls, **d)" }, { "instruction": "Write or improve a Python function based on this description:\n\nConstruct an index from sequences of data.\n\n A single sequence returns an Index. Many sequences returns a\n MultiIndex.\n\n Parameters\n ----------\n sequences : sequence of sequences\n names : sequence of str\n\n Returns\n -------\n index : Index or MultiIndex\n\n Examples\n --------\n >>> ensure_index_from_sequences([[1, 2, 3]], names=['name'])\n Int64Index([1, 2, 3], dtype='int64', name='name')\n\n >>> ensure_index_from_sequences([['a', 'a'], ['a', 'b']],\n names=['L1', 'L2'])\n MultiIndex(levels=[['a'], ['a', 'b']],\n codes=[[0, 0], [0, 1]],\n names=['L1', 'L2'])\n\n See Also\n --------\n ensure_index", "output": "def ensure_index_from_sequences(sequences, names=None):\n \"\"\"\n Construct an index from sequences of data.\n\n A single sequence returns an Index. Many sequences returns a\n MultiIndex.\n\n Parameters\n ----------\n sequences : sequence of sequences\n names : sequence of str\n\n Returns\n -------\n index : Index or MultiIndex\n\n Examples\n --------\n >>> ensure_index_from_sequences([[1, 2, 3]], names=['name'])\n Int64Index([1, 2, 3], dtype='int64', name='name')\n\n >>> ensure_index_from_sequences([['a', 'a'], ['a', 'b']],\n names=['L1', 'L2'])\n MultiIndex(levels=[['a'], ['a', 'b']],\n codes=[[0, 0], [0, 1]],\n names=['L1', 'L2'])\n\n See Also\n --------\n ensure_index\n \"\"\"\n from .multi import MultiIndex\n\n if len(sequences) == 1:\n if names is not None:\n names = names[0]\n return Index(sequences[0], name=names)\n else:\n return MultiIndex.from_arrays(sequences, names=names)" }, { "instruction": "Write or improve a Python function based on this description:\n\nEnsure that we have an index from some index-like object.\n\n Parameters\n ----------\n index : sequence\n An Index or other sequence\n copy : bool\n\n Returns\n -------\n index : Index or MultiIndex\n\n Examples\n --------\n >>> ensure_index(['a', 'b'])\n Index(['a', 'b'], dtype='object')\n\n >>> ensure_index([('a', 'a'), ('b', 'c')])\n Index([('a', 'a'), ('b', 'c')], dtype='object')\n\n >>> ensure_index([['a', 'a'], ['b', 'c']])\n MultiIndex(levels=[['a'], ['b', 'c']],\n codes=[[0, 0], [0, 1]])\n\n See Also\n --------\n ensure_index_from_sequences", "output": "def ensure_index(index_like, copy=False):\n \"\"\"\n Ensure that we have an index from some index-like object.\n\n Parameters\n ----------\n index : sequence\n An Index or other sequence\n copy : bool\n\n Returns\n -------\n index : Index or MultiIndex\n\n Examples\n --------\n >>> ensure_index(['a', 'b'])\n Index(['a', 'b'], dtype='object')\n\n >>> ensure_index([('a', 'a'), ('b', 'c')])\n Index([('a', 'a'), ('b', 'c')], dtype='object')\n\n >>> ensure_index([['a', 'a'], ['b', 'c']])\n MultiIndex(levels=[['a'], ['b', 'c']],\n codes=[[0, 0], [0, 1]])\n\n See Also\n --------\n ensure_index_from_sequences\n \"\"\"\n if isinstance(index_like, Index):\n if copy:\n index_like = index_like.copy()\n return index_like\n if hasattr(index_like, 'name'):\n return Index(index_like, name=index_like.name, copy=copy)\n\n if is_iterator(index_like):\n index_like = list(index_like)\n\n # must check for exactly list here because of strict type\n # check in clean_index_list\n if isinstance(index_like, list):\n if type(index_like) != list:\n index_like = list(index_like)\n\n converted, all_arrays = lib.clean_index_list(index_like)\n\n if len(converted) > 0 and all_arrays:\n from .multi import MultiIndex\n return MultiIndex.from_arrays(converted)\n else:\n index_like = converted\n else:\n # clean_index_list does the equivalent of copying\n # so only need to do this if not list instance\n if copy:\n from copy import copy\n index_like = copy(index_like)\n\n return Index(index_like)" }, { "instruction": "Write or improve a Python function based on this description:\n\nTrims zeros and decimal points.", "output": "def _trim_front(strings):\n \"\"\"\n Trims zeros and decimal points.\n \"\"\"\n trimmed = strings\n while len(strings) > 0 and all(x[0] == ' ' for x in trimmed):\n trimmed = [x[1:] for x in trimmed]\n return trimmed" }, { "instruction": "Write or improve a Python function based on this description:\n\nWe require that we have a dtype compat for the values. If we are passed\n a non-dtype compat, then coerce using the constructor.\n\n Must be careful not to recurse.", "output": "def _simple_new(cls, values, name=None, dtype=None, **kwargs):\n \"\"\"\n We require that we have a dtype compat for the values. If we are passed\n a non-dtype compat, then coerce using the constructor.\n\n Must be careful not to recurse.\n \"\"\"\n if not hasattr(values, 'dtype'):\n if (values is None or not len(values)) and dtype is not None:\n values = np.empty(0, dtype=dtype)\n else:\n values = np.array(values, copy=False)\n if is_object_dtype(values):\n values = cls(values, name=name, dtype=dtype,\n **kwargs)._ndarray_values\n\n if isinstance(values, (ABCSeries, ABCIndexClass)):\n # Index._data must always be an ndarray.\n # This is no-copy for when _values is an ndarray,\n # which should be always at this point.\n values = np.asarray(values._values)\n\n result = object.__new__(cls)\n result._data = values\n # _index_data is a (temporary?) fix to ensure that the direct data\n # manipulation we do in `_libs/reduction.pyx` continues to work.\n # We need access to the actual ndarray, since we're messing with\n # data buffers and strides. We don't re-use `_ndarray_values`, since\n # we actually set this value too.\n result._index_data = values\n result.name = name\n for k, v in kwargs.items():\n setattr(result, k, v)\n return result._reset_identity()" }, { "instruction": "Write or improve a Python function based on this description:\n\nCreate a new Index inferring the class with passed value, don't copy\n the data, use the same object attributes with passed in attributes\n taking precedence.\n\n *this is an internal non-public method*\n\n Parameters\n ----------\n values : the values to create the new Index, optional\n kwargs : updates the default attributes for this Index", "output": "def _shallow_copy_with_infer(self, values, **kwargs):\n \"\"\"\n Create a new Index inferring the class with passed value, don't copy\n the data, use the same object attributes with passed in attributes\n taking precedence.\n\n *this is an internal non-public method*\n\n Parameters\n ----------\n values : the values to create the new Index, optional\n kwargs : updates the default attributes for this Index\n \"\"\"\n attributes = self._get_attributes_dict()\n attributes.update(kwargs)\n attributes['copy'] = False\n if not len(values) and 'dtype' not in kwargs:\n attributes['dtype'] = self.dtype\n if self._infer_as_myclass:\n try:\n return self._constructor(values, **attributes)\n except (TypeError, ValueError):\n pass\n return Index(values, **attributes)" }, { "instruction": "Write or improve a Python function based on this description:\n\nMore flexible, faster check like ``is`` but that works through views.\n\n Note: this is *not* the same as ``Index.identical()``, which checks\n that metadata is also the same.\n\n Parameters\n ----------\n other : object\n other object to compare against.\n\n Returns\n -------\n True if both have same underlying data, False otherwise : bool", "output": "def is_(self, other):\n \"\"\"\n More flexible, faster check like ``is`` but that works through views.\n\n Note: this is *not* the same as ``Index.identical()``, which checks\n that metadata is also the same.\n\n Parameters\n ----------\n other : object\n other object to compare against.\n\n Returns\n -------\n True if both have same underlying data, False otherwise : bool\n \"\"\"\n # use something other than None to be clearer\n return self._id is getattr(\n other, '_id', Ellipsis) and self._id is not None" }, { "instruction": "Write or improve a Python function based on this description:\n\nInternal method to handle NA filling of take.", "output": "def _assert_take_fillable(self, values, indices, allow_fill=True,\n fill_value=None, na_value=np.nan):\n \"\"\"\n Internal method to handle NA filling of take.\n \"\"\"\n indices = ensure_platform_int(indices)\n\n # only fill if we are passing a non-None fill_value\n if allow_fill and fill_value is not None:\n if (indices < -1).any():\n msg = ('When allow_fill=True and fill_value is not None, '\n 'all indices must be >= -1')\n raise ValueError(msg)\n taken = algos.take(values,\n indices,\n allow_fill=allow_fill,\n fill_value=na_value)\n else:\n taken = values.take(indices)\n return taken" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn the formatted data as a unicode string.", "output": "def _format_data(self, name=None):\n \"\"\"\n Return the formatted data as a unicode string.\n \"\"\"\n\n # do we want to justify (only do so for non-objects)\n is_justify = not (self.inferred_type in ('string', 'unicode') or\n (self.inferred_type == 'categorical' and\n is_object_dtype(self.categories)))\n\n return format_object_summary(self, self._formatter_func,\n is_justify=is_justify, name=name)" }, { "instruction": "Write or improve a Python function based on this description:\n\nRender a string representation of the Index.", "output": "def format(self, name=False, formatter=None, **kwargs):\n \"\"\"\n Render a string representation of the Index.\n \"\"\"\n header = []\n if name:\n header.append(pprint_thing(self.name,\n escape_chars=('\\t', '\\r', '\\n')) if\n self.name is not None else '')\n\n if formatter is not None:\n return header + list(self.map(formatter))\n\n return self._format_with_header(header, **kwargs)" }, { "instruction": "Write or improve a Python function based on this description:\n\nFormat specified values of `self` and return them.\n\n Parameters\n ----------\n slicer : int, array-like\n An indexer into `self` that specifies which values\n are used in the formatting process.\n kwargs : dict\n Options for specifying how the values should be formatted.\n These options include the following:\n\n 1) na_rep : str\n The value that serves as a placeholder for NULL values\n 2) quoting : bool or None\n Whether or not there are quoted values in `self`\n 3) date_format : str\n The format used to represent date-like values", "output": "def to_native_types(self, slicer=None, **kwargs):\n \"\"\"\n Format specified values of `self` and return them.\n\n Parameters\n ----------\n slicer : int, array-like\n An indexer into `self` that specifies which values\n are used in the formatting process.\n kwargs : dict\n Options for specifying how the values should be formatted.\n These options include the following:\n\n 1) na_rep : str\n The value that serves as a placeholder for NULL values\n 2) quoting : bool or None\n Whether or not there are quoted values in `self`\n 3) date_format : str\n The format used to represent date-like values\n \"\"\"\n\n values = self\n if slicer is not None:\n values = values[slicer]\n return values._format_native_types(**kwargs)" }, { "instruction": "Write or improve a Python function based on this description:\n\nActually format specific types of the index.", "output": "def _format_native_types(self, na_rep='', quoting=None, **kwargs):\n \"\"\"\n Actually format specific types of the index.\n \"\"\"\n mask = isna(self)\n if not self.is_object() and not quoting:\n values = np.asarray(self).astype(str)\n else:\n values = np.array(self, dtype=object, copy=True)\n\n values[mask] = na_rep\n return values" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn a summarized representation.\n\n Parameters\n ----------\n name : str\n name to use in the summary representation\n\n Returns\n -------\n String with a summarized representation of the index", "output": "def _summary(self, name=None):\n \"\"\"\n Return a summarized representation.\n\n Parameters\n ----------\n name : str\n name to use in the summary representation\n\n Returns\n -------\n String with a summarized representation of the index\n \"\"\"\n if len(self) > 0:\n head = self[0]\n if hasattr(head, 'format') and not isinstance(head, str):\n head = head.format()\n tail = self[-1]\n if hasattr(tail, 'format') and not isinstance(tail, str):\n tail = tail.format()\n index_summary = ', %s to %s' % (pprint_thing(head),\n pprint_thing(tail))\n else:\n index_summary = ''\n\n if name is None:\n name = type(self).__name__\n return '%s: %s entries%s' % (name, len(self), index_summary)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn a summarized representation.\n\n .. deprecated:: 0.23.0", "output": "def summary(self, name=None):\n \"\"\"\n Return a summarized representation.\n\n .. deprecated:: 0.23.0\n \"\"\"\n warnings.warn(\"'summary' is deprecated and will be removed in a \"\n \"future version.\", FutureWarning, stacklevel=2)\n return self._summary(name)" }, { "instruction": "Write or improve a Python function based on this description:\n\nCreate a Series with both index and values equal to the index keys\n useful with map for returning an indexer based on an index.\n\n Parameters\n ----------\n index : Index, optional\n index of resulting Series. If None, defaults to original index\n name : string, optional\n name of resulting Series. If None, defaults to name of original\n index\n\n Returns\n -------\n Series : dtype will be based on the type of the Index values.", "output": "def to_series(self, index=None, name=None):\n \"\"\"\n Create a Series with both index and values equal to the index keys\n useful with map for returning an indexer based on an index.\n\n Parameters\n ----------\n index : Index, optional\n index of resulting Series. If None, defaults to original index\n name : string, optional\n name of resulting Series. If None, defaults to name of original\n index\n\n Returns\n -------\n Series : dtype will be based on the type of the Index values.\n \"\"\"\n\n from pandas import Series\n\n if index is None:\n index = self._shallow_copy()\n if name is None:\n name = self.name\n\n return Series(self.values.copy(), index=index, name=name)" }, { "instruction": "Write or improve a Python function based on this description:\n\nCreate a DataFrame with a column containing the Index.\n\n .. versionadded:: 0.24.0\n\n Parameters\n ----------\n index : boolean, default True\n Set the index of the returned DataFrame as the original Index.\n\n name : object, default None\n The passed name should substitute for the index name (if it has\n one).\n\n Returns\n -------\n DataFrame\n DataFrame containing the original Index data.\n\n See Also\n --------\n Index.to_series : Convert an Index to a Series.\n Series.to_frame : Convert Series to DataFrame.\n\n Examples\n --------\n >>> idx = pd.Index(['Ant', 'Bear', 'Cow'], name='animal')\n >>> idx.to_frame()\n animal\n animal\n Ant Ant\n Bear Bear\n Cow Cow\n\n By default, the original Index is reused. To enforce a new Index:\n\n >>> idx.to_frame(index=False)\n animal\n 0 Ant\n 1 Bear\n 2 Cow\n\n To override the name of the resulting column, specify `name`:\n\n >>> idx.to_frame(index=False, name='zoo')\n zoo\n 0 Ant\n 1 Bear\n 2 Cow", "output": "def to_frame(self, index=True, name=None):\n \"\"\"\n Create a DataFrame with a column containing the Index.\n\n .. versionadded:: 0.24.0\n\n Parameters\n ----------\n index : boolean, default True\n Set the index of the returned DataFrame as the original Index.\n\n name : object, default None\n The passed name should substitute for the index name (if it has\n one).\n\n Returns\n -------\n DataFrame\n DataFrame containing the original Index data.\n\n See Also\n --------\n Index.to_series : Convert an Index to a Series.\n Series.to_frame : Convert Series to DataFrame.\n\n Examples\n --------\n >>> idx = pd.Index(['Ant', 'Bear', 'Cow'], name='animal')\n >>> idx.to_frame()\n animal\n animal\n Ant Ant\n Bear Bear\n Cow Cow\n\n By default, the original Index is reused. To enforce a new Index:\n\n >>> idx.to_frame(index=False)\n animal\n 0 Ant\n 1 Bear\n 2 Cow\n\n To override the name of the resulting column, specify `name`:\n\n >>> idx.to_frame(index=False, name='zoo')\n zoo\n 0 Ant\n 1 Bear\n 2 Cow\n \"\"\"\n\n from pandas import DataFrame\n if name is None:\n name = self.name or 0\n result = DataFrame({name: self._values.copy()})\n\n if index:\n result.index = self\n return result" }, { "instruction": "Write or improve a Python function based on this description:\n\nHandles the quirks of having a singular 'name' parameter for general\n Index and plural 'names' parameter for MultiIndex.", "output": "def _validate_names(self, name=None, names=None, deep=False):\n \"\"\"\n Handles the quirks of having a singular 'name' parameter for general\n Index and plural 'names' parameter for MultiIndex.\n \"\"\"\n from copy import deepcopy\n if names is not None and name is not None:\n raise TypeError(\"Can only provide one of `names` and `name`\")\n elif names is None and name is None:\n return deepcopy(self.names) if deep else self.names\n elif names is not None:\n if not is_list_like(names):\n raise TypeError(\"Must pass list-like as `names`.\")\n return names\n else:\n if not is_list_like(name):\n return [name]\n return name" }, { "instruction": "Write or improve a Python function based on this description:\n\nSet new names on index. Each name has to be a hashable type.\n\n Parameters\n ----------\n values : str or sequence\n name(s) to set\n level : int, level name, or sequence of int/level names (default None)\n If the index is a MultiIndex (hierarchical), level(s) to set (None\n for all levels). Otherwise level must be None\n\n Raises\n ------\n TypeError if each name is not hashable.", "output": "def _set_names(self, values, level=None):\n \"\"\"\n Set new names on index. Each name has to be a hashable type.\n\n Parameters\n ----------\n values : str or sequence\n name(s) to set\n level : int, level name, or sequence of int/level names (default None)\n If the index is a MultiIndex (hierarchical), level(s) to set (None\n for all levels). Otherwise level must be None\n\n Raises\n ------\n TypeError if each name is not hashable.\n \"\"\"\n if not is_list_like(values):\n raise ValueError('Names must be a list-like')\n if len(values) != 1:\n raise ValueError('Length of new names must be 1, got %d' %\n len(values))\n\n # GH 20527\n # All items in 'name' need to be hashable:\n for name in values:\n if not is_hashable(name):\n raise TypeError('{}.name must be a hashable type'\n .format(self.__class__.__name__))\n self.name = values[0]" }, { "instruction": "Write or improve a Python function based on this description:\n\nSet Index or MultiIndex name.\n\n Able to set new names partially and by level.\n\n Parameters\n ----------\n names : label or list of label\n Name(s) to set.\n level : int, label or list of int or label, optional\n If the index is a MultiIndex, level(s) to set (None for all\n levels). Otherwise level must be None.\n inplace : bool, default False\n Modifies the object directly, instead of creating a new Index or\n MultiIndex.\n\n Returns\n -------\n Index\n The same type as the caller or None if inplace is True.\n\n See Also\n --------\n Index.rename : Able to set new names without level.\n\n Examples\n --------\n >>> idx = pd.Index([1, 2, 3, 4])\n >>> idx\n Int64Index([1, 2, 3, 4], dtype='int64')\n >>> idx.set_names('quarter')\n Int64Index([1, 2, 3, 4], dtype='int64', name='quarter')\n\n >>> idx = pd.MultiIndex.from_product([['python', 'cobra'],\n ... [2018, 2019]])\n >>> idx\n MultiIndex(levels=[['cobra', 'python'], [2018, 2019]],\n codes=[[1, 1, 0, 0], [0, 1, 0, 1]])\n >>> idx.set_names(['kind', 'year'], inplace=True)\n >>> idx\n MultiIndex(levels=[['cobra', 'python'], [2018, 2019]],\n codes=[[1, 1, 0, 0], [0, 1, 0, 1]],\n names=['kind', 'year'])\n >>> idx.set_names('species', level=0)\n MultiIndex(levels=[['cobra', 'python'], [2018, 2019]],\n codes=[[1, 1, 0, 0], [0, 1, 0, 1]],\n names=['species', 'year'])", "output": "def set_names(self, names, level=None, inplace=False):\n \"\"\"\n Set Index or MultiIndex name.\n\n Able to set new names partially and by level.\n\n Parameters\n ----------\n names : label or list of label\n Name(s) to set.\n level : int, label or list of int or label, optional\n If the index is a MultiIndex, level(s) to set (None for all\n levels). Otherwise level must be None.\n inplace : bool, default False\n Modifies the object directly, instead of creating a new Index or\n MultiIndex.\n\n Returns\n -------\n Index\n The same type as the caller or None if inplace is True.\n\n See Also\n --------\n Index.rename : Able to set new names without level.\n\n Examples\n --------\n >>> idx = pd.Index([1, 2, 3, 4])\n >>> idx\n Int64Index([1, 2, 3, 4], dtype='int64')\n >>> idx.set_names('quarter')\n Int64Index([1, 2, 3, 4], dtype='int64', name='quarter')\n\n >>> idx = pd.MultiIndex.from_product([['python', 'cobra'],\n ... [2018, 2019]])\n >>> idx\n MultiIndex(levels=[['cobra', 'python'], [2018, 2019]],\n codes=[[1, 1, 0, 0], [0, 1, 0, 1]])\n >>> idx.set_names(['kind', 'year'], inplace=True)\n >>> idx\n MultiIndex(levels=[['cobra', 'python'], [2018, 2019]],\n codes=[[1, 1, 0, 0], [0, 1, 0, 1]],\n names=['kind', 'year'])\n >>> idx.set_names('species', level=0)\n MultiIndex(levels=[['cobra', 'python'], [2018, 2019]],\n codes=[[1, 1, 0, 0], [0, 1, 0, 1]],\n names=['species', 'year'])\n \"\"\"\n\n if level is not None and not isinstance(self, ABCMultiIndex):\n raise ValueError('Level must be None for non-MultiIndex')\n\n if level is not None and not is_list_like(level) and is_list_like(\n names):\n msg = \"Names must be a string when a single level is provided.\"\n raise TypeError(msg)\n\n if not is_list_like(names) and level is None and self.nlevels > 1:\n raise TypeError(\"Must pass list-like as `names`.\")\n\n if not is_list_like(names):\n names = [names]\n if level is not None and not is_list_like(level):\n level = [level]\n\n if inplace:\n idx = self\n else:\n idx = self._shallow_copy()\n idx._set_names(names, level=level)\n if not inplace:\n return idx" }, { "instruction": "Write or improve a Python function based on this description:\n\nAlter Index or MultiIndex name.\n\n Able to set new names without level. Defaults to returning new index.\n Length of names must match number of levels in MultiIndex.\n\n Parameters\n ----------\n name : label or list of labels\n Name(s) to set.\n inplace : boolean, default False\n Modifies the object directly, instead of creating a new Index or\n MultiIndex.\n\n Returns\n -------\n Index\n The same type as the caller or None if inplace is True.\n\n See Also\n --------\n Index.set_names : Able to set new names partially and by level.\n\n Examples\n --------\n >>> idx = pd.Index(['A', 'C', 'A', 'B'], name='score')\n >>> idx.rename('grade')\n Index(['A', 'C', 'A', 'B'], dtype='object', name='grade')\n\n >>> idx = pd.MultiIndex.from_product([['python', 'cobra'],\n ... [2018, 2019]],\n ... names=['kind', 'year'])\n >>> idx\n MultiIndex(levels=[['cobra', 'python'], [2018, 2019]],\n codes=[[1, 1, 0, 0], [0, 1, 0, 1]],\n names=['kind', 'year'])\n >>> idx.rename(['species', 'year'])\n MultiIndex(levels=[['cobra', 'python'], [2018, 2019]],\n codes=[[1, 1, 0, 0], [0, 1, 0, 1]],\n names=['species', 'year'])\n >>> idx.rename('species')\n Traceback (most recent call last):\n TypeError: Must pass list-like as `names`.", "output": "def rename(self, name, inplace=False):\n \"\"\"\n Alter Index or MultiIndex name.\n\n Able to set new names without level. Defaults to returning new index.\n Length of names must match number of levels in MultiIndex.\n\n Parameters\n ----------\n name : label or list of labels\n Name(s) to set.\n inplace : boolean, default False\n Modifies the object directly, instead of creating a new Index or\n MultiIndex.\n\n Returns\n -------\n Index\n The same type as the caller or None if inplace is True.\n\n See Also\n --------\n Index.set_names : Able to set new names partially and by level.\n\n Examples\n --------\n >>> idx = pd.Index(['A', 'C', 'A', 'B'], name='score')\n >>> idx.rename('grade')\n Index(['A', 'C', 'A', 'B'], dtype='object', name='grade')\n\n >>> idx = pd.MultiIndex.from_product([['python', 'cobra'],\n ... [2018, 2019]],\n ... names=['kind', 'year'])\n >>> idx\n MultiIndex(levels=[['cobra', 'python'], [2018, 2019]],\n codes=[[1, 1, 0, 0], [0, 1, 0, 1]],\n names=['kind', 'year'])\n >>> idx.rename(['species', 'year'])\n MultiIndex(levels=[['cobra', 'python'], [2018, 2019]],\n codes=[[1, 1, 0, 0], [0, 1, 0, 1]],\n names=['species', 'year'])\n >>> idx.rename('species')\n Traceback (most recent call last):\n TypeError: Must pass list-like as `names`.\n \"\"\"\n return self.set_names([name], inplace=inplace)" }, { "instruction": "Write or improve a Python function based on this description:\n\nValidate index level.\n\n For single-level Index getting level number is a no-op, but some\n verification must be done like in MultiIndex.", "output": "def _validate_index_level(self, level):\n \"\"\"\n Validate index level.\n\n For single-level Index getting level number is a no-op, but some\n verification must be done like in MultiIndex.\n\n \"\"\"\n if isinstance(level, int):\n if level < 0 and level != -1:\n raise IndexError(\"Too many levels: Index has only 1 level,\"\n \" %d is not a valid level number\" % (level, ))\n elif level > 0:\n raise IndexError(\"Too many levels:\"\n \" Index has only 1 level, not %d\" %\n (level + 1))\n elif level != self.name:\n raise KeyError('Level %s must be same as name (%s)' %\n (level, self.name))" }, { "instruction": "Write or improve a Python function based on this description:\n\nFor internal compatibility with with the Index API.\n\n Sort the Index. This is for compat with MultiIndex\n\n Parameters\n ----------\n ascending : boolean, default True\n False to sort in descending order\n\n level, sort_remaining are compat parameters\n\n Returns\n -------\n Index", "output": "def sortlevel(self, level=None, ascending=True, sort_remaining=None):\n \"\"\"\n For internal compatibility with with the Index API.\n\n Sort the Index. This is for compat with MultiIndex\n\n Parameters\n ----------\n ascending : boolean, default True\n False to sort in descending order\n\n level, sort_remaining are compat parameters\n\n Returns\n -------\n Index\n \"\"\"\n return self.sort_values(return_indexer=True, ascending=ascending)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn index with requested level(s) removed.\n\n If resulting index has only 1 level left, the result will be\n of Index type, not MultiIndex.\n\n .. versionadded:: 0.23.1 (support for non-MultiIndex)\n\n Parameters\n ----------\n level : int, str, or list-like, default 0\n If a string is given, must be the name of a level\n If list-like, elements must be names or indexes of levels.\n\n Returns\n -------\n Index or MultiIndex", "output": "def droplevel(self, level=0):\n \"\"\"\n Return index with requested level(s) removed.\n\n If resulting index has only 1 level left, the result will be\n of Index type, not MultiIndex.\n\n .. versionadded:: 0.23.1 (support for non-MultiIndex)\n\n Parameters\n ----------\n level : int, str, or list-like, default 0\n If a string is given, must be the name of a level\n If list-like, elements must be names or indexes of levels.\n\n Returns\n -------\n Index or MultiIndex\n \"\"\"\n if not isinstance(level, (tuple, list)):\n level = [level]\n\n levnums = sorted(self._get_level_number(lev) for lev in level)[::-1]\n\n if len(level) == 0:\n return self\n if len(level) >= self.nlevels:\n raise ValueError(\"Cannot remove {} levels from an index with {} \"\n \"levels: at least one level must be \"\n \"left.\".format(len(level), self.nlevels))\n # The two checks above guarantee that here self is a MultiIndex\n\n new_levels = list(self.levels)\n new_codes = list(self.codes)\n new_names = list(self.names)\n\n for i in levnums:\n new_levels.pop(i)\n new_codes.pop(i)\n new_names.pop(i)\n\n if len(new_levels) == 1:\n\n # set nan if needed\n mask = new_codes[0] == -1\n result = new_levels[0].take(new_codes[0])\n if mask.any():\n result = result.putmask(mask, np.nan)\n\n result.name = new_names[0]\n return result\n else:\n from .multi import MultiIndex\n return MultiIndex(levels=new_levels, codes=new_codes,\n names=new_names, verify_integrity=False)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn if each value is NaN.", "output": "def _isnan(self):\n \"\"\"\n Return if each value is NaN.\n \"\"\"\n if self._can_hold_na:\n return isna(self)\n else:\n # shouldn't reach to this condition by checking hasnans beforehand\n values = np.empty(len(self), dtype=np.bool_)\n values.fill(False)\n return values" }, { "instruction": "Write or improve a Python function based on this description:\n\nExtract duplicated index elements.\n\n .. deprecated:: 0.23.0\n Use idx[idx.duplicated()].unique() instead\n\n Returns a sorted list of index elements which appear more than once in\n the index.\n\n Returns\n -------\n array-like\n List of duplicated indexes.\n\n See Also\n --------\n Index.duplicated : Return boolean array denoting duplicates.\n Index.drop_duplicates : Return Index with duplicates removed.\n\n Examples\n --------\n\n Works on different Index of types.\n\n >>> pd.Index([1, 2, 2, 3, 3, 3, 4]).get_duplicates() # doctest: +SKIP\n [2, 3]\n\n Note that for a DatetimeIndex, it does not return a list but a new\n DatetimeIndex:\n\n >>> dates = pd.to_datetime(['2018-01-01', '2018-01-02', '2018-01-03',\n ... '2018-01-03', '2018-01-04', '2018-01-04'],\n ... format='%Y-%m-%d')\n >>> pd.Index(dates).get_duplicates() # doctest: +SKIP\n DatetimeIndex(['2018-01-03', '2018-01-04'],\n dtype='datetime64[ns]', freq=None)\n\n Sorts duplicated elements even when indexes are unordered.\n\n >>> pd.Index([1, 2, 3, 2, 3, 4, 3]).get_duplicates() # doctest: +SKIP\n [2, 3]\n\n Return empty array-like structure when all elements are unique.\n\n >>> pd.Index([1, 2, 3, 4]).get_duplicates() # doctest: +SKIP\n []\n >>> dates = pd.to_datetime(['2018-01-01', '2018-01-02', '2018-01-03'],\n ... format='%Y-%m-%d')\n >>> pd.Index(dates).get_duplicates() # doctest: +SKIP\n DatetimeIndex([], dtype='datetime64[ns]', freq=None)", "output": "def get_duplicates(self):\n \"\"\"\n Extract duplicated index elements.\n\n .. deprecated:: 0.23.0\n Use idx[idx.duplicated()].unique() instead\n\n Returns a sorted list of index elements which appear more than once in\n the index.\n\n Returns\n -------\n array-like\n List of duplicated indexes.\n\n See Also\n --------\n Index.duplicated : Return boolean array denoting duplicates.\n Index.drop_duplicates : Return Index with duplicates removed.\n\n Examples\n --------\n\n Works on different Index of types.\n\n >>> pd.Index([1, 2, 2, 3, 3, 3, 4]).get_duplicates() # doctest: +SKIP\n [2, 3]\n\n Note that for a DatetimeIndex, it does not return a list but a new\n DatetimeIndex:\n\n >>> dates = pd.to_datetime(['2018-01-01', '2018-01-02', '2018-01-03',\n ... '2018-01-03', '2018-01-04', '2018-01-04'],\n ... format='%Y-%m-%d')\n >>> pd.Index(dates).get_duplicates() # doctest: +SKIP\n DatetimeIndex(['2018-01-03', '2018-01-04'],\n dtype='datetime64[ns]', freq=None)\n\n Sorts duplicated elements even when indexes are unordered.\n\n >>> pd.Index([1, 2, 3, 2, 3, 4, 3]).get_duplicates() # doctest: +SKIP\n [2, 3]\n\n Return empty array-like structure when all elements are unique.\n\n >>> pd.Index([1, 2, 3, 4]).get_duplicates() # doctest: +SKIP\n []\n >>> dates = pd.to_datetime(['2018-01-01', '2018-01-02', '2018-01-03'],\n ... format='%Y-%m-%d')\n >>> pd.Index(dates).get_duplicates() # doctest: +SKIP\n DatetimeIndex([], dtype='datetime64[ns]', freq=None)\n \"\"\"\n warnings.warn(\"'get_duplicates' is deprecated and will be removed in \"\n \"a future release. You can use \"\n \"idx[idx.duplicated()].unique() instead\",\n FutureWarning, stacklevel=2)\n\n return self[self.duplicated()].unique()" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns an index containing unique values.\n\n Parameters\n ----------\n dropna : bool\n If True, NaN values are dropped.\n\n Returns\n -------\n uniques : index", "output": "def _get_unique_index(self, dropna=False):\n \"\"\"\n Returns an index containing unique values.\n\n Parameters\n ----------\n dropna : bool\n If True, NaN values are dropped.\n\n Returns\n -------\n uniques : index\n \"\"\"\n if self.is_unique and not dropna:\n return self\n\n values = self.values\n\n if not self.is_unique:\n values = self.unique()\n\n if dropna:\n try:\n if self.hasnans:\n values = values[~isna(values)]\n except NotImplementedError:\n pass\n\n return self._shallow_copy(values)" }, { "instruction": "Write or improve a Python function based on this description:\n\nIf the result of a set operation will be self,\n return self, unless the name changes, in which\n case make a shallow copy of self.", "output": "def _get_reconciled_name_object(self, other):\n \"\"\"\n If the result of a set operation will be self,\n return self, unless the name changes, in which\n case make a shallow copy of self.\n \"\"\"\n name = get_op_result_name(self, other)\n if self.name != name:\n return self._shallow_copy(name=name)\n return self" }, { "instruction": "Write or improve a Python function based on this description:\n\nForm the union of two Index objects.\n\n Parameters\n ----------\n other : Index or array-like\n sort : bool or None, default None\n Whether to sort the resulting Index.\n\n * None : Sort the result, except when\n\n 1. `self` and `other` are equal.\n 2. `self` or `other` has length 0.\n 3. Some values in `self` or `other` cannot be compared.\n A RuntimeWarning is issued in this case.\n\n * False : do not sort the result.\n\n .. versionadded:: 0.24.0\n\n .. versionchanged:: 0.24.1\n\n Changed the default value from ``True`` to ``None``\n (without change in behaviour).\n\n Returns\n -------\n union : Index\n\n Examples\n --------\n\n >>> idx1 = pd.Index([1, 2, 3, 4])\n >>> idx2 = pd.Index([3, 4, 5, 6])\n >>> idx1.union(idx2)\n Int64Index([1, 2, 3, 4, 5, 6], dtype='int64')", "output": "def union(self, other, sort=None):\n \"\"\"\n Form the union of two Index objects.\n\n Parameters\n ----------\n other : Index or array-like\n sort : bool or None, default None\n Whether to sort the resulting Index.\n\n * None : Sort the result, except when\n\n 1. `self` and `other` are equal.\n 2. `self` or `other` has length 0.\n 3. Some values in `self` or `other` cannot be compared.\n A RuntimeWarning is issued in this case.\n\n * False : do not sort the result.\n\n .. versionadded:: 0.24.0\n\n .. versionchanged:: 0.24.1\n\n Changed the default value from ``True`` to ``None``\n (without change in behaviour).\n\n Returns\n -------\n union : Index\n\n Examples\n --------\n\n >>> idx1 = pd.Index([1, 2, 3, 4])\n >>> idx2 = pd.Index([3, 4, 5, 6])\n >>> idx1.union(idx2)\n Int64Index([1, 2, 3, 4, 5, 6], dtype='int64')\n \"\"\"\n self._validate_sort_keyword(sort)\n self._assert_can_do_setop(other)\n other = ensure_index(other)\n\n if len(other) == 0 or self.equals(other):\n return self._get_reconciled_name_object(other)\n\n if len(self) == 0:\n return other._get_reconciled_name_object(self)\n\n # TODO: is_dtype_union_equal is a hack around\n # 1. buggy set ops with duplicates (GH #13432)\n # 2. CategoricalIndex lacking setops (GH #10186)\n # Once those are fixed, this workaround can be removed\n if not is_dtype_union_equal(self.dtype, other.dtype):\n this = self.astype('O')\n other = other.astype('O')\n return this.union(other, sort=sort)\n\n # TODO(EA): setops-refactor, clean all this up\n if is_period_dtype(self) or is_datetime64tz_dtype(self):\n lvals = self._ndarray_values\n else:\n lvals = self._values\n if is_period_dtype(other) or is_datetime64tz_dtype(other):\n rvals = other._ndarray_values\n else:\n rvals = other._values\n\n if sort is None and self.is_monotonic and other.is_monotonic:\n try:\n result = self._outer_indexer(lvals, rvals)[0]\n except TypeError:\n # incomparable objects\n result = list(lvals)\n\n # worth making this faster? a very unusual case\n value_set = set(lvals)\n result.extend([x for x in rvals if x not in value_set])\n else:\n indexer = self.get_indexer(other)\n indexer, = (indexer == -1).nonzero()\n\n if len(indexer) > 0:\n other_diff = algos.take_nd(rvals, indexer,\n allow_fill=False)\n result = _concat._concat_compat((lvals, other_diff))\n\n else:\n result = lvals\n\n if sort is None:\n try:\n result = sorting.safe_sort(result)\n except TypeError as e:\n warnings.warn(\"{}, sort order is undefined for \"\n \"incomparable objects\".format(e),\n RuntimeWarning, stacklevel=3)\n\n # for subclasses\n return self._wrap_setop_result(other, result)" }, { "instruction": "Write or improve a Python function based on this description:\n\nForm the intersection of two Index objects.\n\n This returns a new Index with elements common to the index and `other`.\n\n Parameters\n ----------\n other : Index or array-like\n sort : False or None, default False\n Whether to sort the resulting index.\n\n * False : do not sort the result.\n * None : sort the result, except when `self` and `other` are equal\n or when the values cannot be compared.\n\n .. versionadded:: 0.24.0\n\n .. versionchanged:: 0.24.1\n\n Changed the default from ``True`` to ``False``, to match\n the behaviour of 0.23.4 and earlier.\n\n Returns\n -------\n intersection : Index\n\n Examples\n --------\n\n >>> idx1 = pd.Index([1, 2, 3, 4])\n >>> idx2 = pd.Index([3, 4, 5, 6])\n >>> idx1.intersection(idx2)\n Int64Index([3, 4], dtype='int64')", "output": "def intersection(self, other, sort=False):\n \"\"\"\n Form the intersection of two Index objects.\n\n This returns a new Index with elements common to the index and `other`.\n\n Parameters\n ----------\n other : Index or array-like\n sort : False or None, default False\n Whether to sort the resulting index.\n\n * False : do not sort the result.\n * None : sort the result, except when `self` and `other` are equal\n or when the values cannot be compared.\n\n .. versionadded:: 0.24.0\n\n .. versionchanged:: 0.24.1\n\n Changed the default from ``True`` to ``False``, to match\n the behaviour of 0.23.4 and earlier.\n\n Returns\n -------\n intersection : Index\n\n Examples\n --------\n\n >>> idx1 = pd.Index([1, 2, 3, 4])\n >>> idx2 = pd.Index([3, 4, 5, 6])\n >>> idx1.intersection(idx2)\n Int64Index([3, 4], dtype='int64')\n \"\"\"\n self._validate_sort_keyword(sort)\n self._assert_can_do_setop(other)\n other = ensure_index(other)\n\n if self.equals(other):\n return self._get_reconciled_name_object(other)\n\n if not is_dtype_equal(self.dtype, other.dtype):\n this = self.astype('O')\n other = other.astype('O')\n return this.intersection(other, sort=sort)\n\n # TODO(EA): setops-refactor, clean all this up\n if is_period_dtype(self):\n lvals = self._ndarray_values\n else:\n lvals = self._values\n if is_period_dtype(other):\n rvals = other._ndarray_values\n else:\n rvals = other._values\n\n if self.is_monotonic and other.is_monotonic:\n try:\n result = self._inner_indexer(lvals, rvals)[0]\n return self._wrap_setop_result(other, result)\n except TypeError:\n pass\n\n try:\n indexer = Index(rvals).get_indexer(lvals)\n indexer = indexer.take((indexer != -1).nonzero()[0])\n except Exception:\n # duplicates\n indexer = algos.unique1d(\n Index(rvals).get_indexer_non_unique(lvals)[0])\n indexer = indexer[indexer != -1]\n\n taken = other.take(indexer)\n\n if sort is None:\n taken = sorting.safe_sort(taken.values)\n if self.name != other.name:\n name = None\n else:\n name = self.name\n return self._shallow_copy(taken, name=name)\n\n if self.name != other.name:\n taken.name = None\n\n return taken" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn a new Index with elements from the index that are not in\n `other`.\n\n This is the set difference of two Index objects.\n\n Parameters\n ----------\n other : Index or array-like\n sort : False or None, default None\n Whether to sort the resulting index. By default, the\n values are attempted to be sorted, but any TypeError from\n incomparable elements is caught by pandas.\n\n * None : Attempt to sort the result, but catch any TypeErrors\n from comparing incomparable elements.\n * False : Do not sort the result.\n\n .. versionadded:: 0.24.0\n\n .. versionchanged:: 0.24.1\n\n Changed the default value from ``True`` to ``None``\n (without change in behaviour).\n\n Returns\n -------\n difference : Index\n\n Examples\n --------\n\n >>> idx1 = pd.Index([2, 1, 3, 4])\n >>> idx2 = pd.Index([3, 4, 5, 6])\n >>> idx1.difference(idx2)\n Int64Index([1, 2], dtype='int64')\n >>> idx1.difference(idx2, sort=False)\n Int64Index([2, 1], dtype='int64')", "output": "def difference(self, other, sort=None):\n \"\"\"\n Return a new Index with elements from the index that are not in\n `other`.\n\n This is the set difference of two Index objects.\n\n Parameters\n ----------\n other : Index or array-like\n sort : False or None, default None\n Whether to sort the resulting index. By default, the\n values are attempted to be sorted, but any TypeError from\n incomparable elements is caught by pandas.\n\n * None : Attempt to sort the result, but catch any TypeErrors\n from comparing incomparable elements.\n * False : Do not sort the result.\n\n .. versionadded:: 0.24.0\n\n .. versionchanged:: 0.24.1\n\n Changed the default value from ``True`` to ``None``\n (without change in behaviour).\n\n Returns\n -------\n difference : Index\n\n Examples\n --------\n\n >>> idx1 = pd.Index([2, 1, 3, 4])\n >>> idx2 = pd.Index([3, 4, 5, 6])\n >>> idx1.difference(idx2)\n Int64Index([1, 2], dtype='int64')\n >>> idx1.difference(idx2, sort=False)\n Int64Index([2, 1], dtype='int64')\n \"\"\"\n self._validate_sort_keyword(sort)\n self._assert_can_do_setop(other)\n\n if self.equals(other):\n # pass an empty np.ndarray with the appropriate dtype\n return self._shallow_copy(self._data[:0])\n\n other, result_name = self._convert_can_do_setop(other)\n\n this = self._get_unique_index()\n\n indexer = this.get_indexer(other)\n indexer = indexer.take((indexer != -1).nonzero()[0])\n\n label_diff = np.setdiff1d(np.arange(this.size), indexer,\n assume_unique=True)\n the_diff = this.values.take(label_diff)\n if sort is None:\n try:\n the_diff = sorting.safe_sort(the_diff)\n except TypeError:\n pass\n\n return this._shallow_copy(the_diff, name=result_name, freq=None)" }, { "instruction": "Write or improve a Python function based on this description:\n\nCompute the symmetric difference of two Index objects.\n\n Parameters\n ----------\n other : Index or array-like\n result_name : str\n sort : False or None, default None\n Whether to sort the resulting index. By default, the\n values are attempted to be sorted, but any TypeError from\n incomparable elements is caught by pandas.\n\n * None : Attempt to sort the result, but catch any TypeErrors\n from comparing incomparable elements.\n * False : Do not sort the result.\n\n .. versionadded:: 0.24.0\n\n .. versionchanged:: 0.24.1\n\n Changed the default value from ``True`` to ``None``\n (without change in behaviour).\n\n Returns\n -------\n symmetric_difference : Index\n\n Notes\n -----\n ``symmetric_difference`` contains elements that appear in either\n ``idx1`` or ``idx2`` but not both. Equivalent to the Index created by\n ``idx1.difference(idx2) | idx2.difference(idx1)`` with duplicates\n dropped.\n\n Examples\n --------\n >>> idx1 = pd.Index([1, 2, 3, 4])\n >>> idx2 = pd.Index([2, 3, 4, 5])\n >>> idx1.symmetric_difference(idx2)\n Int64Index([1, 5], dtype='int64')\n\n You can also use the ``^`` operator:\n\n >>> idx1 ^ idx2\n Int64Index([1, 5], dtype='int64')", "output": "def symmetric_difference(self, other, result_name=None, sort=None):\n \"\"\"\n Compute the symmetric difference of two Index objects.\n\n Parameters\n ----------\n other : Index or array-like\n result_name : str\n sort : False or None, default None\n Whether to sort the resulting index. By default, the\n values are attempted to be sorted, but any TypeError from\n incomparable elements is caught by pandas.\n\n * None : Attempt to sort the result, but catch any TypeErrors\n from comparing incomparable elements.\n * False : Do not sort the result.\n\n .. versionadded:: 0.24.0\n\n .. versionchanged:: 0.24.1\n\n Changed the default value from ``True`` to ``None``\n (without change in behaviour).\n\n Returns\n -------\n symmetric_difference : Index\n\n Notes\n -----\n ``symmetric_difference`` contains elements that appear in either\n ``idx1`` or ``idx2`` but not both. Equivalent to the Index created by\n ``idx1.difference(idx2) | idx2.difference(idx1)`` with duplicates\n dropped.\n\n Examples\n --------\n >>> idx1 = pd.Index([1, 2, 3, 4])\n >>> idx2 = pd.Index([2, 3, 4, 5])\n >>> idx1.symmetric_difference(idx2)\n Int64Index([1, 5], dtype='int64')\n\n You can also use the ``^`` operator:\n\n >>> idx1 ^ idx2\n Int64Index([1, 5], dtype='int64')\n \"\"\"\n self._validate_sort_keyword(sort)\n self._assert_can_do_setop(other)\n other, result_name_update = self._convert_can_do_setop(other)\n if result_name is None:\n result_name = result_name_update\n\n this = self._get_unique_index()\n other = other._get_unique_index()\n indexer = this.get_indexer(other)\n\n # {this} minus {other}\n common_indexer = indexer.take((indexer != -1).nonzero()[0])\n left_indexer = np.setdiff1d(np.arange(this.size), common_indexer,\n assume_unique=True)\n left_diff = this.values.take(left_indexer)\n\n # {other} minus {this}\n right_indexer = (indexer == -1).nonzero()[0]\n right_diff = other.values.take(right_indexer)\n\n the_diff = _concat._concat_compat([left_diff, right_diff])\n if sort is None:\n try:\n the_diff = sorting.safe_sort(the_diff)\n except TypeError:\n pass\n\n attribs = self._get_attributes_dict()\n attribs['name'] = result_name\n if 'freq' in attribs:\n attribs['freq'] = None\n return self._shallow_copy_with_infer(the_diff, **attribs)" }, { "instruction": "Write or improve a Python function based on this description:\n\nFallback pad/backfill get_indexer that works for monotonic decreasing\n indexes and non-monotonic targets.", "output": "def _get_fill_indexer_searchsorted(self, target, method, limit=None):\n \"\"\"\n Fallback pad/backfill get_indexer that works for monotonic decreasing\n indexes and non-monotonic targets.\n \"\"\"\n if limit is not None:\n raise ValueError('limit argument for %r method only well-defined '\n 'if index and target are monotonic' % method)\n\n side = 'left' if method == 'pad' else 'right'\n\n # find exact matches first (this simplifies the algorithm)\n indexer = self.get_indexer(target)\n nonexact = (indexer == -1)\n indexer[nonexact] = self._searchsorted_monotonic(target[nonexact],\n side)\n if side == 'left':\n # searchsorted returns \"indices into a sorted array such that,\n # if the corresponding elements in v were inserted before the\n # indices, the order of a would be preserved\".\n # Thus, we need to subtract 1 to find values to the left.\n indexer[nonexact] -= 1\n # This also mapped not found values (values of 0 from\n # np.searchsorted) to -1, which conveniently is also our\n # sentinel for missing values\n else:\n # Mark indices to the right of the largest value as not found\n indexer[indexer == len(self)] = -1\n return indexer" }, { "instruction": "Write or improve a Python function based on this description:\n\nGet the indexer for the nearest index labels; requires an index with\n values that can be subtracted from each other (e.g., not strings or\n tuples).", "output": "def _get_nearest_indexer(self, target, limit, tolerance):\n \"\"\"\n Get the indexer for the nearest index labels; requires an index with\n values that can be subtracted from each other (e.g., not strings or\n tuples).\n \"\"\"\n left_indexer = self.get_indexer(target, 'pad', limit=limit)\n right_indexer = self.get_indexer(target, 'backfill', limit=limit)\n\n target = np.asarray(target)\n left_distances = abs(self.values[left_indexer] - target)\n right_distances = abs(self.values[right_indexer] - target)\n\n op = operator.lt if self.is_monotonic_increasing else operator.le\n indexer = np.where(op(left_distances, right_distances) |\n (right_indexer == -1), left_indexer, right_indexer)\n if tolerance is not None:\n indexer = self._filter_indexer_tolerance(target, indexer,\n tolerance)\n return indexer" }, { "instruction": "Write or improve a Python function based on this description:\n\nParameters\n ----------\n keyarr : list-like\n Indexer to convert.\n\n Returns\n -------\n indexer : numpy.ndarray or None\n Return an ndarray or None if cannot convert.\n keyarr : numpy.ndarray\n Return tuple-safe keys.", "output": "def _convert_listlike_indexer(self, keyarr, kind=None):\n \"\"\"\n Parameters\n ----------\n keyarr : list-like\n Indexer to convert.\n\n Returns\n -------\n indexer : numpy.ndarray or None\n Return an ndarray or None if cannot convert.\n keyarr : numpy.ndarray\n Return tuple-safe keys.\n \"\"\"\n if isinstance(keyarr, Index):\n keyarr = self._convert_index_indexer(keyarr)\n else:\n keyarr = self._convert_arr_indexer(keyarr)\n\n indexer = self._convert_list_indexer(keyarr, kind=kind)\n return indexer, keyarr" }, { "instruction": "Write or improve a Python function based on this description:\n\nConsistent invalid indexer message.", "output": "def _invalid_indexer(self, form, key):\n \"\"\"\n Consistent invalid indexer message.\n \"\"\"\n raise TypeError(\"cannot do {form} indexing on {klass} with these \"\n \"indexers [{key}] of {kind}\".format(\n form=form, klass=type(self), key=key,\n kind=type(key)))" }, { "instruction": "Write or improve a Python function based on this description:\n\nCreate index with target's values (move/add/delete values\n as necessary).\n\n Parameters\n ----------\n target : an iterable\n\n Returns\n -------\n new_index : pd.Index\n Resulting index.\n indexer : np.ndarray or None\n Indices of output values in original index.", "output": "def reindex(self, target, method=None, level=None, limit=None,\n tolerance=None):\n \"\"\"\n Create index with target's values (move/add/delete values\n as necessary).\n\n Parameters\n ----------\n target : an iterable\n\n Returns\n -------\n new_index : pd.Index\n Resulting index.\n indexer : np.ndarray or None\n Indices of output values in original index.\n \"\"\"\n # GH6552: preserve names when reindexing to non-named target\n # (i.e. neither Index nor Series).\n preserve_names = not hasattr(target, 'name')\n\n # GH7774: preserve dtype/tz if target is empty and not an Index.\n target = _ensure_has_len(target) # target may be an iterator\n\n if not isinstance(target, Index) and len(target) == 0:\n attrs = self._get_attributes_dict()\n attrs.pop('freq', None) # don't preserve freq\n values = self._data[:0] # appropriately-dtyped empty array\n target = self._simple_new(values, dtype=self.dtype, **attrs)\n else:\n target = ensure_index(target)\n\n if level is not None:\n if method is not None:\n raise TypeError('Fill method not supported if level passed')\n _, indexer, _ = self._join_level(target, level, how='right',\n return_indexers=True)\n else:\n if self.equals(target):\n indexer = None\n else:\n\n if self.is_unique:\n indexer = self.get_indexer(target, method=method,\n limit=limit,\n tolerance=tolerance)\n else:\n if method is not None or limit is not None:\n raise ValueError(\"cannot reindex a non-unique index \"\n \"with a method or limit\")\n indexer, missing = self.get_indexer_non_unique(target)\n\n if preserve_names and target.nlevels == 1 and target.name != self.name:\n target = target.copy()\n target.name = self.name\n\n return target, indexer" }, { "instruction": "Write or improve a Python function based on this description:\n\nCreate a new index with target's values (move/add/delete values as\n necessary) use with non-unique Index and a possibly non-unique target.\n\n Parameters\n ----------\n target : an iterable\n\n Returns\n -------\n new_index : pd.Index\n Resulting index.\n indexer : np.ndarray or None\n Indices of output values in original index.", "output": "def _reindex_non_unique(self, target):\n \"\"\"\n Create a new index with target's values (move/add/delete values as\n necessary) use with non-unique Index and a possibly non-unique target.\n\n Parameters\n ----------\n target : an iterable\n\n Returns\n -------\n new_index : pd.Index\n Resulting index.\n indexer : np.ndarray or None\n Indices of output values in original index.\n\n \"\"\"\n\n target = ensure_index(target)\n indexer, missing = self.get_indexer_non_unique(target)\n check = indexer != -1\n new_labels = self.take(indexer[check])\n new_indexer = None\n\n if len(missing):\n length = np.arange(len(indexer))\n\n missing = ensure_platform_int(missing)\n missing_labels = target.take(missing)\n missing_indexer = ensure_int64(length[~check])\n cur_labels = self.take(indexer[check]).values\n cur_indexer = ensure_int64(length[check])\n\n new_labels = np.empty(tuple([len(indexer)]), dtype=object)\n new_labels[cur_indexer] = cur_labels\n new_labels[missing_indexer] = missing_labels\n\n # a unique indexer\n if target.is_unique:\n\n # see GH5553, make sure we use the right indexer\n new_indexer = np.arange(len(indexer))\n new_indexer[cur_indexer] = np.arange(len(cur_labels))\n new_indexer[missing_indexer] = -1\n\n # we have a non_unique selector, need to use the original\n # indexer here\n else:\n\n # need to retake to have the same size as the indexer\n indexer[~check] = -1\n\n # reset the new indexer to account for the new size\n new_indexer = np.arange(len(self.take(indexer)))\n new_indexer[~check] = -1\n\n new_index = self._shallow_copy_with_infer(new_labels, freq=None)\n return new_index, indexer, new_indexer" }, { "instruction": "Write or improve a Python function based on this description:\n\nThe join method *only* affects the level of the resulting\n MultiIndex. Otherwise it just exactly aligns the Index data to the\n labels of the level in the MultiIndex.\n\n If ```keep_order == True```, the order of the data indexed by the\n MultiIndex will not be changed; otherwise, it will tie out\n with `other`.", "output": "def _join_level(self, other, level, how='left', return_indexers=False,\n keep_order=True):\n \"\"\"\n The join method *only* affects the level of the resulting\n MultiIndex. Otherwise it just exactly aligns the Index data to the\n labels of the level in the MultiIndex.\n\n If ```keep_order == True```, the order of the data indexed by the\n MultiIndex will not be changed; otherwise, it will tie out\n with `other`.\n \"\"\"\n from .multi import MultiIndex\n\n def _get_leaf_sorter(labels):\n \"\"\"\n Returns sorter for the inner most level while preserving the\n order of higher levels.\n \"\"\"\n if labels[0].size == 0:\n return np.empty(0, dtype='int64')\n\n if len(labels) == 1:\n lab = ensure_int64(labels[0])\n sorter, _ = libalgos.groupsort_indexer(lab, 1 + lab.max())\n return sorter\n\n # find indexers of beginning of each set of\n # same-key labels w.r.t all but last level\n tic = labels[0][:-1] != labels[0][1:]\n for lab in labels[1:-1]:\n tic |= lab[:-1] != lab[1:]\n\n starts = np.hstack(([True], tic, [True])).nonzero()[0]\n lab = ensure_int64(labels[-1])\n return lib.get_level_sorter(lab, ensure_int64(starts))\n\n if isinstance(self, MultiIndex) and isinstance(other, MultiIndex):\n raise TypeError('Join on level between two MultiIndex objects '\n 'is ambiguous')\n\n left, right = self, other\n\n flip_order = not isinstance(self, MultiIndex)\n if flip_order:\n left, right = right, left\n how = {'right': 'left', 'left': 'right'}.get(how, how)\n\n level = left._get_level_number(level)\n old_level = left.levels[level]\n\n if not right.is_unique:\n raise NotImplementedError('Index._join_level on non-unique index '\n 'is not implemented')\n\n new_level, left_lev_indexer, right_lev_indexer = \\\n old_level.join(right, how=how, return_indexers=True)\n\n if left_lev_indexer is None:\n if keep_order or len(left) == 0:\n left_indexer = None\n join_index = left\n else: # sort the leaves\n left_indexer = _get_leaf_sorter(left.codes[:level + 1])\n join_index = left[left_indexer]\n\n else:\n left_lev_indexer = ensure_int64(left_lev_indexer)\n rev_indexer = lib.get_reverse_indexer(left_lev_indexer,\n len(old_level))\n\n new_lev_codes = algos.take_nd(rev_indexer, left.codes[level],\n allow_fill=False)\n\n new_codes = list(left.codes)\n new_codes[level] = new_lev_codes\n\n new_levels = list(left.levels)\n new_levels[level] = new_level\n\n if keep_order: # just drop missing values. o.w. keep order\n left_indexer = np.arange(len(left), dtype=np.intp)\n mask = new_lev_codes != -1\n if not mask.all():\n new_codes = [lab[mask] for lab in new_codes]\n left_indexer = left_indexer[mask]\n\n else: # tie out the order with other\n if level == 0: # outer most level, take the fast route\n ngroups = 1 + new_lev_codes.max()\n left_indexer, counts = libalgos.groupsort_indexer(\n new_lev_codes, ngroups)\n\n # missing values are placed first; drop them!\n left_indexer = left_indexer[counts[0]:]\n new_codes = [lab[left_indexer] for lab in new_codes]\n\n else: # sort the leaves\n mask = new_lev_codes != -1\n mask_all = mask.all()\n if not mask_all:\n new_codes = [lab[mask] for lab in new_codes]\n\n left_indexer = _get_leaf_sorter(new_codes[:level + 1])\n new_codes = [lab[left_indexer] for lab in new_codes]\n\n # left_indexers are w.r.t masked frame.\n # reverse to original frame!\n if not mask_all:\n left_indexer = mask.nonzero()[0][left_indexer]\n\n join_index = MultiIndex(levels=new_levels, codes=new_codes,\n names=left.names, verify_integrity=False)\n\n if right_lev_indexer is not None:\n right_indexer = algos.take_nd(right_lev_indexer,\n join_index.codes[level],\n allow_fill=False)\n else:\n right_indexer = join_index.codes[level]\n\n if flip_order:\n left_indexer, right_indexer = right_indexer, left_indexer\n\n if return_indexers:\n left_indexer = (None if left_indexer is None\n else ensure_platform_int(left_indexer))\n right_indexer = (None if right_indexer is None\n else ensure_platform_int(right_indexer))\n return join_index, left_indexer, right_indexer\n else:\n return join_index" }, { "instruction": "Write or improve a Python function based on this description:\n\nAttempt to convert an array of data into an integer index.\n\n Parameters\n ----------\n data : The data to convert.\n copy : Whether to copy the data or not.\n name : The name of the index returned.\n\n Returns\n -------\n int_index : data converted to either an Int64Index or a\n UInt64Index\n\n Raises\n ------\n ValueError if the conversion was not successful.", "output": "def _try_convert_to_int_index(cls, data, copy, name, dtype):\n \"\"\"\n Attempt to convert an array of data into an integer index.\n\n Parameters\n ----------\n data : The data to convert.\n copy : Whether to copy the data or not.\n name : The name of the index returned.\n\n Returns\n -------\n int_index : data converted to either an Int64Index or a\n UInt64Index\n\n Raises\n ------\n ValueError if the conversion was not successful.\n \"\"\"\n\n from .numeric import Int64Index, UInt64Index\n if not is_unsigned_integer_dtype(dtype):\n # skip int64 conversion attempt if uint-like dtype is passed, as\n # this could return Int64Index when UInt64Index is what's desrired\n try:\n res = data.astype('i8', copy=False)\n if (res == data).all():\n return Int64Index(res, copy=copy, name=name)\n except (OverflowError, TypeError, ValueError):\n pass\n\n # Conversion to int64 failed (possibly due to overflow) or was skipped,\n # so let's try now with uint64.\n try:\n res = data.astype('u8', copy=False)\n if (res == data).all():\n return UInt64Index(res, copy=copy, name=name)\n except (OverflowError, TypeError, ValueError):\n pass\n\n raise ValueError" }, { "instruction": "Write or improve a Python function based on this description:\n\nCoerces data to ndarray.\n\n Converts other iterables to list first and then to array.\n Does not touch ndarrays.\n\n Raises\n ------\n TypeError\n When the data passed in is a scalar.", "output": "def _coerce_to_ndarray(cls, data):\n \"\"\"\n Coerces data to ndarray.\n\n Converts other iterables to list first and then to array.\n Does not touch ndarrays.\n\n Raises\n ------\n TypeError\n When the data passed in is a scalar.\n \"\"\"\n\n if not isinstance(data, (np.ndarray, Index)):\n if data is None or is_scalar(data):\n cls._scalar_data_error(data)\n\n # other iterable of some kind\n if not isinstance(data, (ABCSeries, list, tuple)):\n data = list(data)\n data = np.asarray(data)\n return data" }, { "instruction": "Write or improve a Python function based on this description:\n\nWe need to coerce a scalar to a compat for our index type.\n\n Parameters\n ----------\n item : scalar item to coerce", "output": "def _coerce_scalar_to_index(self, item):\n \"\"\"\n We need to coerce a scalar to a compat for our index type.\n\n Parameters\n ----------\n item : scalar item to coerce\n \"\"\"\n dtype = self.dtype\n\n if self._is_numeric_dtype and isna(item):\n # We can't coerce to the numeric dtype of \"self\" (unless\n # it's float) if there are NaN values in our output.\n dtype = None\n\n return Index([item], dtype=dtype, **self._get_attributes_dict())" }, { "instruction": "Write or improve a Python function based on this description:\n\nCheck value is valid for scalar op.", "output": "def _assert_can_do_op(self, value):\n \"\"\"\n Check value is valid for scalar op.\n \"\"\"\n if not is_scalar(value):\n msg = \"'value' must be a scalar, passed: {0}\"\n raise TypeError(msg.format(type(value).__name__))" }, { "instruction": "Write or improve a Python function based on this description:\n\nFaster check for ``name in self`` when we know `name` is a Python\n identifier (e.g. in NDFrame.__getattr__, which hits this to support\n . key lookup). For indexes that can't hold identifiers (everything\n but object & categorical) we just return False.\n\n https://github.com/pandas-dev/pandas/issues/19764", "output": "def _can_hold_identifiers_and_holds_name(self, name):\n \"\"\"\n Faster check for ``name in self`` when we know `name` is a Python\n identifier (e.g. in NDFrame.__getattr__, which hits this to support\n . key lookup). For indexes that can't hold identifiers (everything\n but object & categorical) we just return False.\n\n https://github.com/pandas-dev/pandas/issues/19764\n \"\"\"\n if self.is_object() or self.is_categorical():\n return name in self\n return False" }, { "instruction": "Write or improve a Python function based on this description:\n\nAppend a collection of Index options together.\n\n Parameters\n ----------\n other : Index or list/tuple of indices\n\n Returns\n -------\n appended : Index", "output": "def append(self, other):\n \"\"\"\n Append a collection of Index options together.\n\n Parameters\n ----------\n other : Index or list/tuple of indices\n\n Returns\n -------\n appended : Index\n \"\"\"\n\n to_concat = [self]\n\n if isinstance(other, (list, tuple)):\n to_concat = to_concat + list(other)\n else:\n to_concat.append(other)\n\n for obj in to_concat:\n if not isinstance(obj, Index):\n raise TypeError('all inputs must be Index')\n\n names = {obj.name for obj in to_concat}\n name = None if len(names) > 1 else self.name\n\n return self._concat(to_concat, name)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn a new Index of the values set with the mask.\n\n See Also\n --------\n numpy.ndarray.putmask", "output": "def putmask(self, mask, value):\n \"\"\"\n Return a new Index of the values set with the mask.\n\n See Also\n --------\n numpy.ndarray.putmask\n \"\"\"\n values = self.values.copy()\n try:\n np.putmask(values, mask, self._convert_for_op(value))\n return self._shallow_copy(values)\n except (ValueError, TypeError) as err:\n if is_object_dtype(self):\n raise err\n\n # coerces to object\n return self.astype(object).putmask(mask, value)" }, { "instruction": "Write or improve a Python function based on this description:\n\nDetermine if two Index objects contain the same elements.", "output": "def equals(self, other):\n \"\"\"\n Determine if two Index objects contain the same elements.\n \"\"\"\n if self.is_(other):\n return True\n\n if not isinstance(other, Index):\n return False\n\n if is_object_dtype(self) and not is_object_dtype(other):\n # if other is not object, use other's logic for coercion\n return other.equals(self)\n\n try:\n return array_equivalent(com.values_from_object(self),\n com.values_from_object(other))\n except Exception:\n return False" }, { "instruction": "Write or improve a Python function based on this description:\n\nSimilar to equals, but check that other comparable attributes are\n also equal.", "output": "def identical(self, other):\n \"\"\"\n Similar to equals, but check that other comparable attributes are\n also equal.\n \"\"\"\n return (self.equals(other) and\n all((getattr(self, c, None) == getattr(other, c, None)\n for c in self._comparables)) and\n type(self) == type(other))" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn the label from the index, or, if not present, the previous one.\n\n Assuming that the index is sorted, return the passed index label if it\n is in the index, or return the previous index label if the passed one\n is not in the index.\n\n Parameters\n ----------\n label : object\n The label up to which the method returns the latest index label.\n\n Returns\n -------\n object\n The passed label if it is in the index. The previous label if the\n passed label is not in the sorted index or `NaN` if there is no\n such label.\n\n See Also\n --------\n Series.asof : Return the latest value in a Series up to the\n passed index.\n merge_asof : Perform an asof merge (similar to left join but it\n matches on nearest key rather than equal key).\n Index.get_loc : An `asof` is a thin wrapper around `get_loc`\n with method='pad'.\n\n Examples\n --------\n `Index.asof` returns the latest index label up to the passed label.\n\n >>> idx = pd.Index(['2013-12-31', '2014-01-02', '2014-01-03'])\n >>> idx.asof('2014-01-01')\n '2013-12-31'\n\n If the label is in the index, the method returns the passed label.\n\n >>> idx.asof('2014-01-02')\n '2014-01-02'\n\n If all of the labels in the index are later than the passed label,\n NaN is returned.\n\n >>> idx.asof('1999-01-02')\n nan\n\n If the index is not sorted, an error is raised.\n\n >>> idx_not_sorted = pd.Index(['2013-12-31', '2015-01-02',\n ... '2014-01-03'])\n >>> idx_not_sorted.asof('2013-12-31')\n Traceback (most recent call last):\n ValueError: index must be monotonic increasing or decreasing", "output": "def asof(self, label):\n \"\"\"\n Return the label from the index, or, if not present, the previous one.\n\n Assuming that the index is sorted, return the passed index label if it\n is in the index, or return the previous index label if the passed one\n is not in the index.\n\n Parameters\n ----------\n label : object\n The label up to which the method returns the latest index label.\n\n Returns\n -------\n object\n The passed label if it is in the index. The previous label if the\n passed label is not in the sorted index or `NaN` if there is no\n such label.\n\n See Also\n --------\n Series.asof : Return the latest value in a Series up to the\n passed index.\n merge_asof : Perform an asof merge (similar to left join but it\n matches on nearest key rather than equal key).\n Index.get_loc : An `asof` is a thin wrapper around `get_loc`\n with method='pad'.\n\n Examples\n --------\n `Index.asof` returns the latest index label up to the passed label.\n\n >>> idx = pd.Index(['2013-12-31', '2014-01-02', '2014-01-03'])\n >>> idx.asof('2014-01-01')\n '2013-12-31'\n\n If the label is in the index, the method returns the passed label.\n\n >>> idx.asof('2014-01-02')\n '2014-01-02'\n\n If all of the labels in the index are later than the passed label,\n NaN is returned.\n\n >>> idx.asof('1999-01-02')\n nan\n\n If the index is not sorted, an error is raised.\n\n >>> idx_not_sorted = pd.Index(['2013-12-31', '2015-01-02',\n ... '2014-01-03'])\n >>> idx_not_sorted.asof('2013-12-31')\n Traceback (most recent call last):\n ValueError: index must be monotonic increasing or decreasing\n \"\"\"\n try:\n loc = self.get_loc(label, method='pad')\n except KeyError:\n return self._na_value\n else:\n if isinstance(loc, slice):\n loc = loc.indices(len(self))[-1]\n return self[loc]" }, { "instruction": "Write or improve a Python function based on this description:\n\nFind the locations (indices) of the labels from the index for\n every entry in the `where` argument.\n\n As in the `asof` function, if the label (a particular entry in\n `where`) is not in the index, the latest index label upto the\n passed label is chosen and its index returned.\n\n If all of the labels in the index are later than a label in `where`,\n -1 is returned.\n\n `mask` is used to ignore NA values in the index during calculation.\n\n Parameters\n ----------\n where : Index\n An Index consisting of an array of timestamps.\n mask : array-like\n Array of booleans denoting where values in the original\n data are not NA.\n\n Returns\n -------\n numpy.ndarray\n An array of locations (indices) of the labels from the Index\n which correspond to the return values of the `asof` function\n for every element in `where`.", "output": "def asof_locs(self, where, mask):\n \"\"\"\n Find the locations (indices) of the labels from the index for\n every entry in the `where` argument.\n\n As in the `asof` function, if the label (a particular entry in\n `where`) is not in the index, the latest index label upto the\n passed label is chosen and its index returned.\n\n If all of the labels in the index are later than a label in `where`,\n -1 is returned.\n\n `mask` is used to ignore NA values in the index during calculation.\n\n Parameters\n ----------\n where : Index\n An Index consisting of an array of timestamps.\n mask : array-like\n Array of booleans denoting where values in the original\n data are not NA.\n\n Returns\n -------\n numpy.ndarray\n An array of locations (indices) of the labels from the Index\n which correspond to the return values of the `asof` function\n for every element in `where`.\n \"\"\"\n locs = self.values[mask].searchsorted(where.values, side='right')\n locs = np.where(locs > 0, locs - 1, 0)\n\n result = np.arange(len(self))[mask].take(locs)\n\n first = mask.argmax()\n result[(locs == 0) & (where.values < self.values[first])] = -1\n\n return result" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn a sorted copy of the index.\n\n Return a sorted copy of the index, and optionally return the indices\n that sorted the index itself.\n\n Parameters\n ----------\n return_indexer : bool, default False\n Should the indices that would sort the index be returned.\n ascending : bool, default True\n Should the index values be sorted in an ascending order.\n\n Returns\n -------\n sorted_index : pandas.Index\n Sorted copy of the index.\n indexer : numpy.ndarray, optional\n The indices that the index itself was sorted by.\n\n See Also\n --------\n Series.sort_values : Sort values of a Series.\n DataFrame.sort_values : Sort values in a DataFrame.\n\n Examples\n --------\n >>> idx = pd.Index([10, 100, 1, 1000])\n >>> idx\n Int64Index([10, 100, 1, 1000], dtype='int64')\n\n Sort values in ascending order (default behavior).\n\n >>> idx.sort_values()\n Int64Index([1, 10, 100, 1000], dtype='int64')\n\n Sort values in descending order, and also get the indices `idx` was\n sorted by.\n\n >>> idx.sort_values(ascending=False, return_indexer=True)\n (Int64Index([1000, 100, 10, 1], dtype='int64'), array([3, 1, 0, 2]))", "output": "def sort_values(self, return_indexer=False, ascending=True):\n \"\"\"\n Return a sorted copy of the index.\n\n Return a sorted copy of the index, and optionally return the indices\n that sorted the index itself.\n\n Parameters\n ----------\n return_indexer : bool, default False\n Should the indices that would sort the index be returned.\n ascending : bool, default True\n Should the index values be sorted in an ascending order.\n\n Returns\n -------\n sorted_index : pandas.Index\n Sorted copy of the index.\n indexer : numpy.ndarray, optional\n The indices that the index itself was sorted by.\n\n See Also\n --------\n Series.sort_values : Sort values of a Series.\n DataFrame.sort_values : Sort values in a DataFrame.\n\n Examples\n --------\n >>> idx = pd.Index([10, 100, 1, 1000])\n >>> idx\n Int64Index([10, 100, 1, 1000], dtype='int64')\n\n Sort values in ascending order (default behavior).\n\n >>> idx.sort_values()\n Int64Index([1, 10, 100, 1000], dtype='int64')\n\n Sort values in descending order, and also get the indices `idx` was\n sorted by.\n\n >>> idx.sort_values(ascending=False, return_indexer=True)\n (Int64Index([1000, 100, 10, 1], dtype='int64'), array([3, 1, 0, 2]))\n \"\"\"\n _as = self.argsort()\n if not ascending:\n _as = _as[::-1]\n\n sorted_index = self.take(_as)\n\n if return_indexer:\n return sorted_index, _as\n else:\n return sorted_index" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn the integer indices that would sort the index.\n\n Parameters\n ----------\n *args\n Passed to `numpy.ndarray.argsort`.\n **kwargs\n Passed to `numpy.ndarray.argsort`.\n\n Returns\n -------\n numpy.ndarray\n Integer indices that would sort the index if used as\n an indexer.\n\n See Also\n --------\n numpy.argsort : Similar method for NumPy arrays.\n Index.sort_values : Return sorted copy of Index.\n\n Examples\n --------\n >>> idx = pd.Index(['b', 'a', 'd', 'c'])\n >>> idx\n Index(['b', 'a', 'd', 'c'], dtype='object')\n\n >>> order = idx.argsort()\n >>> order\n array([1, 0, 3, 2])\n\n >>> idx[order]\n Index(['a', 'b', 'c', 'd'], dtype='object')", "output": "def argsort(self, *args, **kwargs):\n \"\"\"\n Return the integer indices that would sort the index.\n\n Parameters\n ----------\n *args\n Passed to `numpy.ndarray.argsort`.\n **kwargs\n Passed to `numpy.ndarray.argsort`.\n\n Returns\n -------\n numpy.ndarray\n Integer indices that would sort the index if used as\n an indexer.\n\n See Also\n --------\n numpy.argsort : Similar method for NumPy arrays.\n Index.sort_values : Return sorted copy of Index.\n\n Examples\n --------\n >>> idx = pd.Index(['b', 'a', 'd', 'c'])\n >>> idx\n Index(['b', 'a', 'd', 'c'], dtype='object')\n\n >>> order = idx.argsort()\n >>> order\n array([1, 0, 3, 2])\n\n >>> idx[order]\n Index(['a', 'b', 'c', 'd'], dtype='object')\n \"\"\"\n result = self.asi8\n if result is None:\n result = np.array(self)\n return result.argsort(*args, **kwargs)" }, { "instruction": "Write or improve a Python function based on this description:\n\nFast lookup of value from 1-dimensional ndarray. Only use this if you\n know what you're doing.", "output": "def get_value(self, series, key):\n \"\"\"\n Fast lookup of value from 1-dimensional ndarray. Only use this if you\n know what you're doing.\n \"\"\"\n\n # if we have something that is Index-like, then\n # use this, e.g. DatetimeIndex\n # Things like `Series._get_value` (via .at) pass the EA directly here.\n s = getattr(series, '_values', series)\n if isinstance(s, (ExtensionArray, Index)) and is_scalar(key):\n # GH 20882, 21257\n # Unify Index and ExtensionArray treatment\n # First try to convert the key to a location\n # If that fails, raise a KeyError if an integer\n # index, otherwise, see if key is an integer, and\n # try that\n try:\n iloc = self.get_loc(key)\n return s[iloc]\n except KeyError:\n if (len(self) > 0 and\n (self.holds_integer() or self.is_boolean())):\n raise\n elif is_integer(key):\n return s[key]\n\n s = com.values_from_object(series)\n k = com.values_from_object(key)\n\n k = self._convert_scalar_indexer(k, kind='getitem')\n try:\n return self._engine.get_value(s, k,\n tz=getattr(series.dtype, 'tz', None))\n except KeyError as e1:\n if len(self) > 0 and (self.holds_integer() or self.is_boolean()):\n raise\n\n try:\n return libindex.get_value_box(s, key)\n except IndexError:\n raise\n except TypeError:\n # generator/iterator-like\n if is_iterator(key):\n raise InvalidIndexError(key)\n else:\n raise e1\n except Exception: # pragma: no cover\n raise e1\n except TypeError:\n # python 3\n if is_scalar(key): # pragma: no cover\n raise IndexError(key)\n raise InvalidIndexError(key)" }, { "instruction": "Write or improve a Python function based on this description:\n\nFast lookup of value from 1-dimensional ndarray.\n\n Notes\n -----\n Only use this if you know what you're doing.", "output": "def set_value(self, arr, key, value):\n \"\"\"\n Fast lookup of value from 1-dimensional ndarray.\n\n Notes\n -----\n Only use this if you know what you're doing.\n \"\"\"\n self._engine.set_value(com.values_from_object(arr),\n com.values_from_object(key), value)" }, { "instruction": "Write or improve a Python function based on this description:\n\nGuaranteed return of an indexer even when non-unique.\n\n This dispatches to get_indexer or get_indexer_nonunique\n as appropriate.", "output": "def get_indexer_for(self, target, **kwargs):\n \"\"\"\n Guaranteed return of an indexer even when non-unique.\n\n This dispatches to get_indexer or get_indexer_nonunique\n as appropriate.\n \"\"\"\n if self.is_unique:\n return self.get_indexer(target, **kwargs)\n indexer, _ = self.get_indexer_non_unique(target, **kwargs)\n return indexer" }, { "instruction": "Write or improve a Python function based on this description:\n\nGroup the index labels by a given array of values.\n\n Parameters\n ----------\n values : array\n Values used to determine the groups.\n\n Returns\n -------\n groups : dict\n {group name -> group labels}", "output": "def groupby(self, values):\n \"\"\"\n Group the index labels by a given array of values.\n\n Parameters\n ----------\n values : array\n Values used to determine the groups.\n\n Returns\n -------\n groups : dict\n {group name -> group labels}\n \"\"\"\n\n # TODO: if we are a MultiIndex, we can do better\n # that converting to tuples\n if isinstance(values, ABCMultiIndex):\n values = values.values\n values = ensure_categorical(values)\n result = values._reverse_indexer()\n\n # map to the label\n result = {k: self.take(v) for k, v in result.items()}\n\n return result" }, { "instruction": "Write or improve a Python function based on this description:\n\nMap values using input correspondence (a dict, Series, or function).\n\n Parameters\n ----------\n mapper : function, dict, or Series\n Mapping correspondence.\n na_action : {None, 'ignore'}\n If 'ignore', propagate NA values, without passing them to the\n mapping correspondence.\n\n Returns\n -------\n applied : Union[Index, MultiIndex], inferred\n The output of the mapping function applied to the index.\n If the function returns a tuple with more than one element\n a MultiIndex will be returned.", "output": "def map(self, mapper, na_action=None):\n \"\"\"\n Map values using input correspondence (a dict, Series, or function).\n\n Parameters\n ----------\n mapper : function, dict, or Series\n Mapping correspondence.\n na_action : {None, 'ignore'}\n If 'ignore', propagate NA values, without passing them to the\n mapping correspondence.\n\n Returns\n -------\n applied : Union[Index, MultiIndex], inferred\n The output of the mapping function applied to the index.\n If the function returns a tuple with more than one element\n a MultiIndex will be returned.\n \"\"\"\n\n from .multi import MultiIndex\n new_values = super()._map_values(mapper, na_action=na_action)\n\n attributes = self._get_attributes_dict()\n\n # we can return a MultiIndex\n if new_values.size and isinstance(new_values[0], tuple):\n if isinstance(self, MultiIndex):\n names = self.names\n elif attributes.get('name'):\n names = [attributes.get('name')] * len(new_values[0])\n else:\n names = None\n return MultiIndex.from_tuples(new_values,\n names=names)\n\n attributes['copy'] = False\n if not new_values.size:\n # empty\n attributes['dtype'] = self.dtype\n\n return Index(new_values, **attributes)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn a boolean array where the index values are in `values`.\n\n Compute boolean array of whether each index value is found in the\n passed set of values. The length of the returned boolean array matches\n the length of the index.\n\n Parameters\n ----------\n values : set or list-like\n Sought values.\n\n .. versionadded:: 0.18.1\n\n Support for values as a set.\n\n level : str or int, optional\n Name or position of the index level to use (if the index is a\n `MultiIndex`).\n\n Returns\n -------\n is_contained : ndarray\n NumPy array of boolean values.\n\n See Also\n --------\n Series.isin : Same for Series.\n DataFrame.isin : Same method for DataFrames.\n\n Notes\n -----\n In the case of `MultiIndex` you must either specify `values` as a\n list-like object containing tuples that are the same length as the\n number of levels, or specify `level`. Otherwise it will raise a\n ``ValueError``.\n\n If `level` is specified:\n\n - if it is the name of one *and only one* index level, use that level;\n - otherwise it should be a number indicating level position.\n\n Examples\n --------\n >>> idx = pd.Index([1,2,3])\n >>> idx\n Int64Index([1, 2, 3], dtype='int64')\n\n Check whether each index value in a list of values.\n >>> idx.isin([1, 4])\n array([ True, False, False])\n\n >>> midx = pd.MultiIndex.from_arrays([[1,2,3],\n ... ['red', 'blue', 'green']],\n ... names=('number', 'color'))\n >>> midx\n MultiIndex(levels=[[1, 2, 3], ['blue', 'green', 'red']],\n codes=[[0, 1, 2], [2, 0, 1]],\n names=['number', 'color'])\n\n Check whether the strings in the 'color' level of the MultiIndex\n are in a list of colors.\n\n >>> midx.isin(['red', 'orange', 'yellow'], level='color')\n array([ True, False, False])\n\n To check across the levels of a MultiIndex, pass a list of tuples:\n\n >>> midx.isin([(1, 'red'), (3, 'red')])\n array([ True, False, False])\n\n For a DatetimeIndex, string values in `values` are converted to\n Timestamps.\n\n >>> dates = ['2000-03-11', '2000-03-12', '2000-03-13']\n >>> dti = pd.to_datetime(dates)\n >>> dti\n DatetimeIndex(['2000-03-11', '2000-03-12', '2000-03-13'],\n dtype='datetime64[ns]', freq=None)\n\n >>> dti.isin(['2000-03-11'])\n array([ True, False, False])", "output": "def isin(self, values, level=None):\n \"\"\"\n Return a boolean array where the index values are in `values`.\n\n Compute boolean array of whether each index value is found in the\n passed set of values. The length of the returned boolean array matches\n the length of the index.\n\n Parameters\n ----------\n values : set or list-like\n Sought values.\n\n .. versionadded:: 0.18.1\n\n Support for values as a set.\n\n level : str or int, optional\n Name or position of the index level to use (if the index is a\n `MultiIndex`).\n\n Returns\n -------\n is_contained : ndarray\n NumPy array of boolean values.\n\n See Also\n --------\n Series.isin : Same for Series.\n DataFrame.isin : Same method for DataFrames.\n\n Notes\n -----\n In the case of `MultiIndex` you must either specify `values` as a\n list-like object containing tuples that are the same length as the\n number of levels, or specify `level`. Otherwise it will raise a\n ``ValueError``.\n\n If `level` is specified:\n\n - if it is the name of one *and only one* index level, use that level;\n - otherwise it should be a number indicating level position.\n\n Examples\n --------\n >>> idx = pd.Index([1,2,3])\n >>> idx\n Int64Index([1, 2, 3], dtype='int64')\n\n Check whether each index value in a list of values.\n >>> idx.isin([1, 4])\n array([ True, False, False])\n\n >>> midx = pd.MultiIndex.from_arrays([[1,2,3],\n ... ['red', 'blue', 'green']],\n ... names=('number', 'color'))\n >>> midx\n MultiIndex(levels=[[1, 2, 3], ['blue', 'green', 'red']],\n codes=[[0, 1, 2], [2, 0, 1]],\n names=['number', 'color'])\n\n Check whether the strings in the 'color' level of the MultiIndex\n are in a list of colors.\n\n >>> midx.isin(['red', 'orange', 'yellow'], level='color')\n array([ True, False, False])\n\n To check across the levels of a MultiIndex, pass a list of tuples:\n\n >>> midx.isin([(1, 'red'), (3, 'red')])\n array([ True, False, False])\n\n For a DatetimeIndex, string values in `values` are converted to\n Timestamps.\n\n >>> dates = ['2000-03-11', '2000-03-12', '2000-03-13']\n >>> dti = pd.to_datetime(dates)\n >>> dti\n DatetimeIndex(['2000-03-11', '2000-03-12', '2000-03-13'],\n dtype='datetime64[ns]', freq=None)\n\n >>> dti.isin(['2000-03-11'])\n array([ True, False, False])\n \"\"\"\n if level is not None:\n self._validate_index_level(level)\n return algos.isin(self, values)" }, { "instruction": "Write or improve a Python function based on this description:\n\nFor an ordered or unique index, compute the slice indexer for input\n labels and step.\n\n Parameters\n ----------\n start : label, default None\n If None, defaults to the beginning\n end : label, default None\n If None, defaults to the end\n step : int, default None\n kind : string, default None\n\n Returns\n -------\n indexer : slice\n\n Raises\n ------\n KeyError : If key does not exist, or key is not unique and index is\n not ordered.\n\n Notes\n -----\n This function assumes that the data is sorted, so use at your own peril\n\n Examples\n ---------\n This is a method on all index types. For example you can do:\n\n >>> idx = pd.Index(list('abcd'))\n >>> idx.slice_indexer(start='b', end='c')\n slice(1, 3)\n\n >>> idx = pd.MultiIndex.from_arrays([list('abcd'), list('efgh')])\n >>> idx.slice_indexer(start='b', end=('c', 'g'))\n slice(1, 3)", "output": "def slice_indexer(self, start=None, end=None, step=None, kind=None):\n \"\"\"\n For an ordered or unique index, compute the slice indexer for input\n labels and step.\n\n Parameters\n ----------\n start : label, default None\n If None, defaults to the beginning\n end : label, default None\n If None, defaults to the end\n step : int, default None\n kind : string, default None\n\n Returns\n -------\n indexer : slice\n\n Raises\n ------\n KeyError : If key does not exist, or key is not unique and index is\n not ordered.\n\n Notes\n -----\n This function assumes that the data is sorted, so use at your own peril\n\n Examples\n ---------\n This is a method on all index types. For example you can do:\n\n >>> idx = pd.Index(list('abcd'))\n >>> idx.slice_indexer(start='b', end='c')\n slice(1, 3)\n\n >>> idx = pd.MultiIndex.from_arrays([list('abcd'), list('efgh')])\n >>> idx.slice_indexer(start='b', end=('c', 'g'))\n slice(1, 3)\n \"\"\"\n start_slice, end_slice = self.slice_locs(start, end, step=step,\n kind=kind)\n\n # return a slice\n if not is_scalar(start_slice):\n raise AssertionError(\"Start slice bound is non-scalar\")\n if not is_scalar(end_slice):\n raise AssertionError(\"End slice bound is non-scalar\")\n\n return slice(start_slice, end_slice, step)" }, { "instruction": "Write or improve a Python function based on this description:\n\nIf we have a float key and are not a floating index, then try to cast\n to an int if equivalent.", "output": "def _maybe_cast_indexer(self, key):\n \"\"\"\n If we have a float key and are not a floating index, then try to cast\n to an int if equivalent.\n \"\"\"\n\n if is_float(key) and not self.is_floating():\n try:\n ckey = int(key)\n if ckey == key:\n key = ckey\n except (OverflowError, ValueError, TypeError):\n pass\n return key" }, { "instruction": "Write or improve a Python function based on this description:\n\nIf we are positional indexer, validate that we have appropriate\n typed bounds must be an integer.", "output": "def _validate_indexer(self, form, key, kind):\n \"\"\"\n If we are positional indexer, validate that we have appropriate\n typed bounds must be an integer.\n \"\"\"\n assert kind in ['ix', 'loc', 'getitem', 'iloc']\n\n if key is None:\n pass\n elif is_integer(key):\n pass\n elif kind in ['iloc', 'getitem']:\n self._invalid_indexer(form, key)\n return key" }, { "instruction": "Write or improve a Python function based on this description:\n\nCalculate slice bound that corresponds to given label.\n\n Returns leftmost (one-past-the-rightmost if ``side=='right'``) position\n of given label.\n\n Parameters\n ----------\n label : object\n side : {'left', 'right'}\n kind : {'ix', 'loc', 'getitem'}", "output": "def get_slice_bound(self, label, side, kind):\n \"\"\"\n Calculate slice bound that corresponds to given label.\n\n Returns leftmost (one-past-the-rightmost if ``side=='right'``) position\n of given label.\n\n Parameters\n ----------\n label : object\n side : {'left', 'right'}\n kind : {'ix', 'loc', 'getitem'}\n \"\"\"\n assert kind in ['ix', 'loc', 'getitem', None]\n\n if side not in ('left', 'right'):\n raise ValueError(\"Invalid value for side kwarg,\"\n \" must be either 'left' or 'right': %s\" %\n (side, ))\n\n original_label = label\n\n # For datetime indices label may be a string that has to be converted\n # to datetime boundary according to its resolution.\n label = self._maybe_cast_slice_bound(label, side, kind)\n\n # we need to look up the label\n try:\n slc = self._get_loc_only_exact_matches(label)\n except KeyError as err:\n try:\n return self._searchsorted_monotonic(label, side)\n except ValueError:\n # raise the original KeyError\n raise err\n\n if isinstance(slc, np.ndarray):\n # get_loc may return a boolean array or an array of indices, which\n # is OK as long as they are representable by a slice.\n if is_bool_dtype(slc):\n slc = lib.maybe_booleans_to_slice(slc.view('u1'))\n else:\n slc = lib.maybe_indices_to_slice(slc.astype('i8'), len(self))\n if isinstance(slc, np.ndarray):\n raise KeyError(\"Cannot get %s slice bound for non-unique \"\n \"label: %r\" % (side, original_label))\n\n if isinstance(slc, slice):\n if side == 'left':\n return slc.start\n else:\n return slc.stop\n else:\n if side == 'right':\n return slc + 1\n else:\n return slc" }, { "instruction": "Write or improve a Python function based on this description:\n\nCompute slice locations for input labels.\n\n Parameters\n ----------\n start : label, default None\n If None, defaults to the beginning\n end : label, default None\n If None, defaults to the end\n step : int, defaults None\n If None, defaults to 1\n kind : {'ix', 'loc', 'getitem'} or None\n\n Returns\n -------\n start, end : int\n\n See Also\n --------\n Index.get_loc : Get location for a single label.\n\n Notes\n -----\n This method only works if the index is monotonic or unique.\n\n Examples\n ---------\n >>> idx = pd.Index(list('abcd'))\n >>> idx.slice_locs(start='b', end='c')\n (1, 3)", "output": "def slice_locs(self, start=None, end=None, step=None, kind=None):\n \"\"\"\n Compute slice locations for input labels.\n\n Parameters\n ----------\n start : label, default None\n If None, defaults to the beginning\n end : label, default None\n If None, defaults to the end\n step : int, defaults None\n If None, defaults to 1\n kind : {'ix', 'loc', 'getitem'} or None\n\n Returns\n -------\n start, end : int\n\n See Also\n --------\n Index.get_loc : Get location for a single label.\n\n Notes\n -----\n This method only works if the index is monotonic or unique.\n\n Examples\n ---------\n >>> idx = pd.Index(list('abcd'))\n >>> idx.slice_locs(start='b', end='c')\n (1, 3)\n \"\"\"\n inc = (step is None or step >= 0)\n\n if not inc:\n # If it's a reverse slice, temporarily swap bounds.\n start, end = end, start\n\n # GH 16785: If start and end happen to be date strings with UTC offsets\n # attempt to parse and check that the offsets are the same\n if (isinstance(start, (str, datetime))\n and isinstance(end, (str, datetime))):\n try:\n ts_start = Timestamp(start)\n ts_end = Timestamp(end)\n except (ValueError, TypeError):\n pass\n else:\n if not tz_compare(ts_start.tzinfo, ts_end.tzinfo):\n raise ValueError(\"Both dates must have the \"\n \"same UTC offset\")\n\n start_slice = None\n if start is not None:\n start_slice = self.get_slice_bound(start, 'left', kind)\n if start_slice is None:\n start_slice = 0\n\n end_slice = None\n if end is not None:\n end_slice = self.get_slice_bound(end, 'right', kind)\n if end_slice is None:\n end_slice = len(self)\n\n if not inc:\n # Bounds at this moment are swapped, swap them back and shift by 1.\n #\n # slice_locs('B', 'A', step=-1): s='B', e='A'\n #\n # s='A' e='B'\n # AFTER SWAP: | |\n # v ------------------> V\n # -----------------------------------\n # | | |A|A|A|A| | | | | |B|B| | | | |\n # -----------------------------------\n # ^ <------------------ ^\n # SHOULD BE: | |\n # end=s-1 start=e-1\n #\n end_slice, start_slice = start_slice - 1, end_slice - 1\n\n # i == -1 triggers ``len(self) + i`` selection that points to the\n # last element, not before-the-first one, subtracting len(self)\n # compensates that.\n if end_slice == -1:\n end_slice -= len(self)\n if start_slice == -1:\n start_slice -= len(self)\n\n return start_slice, end_slice" }, { "instruction": "Write or improve a Python function based on this description:\n\nMake new Index with passed location(-s) deleted.\n\n Returns\n -------\n new_index : Index", "output": "def delete(self, loc):\n \"\"\"\n Make new Index with passed location(-s) deleted.\n\n Returns\n -------\n new_index : Index\n \"\"\"\n return self._shallow_copy(np.delete(self._data, loc))" }, { "instruction": "Write or improve a Python function based on this description:\n\nMake new Index inserting new item at location.\n\n Follows Python list.append semantics for negative values.\n\n Parameters\n ----------\n loc : int\n item : object\n\n Returns\n -------\n new_index : Index", "output": "def insert(self, loc, item):\n \"\"\"\n Make new Index inserting new item at location.\n\n Follows Python list.append semantics for negative values.\n\n Parameters\n ----------\n loc : int\n item : object\n\n Returns\n -------\n new_index : Index\n \"\"\"\n _self = np.asarray(self)\n item = self._coerce_scalar_to_index(item)._ndarray_values\n idx = np.concatenate((_self[:loc], item, _self[loc:]))\n return self._shallow_copy_with_infer(idx)" }, { "instruction": "Write or improve a Python function based on this description:\n\nMake new Index with passed list of labels deleted.\n\n Parameters\n ----------\n labels : array-like\n errors : {'ignore', 'raise'}, default 'raise'\n If 'ignore', suppress error and existing labels are dropped.\n\n Returns\n -------\n dropped : Index\n\n Raises\n ------\n KeyError\n If not all of the labels are found in the selected axis", "output": "def drop(self, labels, errors='raise'):\n \"\"\"\n Make new Index with passed list of labels deleted.\n\n Parameters\n ----------\n labels : array-like\n errors : {'ignore', 'raise'}, default 'raise'\n If 'ignore', suppress error and existing labels are dropped.\n\n Returns\n -------\n dropped : Index\n\n Raises\n ------\n KeyError\n If not all of the labels are found in the selected axis\n \"\"\"\n arr_dtype = 'object' if self.dtype == 'object' else None\n labels = com.index_labels_to_array(labels, dtype=arr_dtype)\n indexer = self.get_indexer(labels)\n mask = indexer == -1\n if mask.any():\n if errors != 'ignore':\n raise KeyError(\n '{} not found in axis'.format(labels[mask]))\n indexer = indexer[~mask]\n return self.delete(indexer)" }, { "instruction": "Write or improve a Python function based on this description:\n\nAdd in comparison methods.", "output": "def _add_comparison_methods(cls):\n \"\"\"\n Add in comparison methods.\n \"\"\"\n cls.__eq__ = _make_comparison_op(operator.eq, cls)\n cls.__ne__ = _make_comparison_op(operator.ne, cls)\n cls.__lt__ = _make_comparison_op(operator.lt, cls)\n cls.__gt__ = _make_comparison_op(operator.gt, cls)\n cls.__le__ = _make_comparison_op(operator.le, cls)\n cls.__ge__ = _make_comparison_op(operator.ge, cls)" }, { "instruction": "Write or improve a Python function based on this description:\n\nAdd in the numeric add/sub methods to disable.", "output": "def _add_numeric_methods_add_sub_disabled(cls):\n \"\"\"\n Add in the numeric add/sub methods to disable.\n \"\"\"\n cls.__add__ = make_invalid_op('__add__')\n cls.__radd__ = make_invalid_op('__radd__')\n cls.__iadd__ = make_invalid_op('__iadd__')\n cls.__sub__ = make_invalid_op('__sub__')\n cls.__rsub__ = make_invalid_op('__rsub__')\n cls.__isub__ = make_invalid_op('__isub__')" }, { "instruction": "Write or improve a Python function based on this description:\n\nAdd in numeric methods to disable other than add/sub.", "output": "def _add_numeric_methods_disabled(cls):\n \"\"\"\n Add in numeric methods to disable other than add/sub.\n \"\"\"\n cls.__pow__ = make_invalid_op('__pow__')\n cls.__rpow__ = make_invalid_op('__rpow__')\n cls.__mul__ = make_invalid_op('__mul__')\n cls.__rmul__ = make_invalid_op('__rmul__')\n cls.__floordiv__ = make_invalid_op('__floordiv__')\n cls.__rfloordiv__ = make_invalid_op('__rfloordiv__')\n cls.__truediv__ = make_invalid_op('__truediv__')\n cls.__rtruediv__ = make_invalid_op('__rtruediv__')\n cls.__mod__ = make_invalid_op('__mod__')\n cls.__divmod__ = make_invalid_op('__divmod__')\n cls.__neg__ = make_invalid_op('__neg__')\n cls.__pos__ = make_invalid_op('__pos__')\n cls.__abs__ = make_invalid_op('__abs__')\n cls.__inv__ = make_invalid_op('__inv__')" }, { "instruction": "Write or improve a Python function based on this description:\n\nValidate if we can perform a numeric unary operation.", "output": "def _validate_for_numeric_unaryop(self, op, opstr):\n \"\"\"\n Validate if we can perform a numeric unary operation.\n \"\"\"\n if not self._is_numeric_dtype:\n raise TypeError(\"cannot evaluate a numeric op \"\n \"{opstr} for type: {typ}\"\n .format(opstr=opstr, typ=type(self).__name__))" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn valid other; evaluate or raise TypeError if we are not of\n the appropriate type.\n\n Notes\n -----\n This is an internal method called by ops.", "output": "def _validate_for_numeric_binop(self, other, op):\n \"\"\"\n Return valid other; evaluate or raise TypeError if we are not of\n the appropriate type.\n\n Notes\n -----\n This is an internal method called by ops.\n \"\"\"\n opstr = '__{opname}__'.format(opname=op.__name__)\n # if we are an inheritor of numeric,\n # but not actually numeric (e.g. DatetimeIndex/PeriodIndex)\n if not self._is_numeric_dtype:\n raise TypeError(\"cannot evaluate a numeric op {opstr} \"\n \"for type: {typ}\"\n .format(opstr=opstr, typ=type(self).__name__))\n\n if isinstance(other, Index):\n if not other._is_numeric_dtype:\n raise TypeError(\"cannot evaluate a numeric op \"\n \"{opstr} with type: {typ}\"\n .format(opstr=opstr, typ=type(other)))\n elif isinstance(other, np.ndarray) and not other.ndim:\n other = other.item()\n\n if isinstance(other, (Index, ABCSeries, np.ndarray)):\n if len(self) != len(other):\n raise ValueError(\"cannot evaluate a numeric op with \"\n \"unequal lengths\")\n other = com.values_from_object(other)\n if other.dtype.kind not in ['f', 'i', 'u']:\n raise TypeError(\"cannot evaluate a numeric op \"\n \"with a non-numeric dtype\")\n elif isinstance(other, (ABCDateOffset, np.timedelta64, timedelta)):\n # higher up to handle\n pass\n elif isinstance(other, (datetime, np.datetime64)):\n # higher up to handle\n pass\n else:\n if not (is_float(other) or is_integer(other)):\n raise TypeError(\"can only perform ops with scalar values\")\n\n return other" }, { "instruction": "Write or improve a Python function based on this description:\n\nAdd in numeric methods.", "output": "def _add_numeric_methods_binary(cls):\n \"\"\"\n Add in numeric methods.\n \"\"\"\n cls.__add__ = _make_arithmetic_op(operator.add, cls)\n cls.__radd__ = _make_arithmetic_op(ops.radd, cls)\n cls.__sub__ = _make_arithmetic_op(operator.sub, cls)\n cls.__rsub__ = _make_arithmetic_op(ops.rsub, cls)\n cls.__rpow__ = _make_arithmetic_op(ops.rpow, cls)\n cls.__pow__ = _make_arithmetic_op(operator.pow, cls)\n\n cls.__truediv__ = _make_arithmetic_op(operator.truediv, cls)\n cls.__rtruediv__ = _make_arithmetic_op(ops.rtruediv, cls)\n\n # TODO: rmod? rdivmod?\n cls.__mod__ = _make_arithmetic_op(operator.mod, cls)\n cls.__floordiv__ = _make_arithmetic_op(operator.floordiv, cls)\n cls.__rfloordiv__ = _make_arithmetic_op(ops.rfloordiv, cls)\n cls.__divmod__ = _make_arithmetic_op(divmod, cls)\n cls.__mul__ = _make_arithmetic_op(operator.mul, cls)\n cls.__rmul__ = _make_arithmetic_op(ops.rmul, cls)" }, { "instruction": "Write or improve a Python function based on this description:\n\nAdd in numeric unary methods.", "output": "def _add_numeric_methods_unary(cls):\n \"\"\"\n Add in numeric unary methods.\n \"\"\"\n def _make_evaluate_unary(op, opstr):\n\n def _evaluate_numeric_unary(self):\n\n self._validate_for_numeric_unaryop(op, opstr)\n attrs = self._get_attributes_dict()\n attrs = self._maybe_update_attributes(attrs)\n return Index(op(self.values), **attrs)\n\n _evaluate_numeric_unary.__name__ = opstr\n return _evaluate_numeric_unary\n\n cls.__neg__ = _make_evaluate_unary(operator.neg, '__neg__')\n cls.__pos__ = _make_evaluate_unary(operator.pos, '__pos__')\n cls.__abs__ = _make_evaluate_unary(np.abs, '__abs__')\n cls.__inv__ = _make_evaluate_unary(lambda x: -x, '__inv__')" }, { "instruction": "Write or improve a Python function based on this description:\n\nAdd in logical methods.", "output": "def _add_logical_methods(cls):\n \"\"\"\n Add in logical methods.\n \"\"\"\n _doc = \"\"\"\n %(desc)s\n\n Parameters\n ----------\n *args\n These parameters will be passed to numpy.%(outname)s.\n **kwargs\n These parameters will be passed to numpy.%(outname)s.\n\n Returns\n -------\n %(outname)s : bool or array_like (if axis is specified)\n A single element array_like may be converted to bool.\"\"\"\n\n _index_shared_docs['index_all'] = dedent(\"\"\"\n\n See Also\n --------\n Index.any : Return whether any element in an Index is True.\n Series.any : Return whether any element in a Series is True.\n Series.all : Return whether all elements in a Series are True.\n\n Notes\n -----\n Not a Number (NaN), positive infinity and negative infinity\n evaluate to True because these are not equal to zero.\n\n Examples\n --------\n **all**\n\n True, because nonzero integers are considered True.\n\n >>> pd.Index([1, 2, 3]).all()\n True\n\n False, because ``0`` is considered False.\n\n >>> pd.Index([0, 1, 2]).all()\n False\n\n **any**\n\n True, because ``1`` is considered True.\n\n >>> pd.Index([0, 0, 1]).any()\n True\n\n False, because ``0`` is considered False.\n\n >>> pd.Index([0, 0, 0]).any()\n False\n \"\"\")\n\n _index_shared_docs['index_any'] = dedent(\"\"\"\n\n See Also\n --------\n Index.all : Return whether all elements are True.\n Series.all : Return whether all elements are True.\n\n Notes\n -----\n Not a Number (NaN), positive infinity and negative infinity\n evaluate to True because these are not equal to zero.\n\n Examples\n --------\n >>> index = pd.Index([0, 1, 2])\n >>> index.any()\n True\n\n >>> index = pd.Index([0, 0, 0])\n >>> index.any()\n False\n \"\"\")\n\n def _make_logical_function(name, desc, f):\n @Substitution(outname=name, desc=desc)\n @Appender(_index_shared_docs['index_' + name])\n @Appender(_doc)\n def logical_func(self, *args, **kwargs):\n result = f(self.values)\n if (isinstance(result, (np.ndarray, ABCSeries, Index)) and\n result.ndim == 0):\n # return NumPy type\n return result.dtype.type(result.item())\n else: # pragma: no cover\n return result\n\n logical_func.__name__ = name\n return logical_func\n\n cls.all = _make_logical_function('all', 'Return whether all elements '\n 'are True.',\n np.all)\n cls.any = _make_logical_function('any',\n 'Return whether any element is True.',\n np.any)" }, { "instruction": "Write or improve a Python function based on this description:\n\ncreate and return a BaseGrouper, which is an internal\n mapping of how to create the grouper indexers.\n This may be composed of multiple Grouping objects, indicating\n multiple groupers\n\n Groupers are ultimately index mappings. They can originate as:\n index mappings, keys to columns, functions, or Groupers\n\n Groupers enable local references to axis,level,sort, while\n the passed in axis, level, and sort are 'global'.\n\n This routine tries to figure out what the passing in references\n are and then creates a Grouping for each one, combined into\n a BaseGrouper.\n\n If observed & we have a categorical grouper, only show the observed\n values\n\n If validate, then check for key/level overlaps", "output": "def _get_grouper(obj, key=None, axis=0, level=None, sort=True,\n observed=False, mutated=False, validate=True):\n \"\"\"\n create and return a BaseGrouper, which is an internal\n mapping of how to create the grouper indexers.\n This may be composed of multiple Grouping objects, indicating\n multiple groupers\n\n Groupers are ultimately index mappings. They can originate as:\n index mappings, keys to columns, functions, or Groupers\n\n Groupers enable local references to axis,level,sort, while\n the passed in axis, level, and sort are 'global'.\n\n This routine tries to figure out what the passing in references\n are and then creates a Grouping for each one, combined into\n a BaseGrouper.\n\n If observed & we have a categorical grouper, only show the observed\n values\n\n If validate, then check for key/level overlaps\n\n \"\"\"\n group_axis = obj._get_axis(axis)\n\n # validate that the passed single level is compatible with the passed\n # axis of the object\n if level is not None:\n # TODO: These if-block and else-block are almost same.\n # MultiIndex instance check is removable, but it seems that there are\n # some processes only for non-MultiIndex in else-block,\n # eg. `obj.index.name != level`. We have to consider carefully whether\n # these are applicable for MultiIndex. Even if these are applicable,\n # we need to check if it makes no side effect to subsequent processes\n # on the outside of this condition.\n # (GH 17621)\n if isinstance(group_axis, MultiIndex):\n if is_list_like(level) and len(level) == 1:\n level = level[0]\n\n if key is None and is_scalar(level):\n # Get the level values from group_axis\n key = group_axis.get_level_values(level)\n level = None\n\n else:\n # allow level to be a length-one list-like object\n # (e.g., level=[0])\n # GH 13901\n if is_list_like(level):\n nlevels = len(level)\n if nlevels == 1:\n level = level[0]\n elif nlevels == 0:\n raise ValueError('No group keys passed!')\n else:\n raise ValueError('multiple levels only valid with '\n 'MultiIndex')\n\n if isinstance(level, str):\n if obj.index.name != level:\n raise ValueError('level name {} is not the name of the '\n 'index'.format(level))\n elif level > 0 or level < -1:\n raise ValueError(\n 'level > 0 or level < -1 only valid with MultiIndex')\n\n # NOTE: `group_axis` and `group_axis.get_level_values(level)`\n # are same in this section.\n level = None\n key = group_axis\n\n # a passed-in Grouper, directly convert\n if isinstance(key, Grouper):\n binner, grouper, obj = key._get_grouper(obj, validate=False)\n if key.key is None:\n return grouper, [], obj\n else:\n return grouper, {key.key}, obj\n\n # already have a BaseGrouper, just return it\n elif isinstance(key, BaseGrouper):\n return key, [], obj\n\n # In the future, a tuple key will always mean an actual key,\n # not an iterable of keys. In the meantime, we attempt to provide\n # a warning. We can assume that the user wanted a list of keys when\n # the key is not in the index. We just have to be careful with\n # unhashble elements of `key`. Any unhashable elements implies that\n # they wanted a list of keys.\n # https://github.com/pandas-dev/pandas/issues/18314\n is_tuple = isinstance(key, tuple)\n all_hashable = is_tuple and is_hashable(key)\n\n if is_tuple:\n if ((all_hashable and key not in obj and set(key).issubset(obj))\n or not all_hashable):\n # column names ('a', 'b') -> ['a', 'b']\n # arrays like (a, b) -> [a, b]\n msg = (\"Interpreting tuple 'by' as a list of keys, rather than \"\n \"a single key. Use 'by=[...]' instead of 'by=(...)'. In \"\n \"the future, a tuple will always mean a single key.\")\n warnings.warn(msg, FutureWarning, stacklevel=5)\n key = list(key)\n\n if not isinstance(key, list):\n keys = [key]\n match_axis_length = False\n else:\n keys = key\n match_axis_length = len(keys) == len(group_axis)\n\n # what are we after, exactly?\n any_callable = any(callable(g) or isinstance(g, dict) for g in keys)\n any_groupers = any(isinstance(g, Grouper) for g in keys)\n any_arraylike = any(isinstance(g, (list, tuple, Series, Index, np.ndarray))\n for g in keys)\n\n # is this an index replacement?\n if (not any_callable and not any_arraylike and not any_groupers and\n match_axis_length and level is None):\n if isinstance(obj, DataFrame):\n all_in_columns_index = all(g in obj.columns or g in\n obj.index.names for g in keys)\n elif isinstance(obj, Series):\n all_in_columns_index = all(g in obj.index.names for g in keys)\n\n if not all_in_columns_index:\n keys = [com.asarray_tuplesafe(keys)]\n\n if isinstance(level, (tuple, list)):\n if key is None:\n keys = [None] * len(level)\n levels = level\n else:\n levels = [level] * len(keys)\n\n groupings = []\n exclusions = []\n\n # if the actual grouper should be obj[key]\n def is_in_axis(key):\n if not _is_label_like(key):\n try:\n obj._data.items.get_loc(key)\n except Exception:\n return False\n\n return True\n\n # if the grouper is obj[name]\n def is_in_obj(gpr):\n try:\n return id(gpr) == id(obj[gpr.name])\n except Exception:\n return False\n\n for i, (gpr, level) in enumerate(zip(keys, levels)):\n\n if is_in_obj(gpr): # df.groupby(df['name'])\n in_axis, name = True, gpr.name\n exclusions.append(name)\n\n elif is_in_axis(gpr): # df.groupby('name')\n if gpr in obj:\n if validate:\n obj._check_label_or_level_ambiguity(gpr)\n in_axis, name, gpr = True, gpr, obj[gpr]\n exclusions.append(name)\n elif obj._is_level_reference(gpr):\n in_axis, name, level, gpr = False, None, gpr, None\n else:\n raise KeyError(gpr)\n elif isinstance(gpr, Grouper) and gpr.key is not None:\n # Add key to exclusions\n exclusions.append(gpr.key)\n in_axis, name = False, None\n else:\n in_axis, name = False, None\n\n if is_categorical_dtype(gpr) and len(gpr) != obj.shape[axis]:\n raise ValueError(\n (\"Length of grouper ({len_gpr}) and axis ({len_axis})\"\n \" must be same length\"\n .format(len_gpr=len(gpr), len_axis=obj.shape[axis])))\n\n # create the Grouping\n # allow us to passing the actual Grouping as the gpr\n ping = (Grouping(group_axis,\n gpr,\n obj=obj,\n name=name,\n level=level,\n sort=sort,\n observed=observed,\n in_axis=in_axis)\n if not isinstance(gpr, Grouping) else gpr)\n\n groupings.append(ping)\n\n if len(groupings) == 0:\n raise ValueError('No group keys passed!')\n\n # create the internals grouper\n grouper = BaseGrouper(group_axis, groupings, sort=sort, mutated=mutated)\n return grouper, exclusions, obj" }, { "instruction": "Write or improve a Python function based on this description:\n\nParameters\n ----------\n obj : the subject object\n validate : boolean, default True\n if True, validate the grouper\n\n Returns\n -------\n a tuple of binner, grouper, obj (possibly sorted)", "output": "def _get_grouper(self, obj, validate=True):\n \"\"\"\n Parameters\n ----------\n obj : the subject object\n validate : boolean, default True\n if True, validate the grouper\n\n Returns\n -------\n a tuple of binner, grouper, obj (possibly sorted)\n \"\"\"\n\n self._set_grouper(obj)\n self.grouper, exclusions, self.obj = _get_grouper(self.obj, [self.key],\n axis=self.axis,\n level=self.level,\n sort=self.sort,\n validate=validate)\n return self.binner, self.grouper, self.obj" }, { "instruction": "Write or improve a Python function based on this description:\n\ngiven an object and the specifications, setup the internal grouper\n for this particular specification\n\n Parameters\n ----------\n obj : the subject object\n sort : bool, default False\n whether the resulting grouper should be sorted", "output": "def _set_grouper(self, obj, sort=False):\n \"\"\"\n given an object and the specifications, setup the internal grouper\n for this particular specification\n\n Parameters\n ----------\n obj : the subject object\n sort : bool, default False\n whether the resulting grouper should be sorted\n \"\"\"\n\n if self.key is not None and self.level is not None:\n raise ValueError(\n \"The Grouper cannot specify both a key and a level!\")\n\n # Keep self.grouper value before overriding\n if self._grouper is None:\n self._grouper = self.grouper\n\n # the key must be a valid info item\n if self.key is not None:\n key = self.key\n # The 'on' is already defined\n if (getattr(self.grouper, 'name', None) == key and\n isinstance(obj, ABCSeries)):\n ax = self._grouper.take(obj.index)\n else:\n if key not in obj._info_axis:\n raise KeyError(\n \"The grouper name {0} is not found\".format(key))\n ax = Index(obj[key], name=key)\n\n else:\n ax = obj._get_axis(self.axis)\n if self.level is not None:\n level = self.level\n\n # if a level is given it must be a mi level or\n # equivalent to the axis name\n if isinstance(ax, MultiIndex):\n level = ax._get_level_number(level)\n ax = Index(ax._get_level_values(level),\n name=ax.names[level])\n\n else:\n if level not in (0, ax.name):\n raise ValueError(\n \"The level {0} is not valid\".format(level))\n\n # possibly sort\n if (self.sort or sort) and not ax.is_monotonic:\n # use stable sort to support first, last, nth\n indexer = self.indexer = ax.argsort(kind='mergesort')\n ax = ax.take(indexer)\n obj = obj._take(indexer, axis=self.axis, is_copy=False)\n\n self.obj = obj\n self.grouper = ax\n return self.grouper" }, { "instruction": "Write or improve a Python function based on this description:\n\nPickle (serialize) object to file.\n\n Parameters\n ----------\n obj : any object\n Any python object.\n path : str\n File path where the pickled object will be stored.\n compression : {'infer', 'gzip', 'bz2', 'zip', 'xz', None}, default 'infer'\n A string representing the compression to use in the output file. By\n default, infers from the file extension in specified path.\n\n .. versionadded:: 0.20.0\n protocol : int\n Int which indicates which protocol should be used by the pickler,\n default HIGHEST_PROTOCOL (see [1], paragraph 12.1.2). The possible\n values for this parameter depend on the version of Python. For Python\n 2.x, possible values are 0, 1, 2. For Python>=3.0, 3 is a valid value.\n For Python >= 3.4, 4 is a valid value. A negative value for the\n protocol parameter is equivalent to setting its value to\n HIGHEST_PROTOCOL.\n\n .. [1] https://docs.python.org/3/library/pickle.html\n .. versionadded:: 0.21.0\n\n See Also\n --------\n read_pickle : Load pickled pandas object (or any object) from file.\n DataFrame.to_hdf : Write DataFrame to an HDF5 file.\n DataFrame.to_sql : Write DataFrame to a SQL database.\n DataFrame.to_parquet : Write a DataFrame to the binary parquet format.\n\n Examples\n --------\n >>> original_df = pd.DataFrame({\"foo\": range(5), \"bar\": range(5, 10)})\n >>> original_df\n foo bar\n 0 0 5\n 1 1 6\n 2 2 7\n 3 3 8\n 4 4 9\n >>> pd.to_pickle(original_df, \"./dummy.pkl\")\n\n >>> unpickled_df = pd.read_pickle(\"./dummy.pkl\")\n >>> unpickled_df\n foo bar\n 0 0 5\n 1 1 6\n 2 2 7\n 3 3 8\n 4 4 9\n\n >>> import os\n >>> os.remove(\"./dummy.pkl\")", "output": "def to_pickle(obj, path, compression='infer',\n protocol=pickle.HIGHEST_PROTOCOL):\n \"\"\"\n Pickle (serialize) object to file.\n\n Parameters\n ----------\n obj : any object\n Any python object.\n path : str\n File path where the pickled object will be stored.\n compression : {'infer', 'gzip', 'bz2', 'zip', 'xz', None}, default 'infer'\n A string representing the compression to use in the output file. By\n default, infers from the file extension in specified path.\n\n .. versionadded:: 0.20.0\n protocol : int\n Int which indicates which protocol should be used by the pickler,\n default HIGHEST_PROTOCOL (see [1], paragraph 12.1.2). The possible\n values for this parameter depend on the version of Python. For Python\n 2.x, possible values are 0, 1, 2. For Python>=3.0, 3 is a valid value.\n For Python >= 3.4, 4 is a valid value. A negative value for the\n protocol parameter is equivalent to setting its value to\n HIGHEST_PROTOCOL.\n\n .. [1] https://docs.python.org/3/library/pickle.html\n .. versionadded:: 0.21.0\n\n See Also\n --------\n read_pickle : Load pickled pandas object (or any object) from file.\n DataFrame.to_hdf : Write DataFrame to an HDF5 file.\n DataFrame.to_sql : Write DataFrame to a SQL database.\n DataFrame.to_parquet : Write a DataFrame to the binary parquet format.\n\n Examples\n --------\n >>> original_df = pd.DataFrame({\"foo\": range(5), \"bar\": range(5, 10)})\n >>> original_df\n foo bar\n 0 0 5\n 1 1 6\n 2 2 7\n 3 3 8\n 4 4 9\n >>> pd.to_pickle(original_df, \"./dummy.pkl\")\n\n >>> unpickled_df = pd.read_pickle(\"./dummy.pkl\")\n >>> unpickled_df\n foo bar\n 0 0 5\n 1 1 6\n 2 2 7\n 3 3 8\n 4 4 9\n\n >>> import os\n >>> os.remove(\"./dummy.pkl\")\n \"\"\"\n path = _stringify_path(path)\n f, fh = _get_handle(path, 'wb',\n compression=compression,\n is_text=False)\n if protocol < 0:\n protocol = pickle.HIGHEST_PROTOCOL\n try:\n f.write(pickle.dumps(obj, protocol=protocol))\n finally:\n f.close()\n for _f in fh:\n _f.close()" }, { "instruction": "Write or improve a Python function based on this description:\n\nLoad pickled pandas object (or any object) from file.\n\n .. warning::\n\n Loading pickled data received from untrusted sources can be\n unsafe. See `here `__.\n\n Parameters\n ----------\n path : str\n File path where the pickled object will be loaded.\n compression : {'infer', 'gzip', 'bz2', 'zip', 'xz', None}, default 'infer'\n For on-the-fly decompression of on-disk data. If 'infer', then use\n gzip, bz2, xz or zip if path ends in '.gz', '.bz2', '.xz',\n or '.zip' respectively, and no decompression otherwise.\n Set to None for no decompression.\n\n .. versionadded:: 0.20.0\n\n Returns\n -------\n unpickled : same type as object stored in file\n\n See Also\n --------\n DataFrame.to_pickle : Pickle (serialize) DataFrame object to file.\n Series.to_pickle : Pickle (serialize) Series object to file.\n read_hdf : Read HDF5 file into a DataFrame.\n read_sql : Read SQL query or database table into a DataFrame.\n read_parquet : Load a parquet object, returning a DataFrame.\n\n Examples\n --------\n >>> original_df = pd.DataFrame({\"foo\": range(5), \"bar\": range(5, 10)})\n >>> original_df\n foo bar\n 0 0 5\n 1 1 6\n 2 2 7\n 3 3 8\n 4 4 9\n >>> pd.to_pickle(original_df, \"./dummy.pkl\")\n\n >>> unpickled_df = pd.read_pickle(\"./dummy.pkl\")\n >>> unpickled_df\n foo bar\n 0 0 5\n 1 1 6\n 2 2 7\n 3 3 8\n 4 4 9\n\n >>> import os\n >>> os.remove(\"./dummy.pkl\")", "output": "def read_pickle(path, compression='infer'):\n \"\"\"\n Load pickled pandas object (or any object) from file.\n\n .. warning::\n\n Loading pickled data received from untrusted sources can be\n unsafe. See `here `__.\n\n Parameters\n ----------\n path : str\n File path where the pickled object will be loaded.\n compression : {'infer', 'gzip', 'bz2', 'zip', 'xz', None}, default 'infer'\n For on-the-fly decompression of on-disk data. If 'infer', then use\n gzip, bz2, xz or zip if path ends in '.gz', '.bz2', '.xz',\n or '.zip' respectively, and no decompression otherwise.\n Set to None for no decompression.\n\n .. versionadded:: 0.20.0\n\n Returns\n -------\n unpickled : same type as object stored in file\n\n See Also\n --------\n DataFrame.to_pickle : Pickle (serialize) DataFrame object to file.\n Series.to_pickle : Pickle (serialize) Series object to file.\n read_hdf : Read HDF5 file into a DataFrame.\n read_sql : Read SQL query or database table into a DataFrame.\n read_parquet : Load a parquet object, returning a DataFrame.\n\n Examples\n --------\n >>> original_df = pd.DataFrame({\"foo\": range(5), \"bar\": range(5, 10)})\n >>> original_df\n foo bar\n 0 0 5\n 1 1 6\n 2 2 7\n 3 3 8\n 4 4 9\n >>> pd.to_pickle(original_df, \"./dummy.pkl\")\n\n >>> unpickled_df = pd.read_pickle(\"./dummy.pkl\")\n >>> unpickled_df\n foo bar\n 0 0 5\n 1 1 6\n 2 2 7\n 3 3 8\n 4 4 9\n\n >>> import os\n >>> os.remove(\"./dummy.pkl\")\n \"\"\"\n path = _stringify_path(path)\n f, fh = _get_handle(path, 'rb', compression=compression, is_text=False)\n\n # 1) try standard libary Pickle\n # 2) try pickle_compat (older pandas version) to handle subclass changes\n # 3) try pickle_compat with latin1 encoding\n\n try:\n with warnings.catch_warnings(record=True):\n # We want to silence any warnings about, e.g. moved modules.\n warnings.simplefilter(\"ignore\", Warning)\n return pickle.load(f)\n except Exception: # noqa: E722\n try:\n return pc.load(f, encoding=None)\n except Exception: # noqa: E722\n return pc.load(f, encoding='latin1')\n finally:\n f.close()\n for _f in fh:\n _f.close()" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn a masking array of same size/shape as arr\n with entries equaling any member of values_to_mask set to True", "output": "def mask_missing(arr, values_to_mask):\n \"\"\"\n Return a masking array of same size/shape as arr\n with entries equaling any member of values_to_mask set to True\n \"\"\"\n dtype, values_to_mask = infer_dtype_from_array(values_to_mask)\n\n try:\n values_to_mask = np.array(values_to_mask, dtype=dtype)\n\n except Exception:\n values_to_mask = np.array(values_to_mask, dtype=object)\n\n na_mask = isna(values_to_mask)\n nonna = values_to_mask[~na_mask]\n\n mask = None\n for x in nonna:\n if mask is None:\n\n # numpy elementwise comparison warning\n if is_numeric_v_string_like(arr, x):\n mask = False\n else:\n mask = arr == x\n\n # if x is a string and arr is not, then we get False and we must\n # expand the mask to size arr.shape\n if is_scalar(mask):\n mask = np.zeros(arr.shape, dtype=bool)\n else:\n\n # numpy elementwise comparison warning\n if is_numeric_v_string_like(arr, x):\n mask |= False\n else:\n mask |= arr == x\n\n if na_mask.any():\n if mask is None:\n mask = isna(arr)\n else:\n mask |= isna(arr)\n\n # GH 21977\n if mask is None:\n mask = np.zeros(arr.shape, dtype=bool)\n\n return mask" }, { "instruction": "Write or improve a Python function based on this description:\n\nLogic for the 1-d interpolation. The result should be 1-d, inputs\n xvalues and yvalues will each be 1-d arrays of the same length.\n\n Bounds_error is currently hardcoded to False since non-scipy ones don't\n take it as an argument.", "output": "def interpolate_1d(xvalues, yvalues, method='linear', limit=None,\n limit_direction='forward', limit_area=None, fill_value=None,\n bounds_error=False, order=None, **kwargs):\n \"\"\"\n Logic for the 1-d interpolation. The result should be 1-d, inputs\n xvalues and yvalues will each be 1-d arrays of the same length.\n\n Bounds_error is currently hardcoded to False since non-scipy ones don't\n take it as an argument.\n \"\"\"\n # Treat the original, non-scipy methods first.\n\n invalid = isna(yvalues)\n valid = ~invalid\n\n if not valid.any():\n # have to call np.asarray(xvalues) since xvalues could be an Index\n # which can't be mutated\n result = np.empty_like(np.asarray(xvalues), dtype=np.float64)\n result.fill(np.nan)\n return result\n\n if valid.all():\n return yvalues\n\n if method == 'time':\n if not getattr(xvalues, 'is_all_dates', None):\n # if not issubclass(xvalues.dtype.type, np.datetime64):\n raise ValueError('time-weighted interpolation only works '\n 'on Series or DataFrames with a '\n 'DatetimeIndex')\n method = 'values'\n\n valid_limit_directions = ['forward', 'backward', 'both']\n limit_direction = limit_direction.lower()\n if limit_direction not in valid_limit_directions:\n msg = ('Invalid limit_direction: expecting one of {valid!r}, '\n 'got {invalid!r}.')\n raise ValueError(msg.format(valid=valid_limit_directions,\n invalid=limit_direction))\n\n if limit_area is not None:\n valid_limit_areas = ['inside', 'outside']\n limit_area = limit_area.lower()\n if limit_area not in valid_limit_areas:\n raise ValueError('Invalid limit_area: expecting one of {}, got '\n '{}.'.format(valid_limit_areas, limit_area))\n\n # default limit is unlimited GH #16282\n if limit is None:\n # limit = len(xvalues)\n pass\n elif not is_integer(limit):\n raise ValueError('Limit must be an integer')\n elif limit < 1:\n raise ValueError('Limit must be greater than 0')\n\n from pandas import Series\n ys = Series(yvalues)\n\n # These are sets of index pointers to invalid values... i.e. {0, 1, etc...\n all_nans = set(np.flatnonzero(invalid))\n start_nans = set(range(ys.first_valid_index()))\n end_nans = set(range(1 + ys.last_valid_index(), len(valid)))\n mid_nans = all_nans - start_nans - end_nans\n\n # Like the sets above, preserve_nans contains indices of invalid values,\n # but in this case, it is the final set of indices that need to be\n # preserved as NaN after the interpolation.\n\n # For example if limit_direction='forward' then preserve_nans will\n # contain indices of NaNs at the beginning of the series, and NaNs that\n # are more than'limit' away from the prior non-NaN.\n\n # set preserve_nans based on direction using _interp_limit\n if limit_direction == 'forward':\n preserve_nans = start_nans | set(_interp_limit(invalid, limit, 0))\n elif limit_direction == 'backward':\n preserve_nans = end_nans | set(_interp_limit(invalid, 0, limit))\n else:\n # both directions... just use _interp_limit\n preserve_nans = set(_interp_limit(invalid, limit, limit))\n\n # if limit_area is set, add either mid or outside indices\n # to preserve_nans GH #16284\n if limit_area == 'inside':\n # preserve NaNs on the outside\n preserve_nans |= start_nans | end_nans\n elif limit_area == 'outside':\n # preserve NaNs on the inside\n preserve_nans |= mid_nans\n\n # sort preserve_nans and covert to list\n preserve_nans = sorted(preserve_nans)\n\n xvalues = getattr(xvalues, 'values', xvalues)\n yvalues = getattr(yvalues, 'values', yvalues)\n result = yvalues.copy()\n\n if method in ['linear', 'time', 'index', 'values']:\n if method in ('values', 'index'):\n inds = np.asarray(xvalues)\n # hack for DatetimeIndex, #1646\n if needs_i8_conversion(inds.dtype.type):\n inds = inds.view(np.int64)\n if inds.dtype == np.object_:\n inds = lib.maybe_convert_objects(inds)\n else:\n inds = xvalues\n result[invalid] = np.interp(inds[invalid], inds[valid], yvalues[valid])\n result[preserve_nans] = np.nan\n return result\n\n sp_methods = ['nearest', 'zero', 'slinear', 'quadratic', 'cubic',\n 'barycentric', 'krogh', 'spline', 'polynomial',\n 'from_derivatives', 'piecewise_polynomial', 'pchip', 'akima']\n\n if method in sp_methods:\n inds = np.asarray(xvalues)\n # hack for DatetimeIndex, #1646\n if issubclass(inds.dtype.type, np.datetime64):\n inds = inds.view(np.int64)\n result[invalid] = _interpolate_scipy_wrapper(inds[valid],\n yvalues[valid],\n inds[invalid],\n method=method,\n fill_value=fill_value,\n bounds_error=bounds_error,\n order=order, **kwargs)\n result[preserve_nans] = np.nan\n return result" }, { "instruction": "Write or improve a Python function based on this description:\n\nPassed off to scipy.interpolate.interp1d. method is scipy's kind.\n Returns an array interpolated at new_x. Add any new methods to\n the list in _clean_interp_method.", "output": "def _interpolate_scipy_wrapper(x, y, new_x, method, fill_value=None,\n bounds_error=False, order=None, **kwargs):\n \"\"\"\n Passed off to scipy.interpolate.interp1d. method is scipy's kind.\n Returns an array interpolated at new_x. Add any new methods to\n the list in _clean_interp_method.\n \"\"\"\n try:\n from scipy import interpolate\n # TODO: Why is DatetimeIndex being imported here?\n from pandas import DatetimeIndex # noqa\n except ImportError:\n raise ImportError('{method} interpolation requires SciPy'\n .format(method=method))\n\n new_x = np.asarray(new_x)\n\n # ignores some kwargs that could be passed along.\n alt_methods = {\n 'barycentric': interpolate.barycentric_interpolate,\n 'krogh': interpolate.krogh_interpolate,\n 'from_derivatives': _from_derivatives,\n 'piecewise_polynomial': _from_derivatives,\n }\n\n if getattr(x, 'is_all_dates', False):\n # GH 5975, scipy.interp1d can't hande datetime64s\n x, new_x = x._values.astype('i8'), new_x.astype('i8')\n\n if method == 'pchip':\n try:\n alt_methods['pchip'] = interpolate.pchip_interpolate\n except AttributeError:\n raise ImportError(\"Your version of Scipy does not support \"\n \"PCHIP interpolation.\")\n elif method == 'akima':\n try:\n from scipy.interpolate import Akima1DInterpolator # noqa\n alt_methods['akima'] = _akima_interpolate\n except ImportError:\n raise ImportError(\"Your version of Scipy does not support \"\n \"Akima interpolation.\")\n\n interp1d_methods = ['nearest', 'zero', 'slinear', 'quadratic', 'cubic',\n 'polynomial']\n if method in interp1d_methods:\n if method == 'polynomial':\n method = order\n terp = interpolate.interp1d(x, y, kind=method, fill_value=fill_value,\n bounds_error=bounds_error)\n new_y = terp(new_x)\n elif method == 'spline':\n # GH #10633, #24014\n if isna(order) or (order <= 0):\n raise ValueError(\"order needs to be specified and greater than 0; \"\n \"got order: {}\".format(order))\n terp = interpolate.UnivariateSpline(x, y, k=order, **kwargs)\n new_y = terp(new_x)\n else:\n # GH 7295: need to be able to write for some reason\n # in some circumstances: check all three\n if not x.flags.writeable:\n x = x.copy()\n if not y.flags.writeable:\n y = y.copy()\n if not new_x.flags.writeable:\n new_x = new_x.copy()\n method = alt_methods[method]\n new_y = method(x, y, new_x, **kwargs)\n return new_y" }, { "instruction": "Write or improve a Python function based on this description:\n\nConvenience function for interpolate.BPoly.from_derivatives.\n\n Construct a piecewise polynomial in the Bernstein basis, compatible\n with the specified values and derivatives at breakpoints.\n\n Parameters\n ----------\n xi : array_like\n sorted 1D array of x-coordinates\n yi : array_like or list of array-likes\n yi[i][j] is the j-th derivative known at xi[i]\n order: None or int or array_like of ints. Default: None.\n Specifies the degree of local polynomials. If not None, some\n derivatives are ignored.\n der : int or list\n How many derivatives to extract; None for all potentially nonzero\n derivatives (that is a number equal to the number of points), or a\n list of derivatives to extract. This numberincludes the function\n value as 0th derivative.\n extrapolate : bool, optional\n Whether to extrapolate to ouf-of-bounds points based on first and last\n intervals, or to return NaNs. Default: True.\n\n See Also\n --------\n scipy.interpolate.BPoly.from_derivatives\n\n Returns\n -------\n y : scalar or array_like\n The result, of length R or length M or M by R.", "output": "def _from_derivatives(xi, yi, x, order=None, der=0, extrapolate=False):\n \"\"\"\n Convenience function for interpolate.BPoly.from_derivatives.\n\n Construct a piecewise polynomial in the Bernstein basis, compatible\n with the specified values and derivatives at breakpoints.\n\n Parameters\n ----------\n xi : array_like\n sorted 1D array of x-coordinates\n yi : array_like or list of array-likes\n yi[i][j] is the j-th derivative known at xi[i]\n order: None or int or array_like of ints. Default: None.\n Specifies the degree of local polynomials. If not None, some\n derivatives are ignored.\n der : int or list\n How many derivatives to extract; None for all potentially nonzero\n derivatives (that is a number equal to the number of points), or a\n list of derivatives to extract. This numberincludes the function\n value as 0th derivative.\n extrapolate : bool, optional\n Whether to extrapolate to ouf-of-bounds points based on first and last\n intervals, or to return NaNs. Default: True.\n\n See Also\n --------\n scipy.interpolate.BPoly.from_derivatives\n\n Returns\n -------\n y : scalar or array_like\n The result, of length R or length M or M by R.\n \"\"\"\n from scipy import interpolate\n\n # return the method for compat with scipy version & backwards compat\n method = interpolate.BPoly.from_derivatives\n m = method(xi, yi.reshape(-1, 1),\n orders=order, extrapolate=extrapolate)\n\n return m(x)" }, { "instruction": "Write or improve a Python function based on this description:\n\nConvenience function for akima interpolation.\n xi and yi are arrays of values used to approximate some function f,\n with ``yi = f(xi)``.\n\n See `Akima1DInterpolator` for details.\n\n Parameters\n ----------\n xi : array_like\n A sorted list of x-coordinates, of length N.\n yi : array_like\n A 1-D array of real values. `yi`'s length along the interpolation\n axis must be equal to the length of `xi`. If N-D array, use axis\n parameter to select correct axis.\n x : scalar or array_like\n Of length M.\n der : int or list, optional\n How many derivatives to extract; None for all potentially\n nonzero derivatives (that is a number equal to the number\n of points), or a list of derivatives to extract. This number\n includes the function value as 0th derivative.\n axis : int, optional\n Axis in the yi array corresponding to the x-coordinate values.\n\n See Also\n --------\n scipy.interpolate.Akima1DInterpolator\n\n Returns\n -------\n y : scalar or array_like\n The result, of length R or length M or M by R,", "output": "def _akima_interpolate(xi, yi, x, der=0, axis=0):\n \"\"\"\n Convenience function for akima interpolation.\n xi and yi are arrays of values used to approximate some function f,\n with ``yi = f(xi)``.\n\n See `Akima1DInterpolator` for details.\n\n Parameters\n ----------\n xi : array_like\n A sorted list of x-coordinates, of length N.\n yi : array_like\n A 1-D array of real values. `yi`'s length along the interpolation\n axis must be equal to the length of `xi`. If N-D array, use axis\n parameter to select correct axis.\n x : scalar or array_like\n Of length M.\n der : int or list, optional\n How many derivatives to extract; None for all potentially\n nonzero derivatives (that is a number equal to the number\n of points), or a list of derivatives to extract. This number\n includes the function value as 0th derivative.\n axis : int, optional\n Axis in the yi array corresponding to the x-coordinate values.\n\n See Also\n --------\n scipy.interpolate.Akima1DInterpolator\n\n Returns\n -------\n y : scalar or array_like\n The result, of length R or length M or M by R,\n\n \"\"\"\n from scipy import interpolate\n try:\n P = interpolate.Akima1DInterpolator(xi, yi, axis=axis)\n except TypeError:\n # Scipy earlier than 0.17.0 missing axis\n P = interpolate.Akima1DInterpolator(xi, yi)\n if der == 0:\n return P(x)\n elif interpolate._isscalar(der):\n return P(x, der=der)\n else:\n return [P(x, nu) for nu in der]" }, { "instruction": "Write or improve a Python function based on this description:\n\nPerform an actual interpolation of values, values will be make 2-d if\n needed fills inplace, returns the result.", "output": "def interpolate_2d(values, method='pad', axis=0, limit=None, fill_value=None,\n dtype=None):\n \"\"\"\n Perform an actual interpolation of values, values will be make 2-d if\n needed fills inplace, returns the result.\n \"\"\"\n\n transf = (lambda x: x) if axis == 0 else (lambda x: x.T)\n\n # reshape a 1 dim if needed\n ndim = values.ndim\n if values.ndim == 1:\n if axis != 0: # pragma: no cover\n raise AssertionError(\"cannot interpolate on a ndim == 1 with \"\n \"axis != 0\")\n values = values.reshape(tuple((1,) + values.shape))\n\n if fill_value is None:\n mask = None\n else: # todo create faster fill func without masking\n mask = mask_missing(transf(values), fill_value)\n\n method = clean_fill_method(method)\n if method == 'pad':\n values = transf(pad_2d(\n transf(values), limit=limit, mask=mask, dtype=dtype))\n else:\n values = transf(backfill_2d(\n transf(values), limit=limit, mask=mask, dtype=dtype))\n\n # reshape back\n if ndim == 1:\n values = values[0]\n\n return values" }, { "instruction": "Write or improve a Python function based on this description:\n\nCast values to a dtype that algos.pad and algos.backfill can handle.", "output": "def _cast_values_for_fillna(values, dtype):\n \"\"\"\n Cast values to a dtype that algos.pad and algos.backfill can handle.\n \"\"\"\n # TODO: for int-dtypes we make a copy, but for everything else this\n # alters the values in-place. Is this intentional?\n\n if (is_datetime64_dtype(dtype) or is_datetime64tz_dtype(dtype) or\n is_timedelta64_dtype(dtype)):\n values = values.view(np.int64)\n\n elif is_integer_dtype(values):\n # NB: this check needs to come after the datetime64 check above\n values = ensure_float64(values)\n\n return values" }, { "instruction": "Write or improve a Python function based on this description:\n\nIf this is a reversed op, then flip x,y\n\n If we have an integer value (or array in y)\n and we have 0's, fill them with the fill,\n return the result.\n\n Mask the nan's from x.", "output": "def fill_zeros(result, x, y, name, fill):\n \"\"\"\n If this is a reversed op, then flip x,y\n\n If we have an integer value (or array in y)\n and we have 0's, fill them with the fill,\n return the result.\n\n Mask the nan's from x.\n \"\"\"\n if fill is None or is_float_dtype(result):\n return result\n\n if name.startswith(('r', '__r')):\n x, y = y, x\n\n is_variable_type = (hasattr(y, 'dtype') or hasattr(y, 'type'))\n is_scalar_type = is_scalar(y)\n\n if not is_variable_type and not is_scalar_type:\n return result\n\n if is_scalar_type:\n y = np.array(y)\n\n if is_integer_dtype(y):\n\n if (y == 0).any():\n\n # GH 7325, mask and nans must be broadcastable (also: PR 9308)\n # Raveling and then reshaping makes np.putmask faster\n mask = ((y == 0) & ~np.isnan(result)).ravel()\n\n shape = result.shape\n result = result.astype('float64', copy=False).ravel()\n\n np.putmask(result, mask, fill)\n\n # if we have a fill of inf, then sign it correctly\n # (GH 6178 and PR 9308)\n if np.isinf(fill):\n signs = y if name.startswith(('r', '__r')) else x\n signs = np.sign(signs.astype('float', copy=False))\n negative_inf_mask = (signs.ravel() < 0) & mask\n np.putmask(result, negative_inf_mask, -fill)\n\n if \"floordiv\" in name: # (PR 9308)\n nan_mask = ((y == 0) & (x == 0)).ravel()\n np.putmask(result, nan_mask, np.nan)\n\n result = result.reshape(shape)\n\n return result" }, { "instruction": "Write or improve a Python function based on this description:\n\nSet results of 0 / 0 or 0 // 0 to np.nan, regardless of the dtypes\n of the numerator or the denominator.\n\n Parameters\n ----------\n x : ndarray\n y : ndarray\n result : ndarray\n copy : bool (default False)\n Whether to always create a new array or try to fill in the existing\n array if possible.\n\n Returns\n -------\n filled_result : ndarray\n\n Examples\n --------\n >>> x = np.array([1, 0, -1], dtype=np.int64)\n >>> y = 0 # int 0; numpy behavior is different with float\n >>> result = x / y\n >>> result # raw numpy result does not fill division by zero\n array([0, 0, 0])\n >>> mask_zero_div_zero(x, y, result)\n array([ inf, nan, -inf])", "output": "def mask_zero_div_zero(x, y, result, copy=False):\n \"\"\"\n Set results of 0 / 0 or 0 // 0 to np.nan, regardless of the dtypes\n of the numerator or the denominator.\n\n Parameters\n ----------\n x : ndarray\n y : ndarray\n result : ndarray\n copy : bool (default False)\n Whether to always create a new array or try to fill in the existing\n array if possible.\n\n Returns\n -------\n filled_result : ndarray\n\n Examples\n --------\n >>> x = np.array([1, 0, -1], dtype=np.int64)\n >>> y = 0 # int 0; numpy behavior is different with float\n >>> result = x / y\n >>> result # raw numpy result does not fill division by zero\n array([0, 0, 0])\n >>> mask_zero_div_zero(x, y, result)\n array([ inf, nan, -inf])\n \"\"\"\n if is_scalar(y):\n y = np.array(y)\n\n zmask = y == 0\n if zmask.any():\n shape = result.shape\n\n nan_mask = (zmask & (x == 0)).ravel()\n neginf_mask = (zmask & (x < 0)).ravel()\n posinf_mask = (zmask & (x > 0)).ravel()\n\n if nan_mask.any() or neginf_mask.any() or posinf_mask.any():\n # Fill negative/0 with -inf, positive/0 with +inf, 0/0 with NaN\n result = result.astype('float64', copy=copy).ravel()\n\n np.putmask(result, nan_mask, np.nan)\n np.putmask(result, posinf_mask, np.inf)\n np.putmask(result, neginf_mask, -np.inf)\n\n result = result.reshape(shape)\n\n return result" }, { "instruction": "Write or improve a Python function based on this description:\n\nFill nulls caused by division by zero, casting to a diffferent dtype\n if necessary.\n\n Parameters\n ----------\n op : function (operator.add, operator.div, ...)\n left : object (Index for non-reversed ops)\n right : object (Index fof reversed ops)\n result : ndarray\n\n Returns\n -------\n result : ndarray", "output": "def dispatch_missing(op, left, right, result):\n \"\"\"\n Fill nulls caused by division by zero, casting to a diffferent dtype\n if necessary.\n\n Parameters\n ----------\n op : function (operator.add, operator.div, ...)\n left : object (Index for non-reversed ops)\n right : object (Index fof reversed ops)\n result : ndarray\n\n Returns\n -------\n result : ndarray\n \"\"\"\n opstr = '__{opname}__'.format(opname=op.__name__).replace('____', '__')\n if op in [operator.truediv, operator.floordiv,\n getattr(operator, 'div', None)]:\n result = mask_zero_div_zero(left, right, result)\n elif op is operator.mod:\n result = fill_zeros(result, left, right, opstr, np.nan)\n elif op is divmod:\n res0 = mask_zero_div_zero(left, right, result[0])\n res1 = fill_zeros(result[1], left, right, opstr, np.nan)\n result = (res0, res1)\n return result" }, { "instruction": "Write or improve a Python function based on this description:\n\nGet indexers of values that won't be filled\n because they exceed the limits.\n\n Parameters\n ----------\n invalid : boolean ndarray\n fw_limit : int or None\n forward limit to index\n bw_limit : int or None\n backward limit to index\n\n Returns\n -------\n set of indexers\n\n Notes\n -----\n This is equivalent to the more readable, but slower\n\n .. code-block:: python\n\n def _interp_limit(invalid, fw_limit, bw_limit):\n for x in np.where(invalid)[0]:\n if invalid[max(0, x - fw_limit):x + bw_limit + 1].all():\n yield x", "output": "def _interp_limit(invalid, fw_limit, bw_limit):\n \"\"\"\n Get indexers of values that won't be filled\n because they exceed the limits.\n\n Parameters\n ----------\n invalid : boolean ndarray\n fw_limit : int or None\n forward limit to index\n bw_limit : int or None\n backward limit to index\n\n Returns\n -------\n set of indexers\n\n Notes\n -----\n This is equivalent to the more readable, but slower\n\n .. code-block:: python\n\n def _interp_limit(invalid, fw_limit, bw_limit):\n for x in np.where(invalid)[0]:\n if invalid[max(0, x - fw_limit):x + bw_limit + 1].all():\n yield x\n \"\"\"\n # handle forward first; the backward direction is the same except\n # 1. operate on the reversed array\n # 2. subtract the returned indices from N - 1\n N = len(invalid)\n f_idx = set()\n b_idx = set()\n\n def inner(invalid, limit):\n limit = min(limit, N)\n windowed = _rolling_window(invalid, limit + 1).all(1)\n idx = (set(np.where(windowed)[0] + limit) |\n set(np.where((~invalid[:limit + 1]).cumsum() == 0)[0]))\n return idx\n\n if fw_limit is not None:\n\n if fw_limit == 0:\n f_idx = set(np.where(invalid)[0])\n else:\n f_idx = inner(invalid, fw_limit)\n\n if bw_limit is not None:\n\n if bw_limit == 0:\n # then we don't even need to care about backwards\n # just use forwards\n return f_idx\n else:\n b_idx = list(inner(invalid[::-1], bw_limit))\n b_idx = set(N - 1 - np.asarray(b_idx))\n if fw_limit == 0:\n return b_idx\n\n return f_idx & b_idx" }, { "instruction": "Write or improve a Python function based on this description:\n\n[True, True, False, True, False], 2 ->\n\n [\n [True, True],\n [True, False],\n [False, True],\n [True, False],\n ]", "output": "def _rolling_window(a, window):\n \"\"\"\n [True, True, False, True, False], 2 ->\n\n [\n [True, True],\n [True, False],\n [False, True],\n [True, False],\n ]\n \"\"\"\n # https://stackoverflow.com/a/6811241\n shape = a.shape[:-1] + (a.shape[-1] - window + 1, window)\n strides = a.strides + (a.strides[-1],)\n return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn console size as tuple = (width, height).\n\n Returns (None,None) in non-interactive session.", "output": "def get_console_size():\n \"\"\"Return console size as tuple = (width, height).\n\n Returns (None,None) in non-interactive session.\n \"\"\"\n from pandas import get_option\n\n display_width = get_option('display.width')\n # deprecated.\n display_height = get_option('display.max_rows')\n\n # Consider\n # interactive shell terminal, can detect term size\n # interactive non-shell terminal (ipnb/ipqtconsole), cannot detect term\n # size non-interactive script, should disregard term size\n\n # in addition\n # width,height have default values, but setting to 'None' signals\n # should use Auto-Detection, But only in interactive shell-terminal.\n # Simple. yeah.\n\n if in_interactive_session():\n if in_ipython_frontend():\n # sane defaults for interactive non-shell terminal\n # match default for width,height in config_init\n from pandas._config.config import get_default_val\n terminal_width = get_default_val('display.width')\n terminal_height = get_default_val('display.max_rows')\n else:\n # pure terminal\n terminal_width, terminal_height = get_terminal_size()\n else:\n terminal_width, terminal_height = None, None\n\n # Note if the User sets width/Height to None (auto-detection)\n # and we're in a script (non-inter), this will return (None,None)\n # caller needs to deal.\n return (display_width or terminal_width, display_height or terminal_height)" }, { "instruction": "Write or improve a Python function based on this description:\n\ncheck if we're running in an interactive shell\n\n returns True if running under python/ipython interactive shell", "output": "def in_interactive_session():\n \"\"\" check if we're running in an interactive shell\n\n returns True if running under python/ipython interactive shell\n \"\"\"\n from pandas import get_option\n\n def check_main():\n try:\n import __main__ as main\n except ModuleNotFoundError:\n return get_option('mode.sim_interactive')\n return (not hasattr(main, '__file__') or\n get_option('mode.sim_interactive'))\n\n try:\n return __IPYTHON__ or check_main() # noqa\n except NameError:\n return check_main()" }, { "instruction": "Write or improve a Python function based on this description:\n\nCode the categories to ensure we can groupby for categoricals.\n\n If observed=True, we return a new Categorical with the observed\n categories only.\n\n If sort=False, return a copy of self, coded with categories as\n returned by .unique(), followed by any categories not appearing in\n the data. If sort=True, return self.\n\n This method is needed solely to ensure the categorical index of the\n GroupBy result has categories in the order of appearance in the data\n (GH-8868).\n\n Parameters\n ----------\n c : Categorical\n sort : boolean\n The value of the sort parameter groupby was called with.\n observed : boolean\n Account only for the observed values\n\n Returns\n -------\n New Categorical\n If sort=False, the new categories are set to the order of\n appearance in codes (unless ordered=True, in which case the\n original order is preserved), followed by any unrepresented\n categories in the original order.\n Categorical or None\n If we are observed, return the original categorical, otherwise None", "output": "def recode_for_groupby(c, sort, observed):\n \"\"\"\n Code the categories to ensure we can groupby for categoricals.\n\n If observed=True, we return a new Categorical with the observed\n categories only.\n\n If sort=False, return a copy of self, coded with categories as\n returned by .unique(), followed by any categories not appearing in\n the data. If sort=True, return self.\n\n This method is needed solely to ensure the categorical index of the\n GroupBy result has categories in the order of appearance in the data\n (GH-8868).\n\n Parameters\n ----------\n c : Categorical\n sort : boolean\n The value of the sort parameter groupby was called with.\n observed : boolean\n Account only for the observed values\n\n Returns\n -------\n New Categorical\n If sort=False, the new categories are set to the order of\n appearance in codes (unless ordered=True, in which case the\n original order is preserved), followed by any unrepresented\n categories in the original order.\n Categorical or None\n If we are observed, return the original categorical, otherwise None\n \"\"\"\n\n # we only care about observed values\n if observed:\n unique_codes = unique1d(c.codes)\n\n take_codes = unique_codes[unique_codes != -1]\n if c.ordered:\n take_codes = np.sort(take_codes)\n\n # we recode according to the uniques\n categories = c.categories.take(take_codes)\n codes = _recode_for_categories(c.codes,\n c.categories,\n categories)\n\n # return a new categorical that maps our new codes\n # and categories\n dtype = CategoricalDtype(categories, ordered=c.ordered)\n return Categorical(codes, dtype=dtype, fastpath=True), c\n\n # Already sorted according to c.categories; all is fine\n if sort:\n return c, None\n\n # sort=False should order groups in as-encountered order (GH-8868)\n cat = c.unique()\n\n # But for groupby to work, all categories should be present,\n # including those missing from the data (GH-13179), which .unique()\n # above dropped\n cat = cat.add_categories(\n c.categories[~c.categories.isin(cat.categories)])\n\n return c.reorder_categories(cat.categories), None" }, { "instruction": "Write or improve a Python function based on this description:\n\nReverse the codes_to_groupby to account for sort / observed.\n\n Parameters\n ----------\n c : Categorical\n sort : boolean\n The value of the sort parameter groupby was called with.\n ci : CategoricalIndex\n The codes / categories to recode\n\n Returns\n -------\n CategoricalIndex", "output": "def recode_from_groupby(c, sort, ci):\n \"\"\"\n Reverse the codes_to_groupby to account for sort / observed.\n\n Parameters\n ----------\n c : Categorical\n sort : boolean\n The value of the sort parameter groupby was called with.\n ci : CategoricalIndex\n The codes / categories to recode\n\n Returns\n -------\n CategoricalIndex\n \"\"\"\n\n # we re-order to the original category orderings\n if sort:\n return ci.set_categories(c.categories)\n\n # we are not sorting, so add unobserved to the end\n return ci.add_categories(\n c.categories[~c.categories.isin(ci.categories)])" }, { "instruction": "Write or improve a Python function based on this description:\n\nreturn our implementation", "output": "def get_engine(engine):\n \"\"\" return our implementation \"\"\"\n\n if engine == 'auto':\n engine = get_option('io.parquet.engine')\n\n if engine == 'auto':\n # try engines in this order\n try:\n return PyArrowImpl()\n except ImportError:\n pass\n\n try:\n return FastParquetImpl()\n except ImportError:\n pass\n\n raise ImportError(\"Unable to find a usable engine; \"\n \"tried using: 'pyarrow', 'fastparquet'.\\n\"\n \"pyarrow or fastparquet is required for parquet \"\n \"support\")\n\n if engine not in ['pyarrow', 'fastparquet']:\n raise ValueError(\"engine must be one of 'pyarrow', 'fastparquet'\")\n\n if engine == 'pyarrow':\n return PyArrowImpl()\n elif engine == 'fastparquet':\n return FastParquetImpl()" }, { "instruction": "Write or improve a Python function based on this description:\n\nWrite a DataFrame to the parquet format.\n\n Parameters\n ----------\n path : str\n File path or Root Directory path. Will be used as Root Directory path\n while writing a partitioned dataset.\n\n .. versionchanged:: 0.24.0\n\n engine : {'auto', 'pyarrow', 'fastparquet'}, default 'auto'\n Parquet library to use. If 'auto', then the option\n ``io.parquet.engine`` is used. The default ``io.parquet.engine``\n behavior is to try 'pyarrow', falling back to 'fastparquet' if\n 'pyarrow' is unavailable.\n compression : {'snappy', 'gzip', 'brotli', None}, default 'snappy'\n Name of the compression to use. Use ``None`` for no compression.\n index : bool, default None\n If ``True``, include the dataframe's index(es) in the file output. If\n ``False``, they will not be written to the file. If ``None``, the\n engine's default behavior will be used.\n\n .. versionadded 0.24.0\n\n partition_cols : list, optional, default None\n Column names by which to partition the dataset\n Columns are partitioned in the order they are given\n\n .. versionadded:: 0.24.0\n\n kwargs\n Additional keyword arguments passed to the engine", "output": "def to_parquet(df, path, engine='auto', compression='snappy', index=None,\n partition_cols=None, **kwargs):\n \"\"\"\n Write a DataFrame to the parquet format.\n\n Parameters\n ----------\n path : str\n File path or Root Directory path. Will be used as Root Directory path\n while writing a partitioned dataset.\n\n .. versionchanged:: 0.24.0\n\n engine : {'auto', 'pyarrow', 'fastparquet'}, default 'auto'\n Parquet library to use. If 'auto', then the option\n ``io.parquet.engine`` is used. The default ``io.parquet.engine``\n behavior is to try 'pyarrow', falling back to 'fastparquet' if\n 'pyarrow' is unavailable.\n compression : {'snappy', 'gzip', 'brotli', None}, default 'snappy'\n Name of the compression to use. Use ``None`` for no compression.\n index : bool, default None\n If ``True``, include the dataframe's index(es) in the file output. If\n ``False``, they will not be written to the file. If ``None``, the\n engine's default behavior will be used.\n\n .. versionadded 0.24.0\n\n partition_cols : list, optional, default None\n Column names by which to partition the dataset\n Columns are partitioned in the order they are given\n\n .. versionadded:: 0.24.0\n\n kwargs\n Additional keyword arguments passed to the engine\n \"\"\"\n impl = get_engine(engine)\n return impl.write(df, path, compression=compression, index=index,\n partition_cols=partition_cols, **kwargs)" }, { "instruction": "Write or improve a Python function based on this description:\n\nLoad a parquet object from the file path, returning a DataFrame.\n\n .. versionadded 0.21.0\n\n Parameters\n ----------\n path : string\n File path\n engine : {'auto', 'pyarrow', 'fastparquet'}, default 'auto'\n Parquet library to use. If 'auto', then the option\n ``io.parquet.engine`` is used. The default ``io.parquet.engine``\n behavior is to try 'pyarrow', falling back to 'fastparquet' if\n 'pyarrow' is unavailable.\n columns : list, default=None\n If not None, only these columns will be read from the file.\n\n .. versionadded 0.21.1\n **kwargs\n Any additional kwargs are passed to the engine.\n\n Returns\n -------\n DataFrame", "output": "def read_parquet(path, engine='auto', columns=None, **kwargs):\n \"\"\"\n Load a parquet object from the file path, returning a DataFrame.\n\n .. versionadded 0.21.0\n\n Parameters\n ----------\n path : string\n File path\n engine : {'auto', 'pyarrow', 'fastparquet'}, default 'auto'\n Parquet library to use. If 'auto', then the option\n ``io.parquet.engine`` is used. The default ``io.parquet.engine``\n behavior is to try 'pyarrow', falling back to 'fastparquet' if\n 'pyarrow' is unavailable.\n columns : list, default=None\n If not None, only these columns will be read from the file.\n\n .. versionadded 0.21.1\n **kwargs\n Any additional kwargs are passed to the engine.\n\n Returns\n -------\n DataFrame\n \"\"\"\n\n impl = get_engine(engine)\n return impl.read(path, columns=columns, **kwargs)" }, { "instruction": "Write or improve a Python function based on this description:\n\nGenerate bin edge offsets and bin labels for one array using another array\n which has bin edge values. Both arrays must be sorted.\n\n Parameters\n ----------\n values : array of values\n binner : a comparable array of values representing bins into which to bin\n the first array. Note, 'values' end-points must fall within 'binner'\n end-points.\n closed : which end of bin is closed; left (default), right\n\n Returns\n -------\n bins : array of offsets (into 'values' argument) of bins.\n Zero and last edge are excluded in result, so for instance the first\n bin is values[0:bin[0]] and the last is values[bin[-1]:]", "output": "def generate_bins_generic(values, binner, closed):\n \"\"\"\n Generate bin edge offsets and bin labels for one array using another array\n which has bin edge values. Both arrays must be sorted.\n\n Parameters\n ----------\n values : array of values\n binner : a comparable array of values representing bins into which to bin\n the first array. Note, 'values' end-points must fall within 'binner'\n end-points.\n closed : which end of bin is closed; left (default), right\n\n Returns\n -------\n bins : array of offsets (into 'values' argument) of bins.\n Zero and last edge are excluded in result, so for instance the first\n bin is values[0:bin[0]] and the last is values[bin[-1]:]\n \"\"\"\n lenidx = len(values)\n lenbin = len(binner)\n\n if lenidx <= 0 or lenbin <= 0:\n raise ValueError(\"Invalid length for values or for binner\")\n\n # check binner fits data\n if values[0] < binner[0]:\n raise ValueError(\"Values falls before first bin\")\n\n if values[lenidx - 1] > binner[lenbin - 1]:\n raise ValueError(\"Values falls after last bin\")\n\n bins = np.empty(lenbin - 1, dtype=np.int64)\n\n j = 0 # index into values\n bc = 0 # bin count\n\n # linear scan, presume nothing about values/binner except that it fits ok\n for i in range(0, lenbin - 1):\n r_bin = binner[i + 1]\n\n # count values in current bin, advance to next bin\n while j < lenidx and (values[j] < r_bin or\n (closed == 'right' and values[j] == r_bin)):\n j += 1\n\n bins[bc] = j\n bc += 1\n\n return bins" }, { "instruction": "Write or improve a Python function based on this description:\n\nGroupby iterator\n\n Returns\n -------\n Generator yielding sequence of (name, subsetted object)\n for each group", "output": "def get_iterator(self, data, axis=0):\n \"\"\"\n Groupby iterator\n\n Returns\n -------\n Generator yielding sequence of (name, subsetted object)\n for each group\n \"\"\"\n splitter = self._get_splitter(data, axis=axis)\n keys = self._get_group_keys()\n for key, (i, group) in zip(keys, splitter):\n yield key, group" }, { "instruction": "Write or improve a Python function based on this description:\n\ndict {group name -> group indices}", "output": "def indices(self):\n \"\"\" dict {group name -> group indices} \"\"\"\n if len(self.groupings) == 1:\n return self.groupings[0].indices\n else:\n label_list = [ping.labels for ping in self.groupings]\n keys = [com.values_from_object(ping.group_index)\n for ping in self.groupings]\n return get_indexer_dict(label_list, keys)" }, { "instruction": "Write or improve a Python function based on this description:\n\nCompute group sizes", "output": "def size(self):\n \"\"\"\n Compute group sizes\n\n \"\"\"\n ids, _, ngroup = self.group_info\n ids = ensure_platform_int(ids)\n if ngroup:\n out = np.bincount(ids[ids != -1], minlength=ngroup)\n else:\n out = []\n return Series(out,\n index=self.result_index,\n dtype='int64')" }, { "instruction": "Write or improve a Python function based on this description:\n\ndict {group name -> group labels}", "output": "def groups(self):\n \"\"\" dict {group name -> group labels} \"\"\"\n if len(self.groupings) == 1:\n return self.groupings[0].groups\n else:\n to_groupby = lzip(*(ping.grouper for ping in self.groupings))\n to_groupby = Index(to_groupby)\n return self.axis.groupby(to_groupby)" }, { "instruction": "Write or improve a Python function based on this description:\n\ndict {group name -> group labels}", "output": "def groups(self):\n \"\"\" dict {group name -> group labels} \"\"\"\n\n # this is mainly for compat\n # GH 3881\n result = {key: value for key, value in zip(self.binlabels, self.bins)\n if key is not NaT}\n return result" }, { "instruction": "Write or improve a Python function based on this description:\n\nGroupby iterator\n\n Returns\n -------\n Generator yielding sequence of (name, subsetted object)\n for each group", "output": "def get_iterator(self, data, axis=0):\n \"\"\"\n Groupby iterator\n\n Returns\n -------\n Generator yielding sequence of (name, subsetted object)\n for each group\n \"\"\"\n if isinstance(data, NDFrame):\n slicer = lambda start, edge: data._slice(\n slice(start, edge), axis=axis)\n length = len(data.axes[axis])\n else:\n slicer = lambda start, edge: data[slice(start, edge)]\n length = len(data)\n\n start = 0\n for edge, label in zip(self.bins, self.binlabels):\n if label is not NaT:\n yield label, slicer(start, edge)\n start = edge\n\n if start < length:\n yield self.binlabels[-1], slicer(start, None)" }, { "instruction": "Write or improve a Python function based on this description:\n\nNormalize semi-structured JSON data into a flat table.\n\n Parameters\n ----------\n data : dict or list of dicts\n Unserialized JSON objects\n record_path : string or list of strings, default None\n Path in each object to list of records. If not passed, data will be\n assumed to be an array of records\n meta : list of paths (string or list of strings), default None\n Fields to use as metadata for each record in resulting table\n meta_prefix : string, default None\n record_prefix : string, default None\n If True, prefix records with dotted (?) path, e.g. foo.bar.field if\n path to records is ['foo', 'bar']\n errors : {'raise', 'ignore'}, default 'raise'\n\n * 'ignore' : will ignore KeyError if keys listed in meta are not\n always present\n * 'raise' : will raise KeyError if keys listed in meta are not\n always present\n\n .. versionadded:: 0.20.0\n\n sep : string, default '.'\n Nested records will generate names separated by sep,\n e.g., for sep='.', { 'foo' : { 'bar' : 0 } } -> foo.bar\n\n .. versionadded:: 0.20.0\n\n Returns\n -------\n frame : DataFrame\n\n Examples\n --------\n\n >>> from pandas.io.json import json_normalize\n >>> data = [{'id': 1, 'name': {'first': 'Coleen', 'last': 'Volk'}},\n ... {'name': {'given': 'Mose', 'family': 'Regner'}},\n ... {'id': 2, 'name': 'Faye Raker'}]\n >>> json_normalize(data)\n id name name.family name.first name.given name.last\n 0 1.0 NaN NaN Coleen NaN Volk\n 1 NaN NaN Regner NaN Mose NaN\n 2 2.0 Faye Raker NaN NaN NaN NaN\n\n >>> data = [{'state': 'Florida',\n ... 'shortname': 'FL',\n ... 'info': {\n ... 'governor': 'Rick Scott'\n ... },\n ... 'counties': [{'name': 'Dade', 'population': 12345},\n ... {'name': 'Broward', 'population': 40000},\n ... {'name': 'Palm Beach', 'population': 60000}]},\n ... {'state': 'Ohio',\n ... 'shortname': 'OH',\n ... 'info': {\n ... 'governor': 'John Kasich'\n ... },\n ... 'counties': [{'name': 'Summit', 'population': 1234},\n ... {'name': 'Cuyahoga', 'population': 1337}]}]\n >>> result = json_normalize(data, 'counties', ['state', 'shortname',\n ... ['info', 'governor']])\n >>> result\n name population info.governor state shortname\n 0 Dade 12345 Rick Scott Florida FL\n 1 Broward 40000 Rick Scott Florida FL\n 2 Palm Beach 60000 Rick Scott Florida FL\n 3 Summit 1234 John Kasich Ohio OH\n 4 Cuyahoga 1337 John Kasich Ohio OH\n\n >>> data = {'A': [1, 2]}\n >>> json_normalize(data, 'A', record_prefix='Prefix.')\n Prefix.0\n 0 1\n 1 2", "output": "def json_normalize(data, record_path=None, meta=None,\n meta_prefix=None,\n record_prefix=None,\n errors='raise',\n sep='.'):\n \"\"\"\n Normalize semi-structured JSON data into a flat table.\n\n Parameters\n ----------\n data : dict or list of dicts\n Unserialized JSON objects\n record_path : string or list of strings, default None\n Path in each object to list of records. If not passed, data will be\n assumed to be an array of records\n meta : list of paths (string or list of strings), default None\n Fields to use as metadata for each record in resulting table\n meta_prefix : string, default None\n record_prefix : string, default None\n If True, prefix records with dotted (?) path, e.g. foo.bar.field if\n path to records is ['foo', 'bar']\n errors : {'raise', 'ignore'}, default 'raise'\n\n * 'ignore' : will ignore KeyError if keys listed in meta are not\n always present\n * 'raise' : will raise KeyError if keys listed in meta are not\n always present\n\n .. versionadded:: 0.20.0\n\n sep : string, default '.'\n Nested records will generate names separated by sep,\n e.g., for sep='.', { 'foo' : { 'bar' : 0 } } -> foo.bar\n\n .. versionadded:: 0.20.0\n\n Returns\n -------\n frame : DataFrame\n\n Examples\n --------\n\n >>> from pandas.io.json import json_normalize\n >>> data = [{'id': 1, 'name': {'first': 'Coleen', 'last': 'Volk'}},\n ... {'name': {'given': 'Mose', 'family': 'Regner'}},\n ... {'id': 2, 'name': 'Faye Raker'}]\n >>> json_normalize(data)\n id name name.family name.first name.given name.last\n 0 1.0 NaN NaN Coleen NaN Volk\n 1 NaN NaN Regner NaN Mose NaN\n 2 2.0 Faye Raker NaN NaN NaN NaN\n\n >>> data = [{'state': 'Florida',\n ... 'shortname': 'FL',\n ... 'info': {\n ... 'governor': 'Rick Scott'\n ... },\n ... 'counties': [{'name': 'Dade', 'population': 12345},\n ... {'name': 'Broward', 'population': 40000},\n ... {'name': 'Palm Beach', 'population': 60000}]},\n ... {'state': 'Ohio',\n ... 'shortname': 'OH',\n ... 'info': {\n ... 'governor': 'John Kasich'\n ... },\n ... 'counties': [{'name': 'Summit', 'population': 1234},\n ... {'name': 'Cuyahoga', 'population': 1337}]}]\n >>> result = json_normalize(data, 'counties', ['state', 'shortname',\n ... ['info', 'governor']])\n >>> result\n name population info.governor state shortname\n 0 Dade 12345 Rick Scott Florida FL\n 1 Broward 40000 Rick Scott Florida FL\n 2 Palm Beach 60000 Rick Scott Florida FL\n 3 Summit 1234 John Kasich Ohio OH\n 4 Cuyahoga 1337 John Kasich Ohio OH\n\n >>> data = {'A': [1, 2]}\n >>> json_normalize(data, 'A', record_prefix='Prefix.')\n Prefix.0\n 0 1\n 1 2\n \"\"\"\n def _pull_field(js, spec):\n result = js\n if isinstance(spec, list):\n for field in spec:\n result = result[field]\n else:\n result = result[spec]\n\n return result\n\n if isinstance(data, list) and not data:\n return DataFrame()\n\n # A bit of a hackjob\n if isinstance(data, dict):\n data = [data]\n\n if record_path is None:\n if any([isinstance(x, dict) for x in y.values()] for y in data):\n # naive normalization, this is idempotent for flat records\n # and potentially will inflate the data considerably for\n # deeply nested structures:\n # {VeryLong: { b: 1,c:2}} -> {VeryLong.b:1 ,VeryLong.c:@}\n #\n # TODO: handle record value which are lists, at least error\n # reasonably\n data = nested_to_record(data, sep=sep)\n return DataFrame(data)\n elif not isinstance(record_path, list):\n record_path = [record_path]\n\n if meta is None:\n meta = []\n elif not isinstance(meta, list):\n meta = [meta]\n\n meta = [m if isinstance(m, list) else [m] for m in meta]\n\n # Disastrously inefficient for now\n records = []\n lengths = []\n\n meta_vals = defaultdict(list)\n if not isinstance(sep, str):\n sep = str(sep)\n meta_keys = [sep.join(val) for val in meta]\n\n def _recursive_extract(data, path, seen_meta, level=0):\n if isinstance(data, dict):\n data = [data]\n if len(path) > 1:\n for obj in data:\n for val, key in zip(meta, meta_keys):\n if level + 1 == len(val):\n seen_meta[key] = _pull_field(obj, val[-1])\n\n _recursive_extract(obj[path[0]], path[1:],\n seen_meta, level=level + 1)\n else:\n for obj in data:\n recs = _pull_field(obj, path[0])\n\n # For repeating the metadata later\n lengths.append(len(recs))\n\n for val, key in zip(meta, meta_keys):\n if level + 1 > len(val):\n meta_val = seen_meta[key]\n else:\n try:\n meta_val = _pull_field(obj, val[level:])\n except KeyError as e:\n if errors == 'ignore':\n meta_val = np.nan\n else:\n raise KeyError(\"Try running with \"\n \"errors='ignore' as key \"\n \"{err} is not always present\"\n .format(err=e))\n meta_vals[key].append(meta_val)\n\n records.extend(recs)\n\n _recursive_extract(data, record_path, {}, level=0)\n\n result = DataFrame(records)\n\n if record_prefix is not None:\n result = result.rename(\n columns=lambda x: \"{p}{c}\".format(p=record_prefix, c=x))\n\n # Data types, a problem\n for k, v in meta_vals.items():\n if meta_prefix is not None:\n k = meta_prefix + k\n\n if k in result:\n raise ValueError('Conflicting metadata name {name}, '\n 'need distinguishing prefix '.format(name=k))\n\n # forcing dtype to object to avoid the metadata being casted to string\n result[k] = np.array(v, dtype=object).repeat(lengths)\n\n return result" }, { "instruction": "Write or improve a Python function based on this description:\n\nReshape long-format data to wide. Generalized inverse of DataFrame.pivot\n\n Parameters\n ----------\n data : DataFrame\n groups : dict\n {new_name : list_of_columns}\n dropna : boolean, default True\n\n Examples\n --------\n >>> data = pd.DataFrame({'hr1': [514, 573], 'hr2': [545, 526],\n ... 'team': ['Red Sox', 'Yankees'],\n ... 'year1': [2007, 2007], 'year2': [2008, 2008]})\n >>> data\n hr1 hr2 team year1 year2\n 0 514 545 Red Sox 2007 2008\n 1 573 526 Yankees 2007 2008\n\n >>> pd.lreshape(data, {'year': ['year1', 'year2'], 'hr': ['hr1', 'hr2']})\n team year hr\n 0 Red Sox 2007 514\n 1 Yankees 2007 573\n 2 Red Sox 2008 545\n 3 Yankees 2008 526\n\n Returns\n -------\n reshaped : DataFrame", "output": "def lreshape(data, groups, dropna=True, label=None):\n \"\"\"\n Reshape long-format data to wide. Generalized inverse of DataFrame.pivot\n\n Parameters\n ----------\n data : DataFrame\n groups : dict\n {new_name : list_of_columns}\n dropna : boolean, default True\n\n Examples\n --------\n >>> data = pd.DataFrame({'hr1': [514, 573], 'hr2': [545, 526],\n ... 'team': ['Red Sox', 'Yankees'],\n ... 'year1': [2007, 2007], 'year2': [2008, 2008]})\n >>> data\n hr1 hr2 team year1 year2\n 0 514 545 Red Sox 2007 2008\n 1 573 526 Yankees 2007 2008\n\n >>> pd.lreshape(data, {'year': ['year1', 'year2'], 'hr': ['hr1', 'hr2']})\n team year hr\n 0 Red Sox 2007 514\n 1 Yankees 2007 573\n 2 Red Sox 2008 545\n 3 Yankees 2008 526\n\n Returns\n -------\n reshaped : DataFrame\n \"\"\"\n if isinstance(groups, dict):\n keys = list(groups.keys())\n values = list(groups.values())\n else:\n keys, values = zip(*groups)\n\n all_cols = list(set.union(*[set(x) for x in values]))\n id_cols = list(data.columns.difference(all_cols))\n\n K = len(values[0])\n\n for seq in values:\n if len(seq) != K:\n raise ValueError('All column lists must be same length')\n\n mdata = {}\n pivot_cols = []\n\n for target, names in zip(keys, values):\n to_concat = [data[col].values for col in names]\n\n import pandas.core.dtypes.concat as _concat\n mdata[target] = _concat._concat_compat(to_concat)\n pivot_cols.append(target)\n\n for col in id_cols:\n mdata[col] = np.tile(data[col].values, K)\n\n if dropna:\n mask = np.ones(len(mdata[pivot_cols[0]]), dtype=bool)\n for c in pivot_cols:\n mask &= notna(mdata[c])\n if not mask.all():\n mdata = {k: v[mask] for k, v in mdata.items()}\n\n return data._constructor(mdata, columns=id_cols + pivot_cols)" }, { "instruction": "Write or improve a Python function based on this description:\n\nr\"\"\"\n Wide panel to long format. Less flexible but more user-friendly than melt.\n\n With stubnames ['A', 'B'], this function expects to find one or more\n group of columns with format\n A-suffix1, A-suffix2,..., B-suffix1, B-suffix2,...\n You specify what you want to call this suffix in the resulting long format\n with `j` (for example `j='year'`)\n\n Each row of these wide variables are assumed to be uniquely identified by\n `i` (can be a single column name or a list of column names)\n\n All remaining variables in the data frame are left intact.\n\n Parameters\n ----------\n df : DataFrame\n The wide-format DataFrame\n stubnames : str or list-like\n The stub name(s). The wide format variables are assumed to\n start with the stub names.\n i : str or list-like\n Column(s) to use as id variable(s)\n j : str\n The name of the sub-observation variable. What you wish to name your\n suffix in the long format.\n sep : str, default \"\"\n A character indicating the separation of the variable names\n in the wide format, to be stripped from the names in the long format.\n For example, if your column names are A-suffix1, A-suffix2, you\n can strip the hyphen by specifying `sep='-'`\n\n .. versionadded:: 0.20.0\n\n suffix : str, default '\\\\d+'\n A regular expression capturing the wanted suffixes. '\\\\d+' captures\n numeric suffixes. Suffixes with no numbers could be specified with the\n negated character class '\\\\D+'. You can also further disambiguate\n suffixes, for example, if your wide variables are of the form\n A-one, B-two,.., and you have an unrelated column A-rating, you can\n ignore the last one by specifying `suffix='(!?one|two)'`\n\n .. versionadded:: 0.20.0\n\n .. versionchanged:: 0.23.0\n When all suffixes are numeric, they are cast to int64/float64.\n\n Returns\n -------\n DataFrame\n A DataFrame that contains each stub name as a variable, with new index\n (i, j).\n\n Notes\n -----\n All extra variables are left untouched. This simply uses\n `pandas.melt` under the hood, but is hard-coded to \"do the right thing\"\n in a typical case.\n\n Examples\n --------\n >>> np.random.seed(123)\n >>> df = pd.DataFrame({\"A1970\" : {0 : \"a\", 1 : \"b\", 2 : \"c\"},\n ... \"A1980\" : {0 : \"d\", 1 : \"e\", 2 : \"f\"},\n ... \"B1970\" : {0 : 2.5, 1 : 1.2, 2 : .7},\n ... \"B1980\" : {0 : 3.2, 1 : 1.3, 2 : .1},\n ... \"X\" : dict(zip(range(3), np.random.randn(3)))\n ... })\n >>> df[\"id\"] = df.index\n >>> df\n A1970 A1980 B1970 B1980 X id\n 0 a d 2.5 3.2 -1.085631 0\n 1 b e 1.2 1.3 0.997345 1\n 2 c f 0.7 0.1 0.282978 2\n >>> pd.wide_to_long(df, [\"A\", \"B\"], i=\"id\", j=\"year\")\n ... # doctest: +NORMALIZE_WHITESPACE\n X A B\n id year\n 0 1970 -1.085631 a 2.5\n 1 1970 0.997345 b 1.2\n 2 1970 0.282978 c 0.7\n 0 1980 -1.085631 d 3.2\n 1 1980 0.997345 e 1.3\n 2 1980 0.282978 f 0.1\n\n With multiple id columns\n\n >>> df = pd.DataFrame({\n ... 'famid': [1, 1, 1, 2, 2, 2, 3, 3, 3],\n ... 'birth': [1, 2, 3, 1, 2, 3, 1, 2, 3],\n ... 'ht1': [2.8, 2.9, 2.2, 2, 1.8, 1.9, 2.2, 2.3, 2.1],\n ... 'ht2': [3.4, 3.8, 2.9, 3.2, 2.8, 2.4, 3.3, 3.4, 2.9]\n ... })\n >>> df\n birth famid ht1 ht2\n 0 1 1 2.8 3.4\n 1 2 1 2.9 3.8\n 2 3 1 2.2 2.9\n 3 1 2 2.0 3.2\n 4 2 2 1.8 2.8\n 5 3 2 1.9 2.4\n 6 1 3 2.2 3.3\n 7 2 3 2.3 3.4\n 8 3 3 2.1 2.9\n >>> l = pd.wide_to_long(df, stubnames='ht', i=['famid', 'birth'], j='age')\n >>> l\n ... # doctest: +NORMALIZE_WHITESPACE\n ht\n famid birth age\n 1 1 1 2.8\n 2 3.4\n 2 1 2.9\n 2 3.8\n 3 1 2.2\n 2 2.9\n 2 1 1 2.0\n 2 3.2\n 2 1 1.8\n 2 2.8\n 3 1 1.9\n 2 2.4\n 3 1 1 2.2\n 2 3.3\n 2 1 2.3\n 2 3.4\n 3 1 2.1\n 2 2.9\n\n Going from long back to wide just takes some creative use of `unstack`\n\n >>> w = l.unstack()\n >>> w.columns = w.columns.map('{0[0]}{0[1]}'.format)\n >>> w.reset_index()\n famid birth ht1 ht2\n 0 1 1 2.8 3.4\n 1 1 2 2.9 3.8\n 2 1 3 2.2 2.9\n 3 2 1 2.0 3.2\n 4 2 2 1.8 2.8\n 5 2 3 1.9 2.4\n 6 3 1 2.2 3.3\n 7 3 2 2.3 3.4\n 8 3 3 2.1 2.9\n\n Less wieldy column names are also handled\n\n >>> np.random.seed(0)\n >>> df = pd.DataFrame({'A(quarterly)-2010': np.random.rand(3),\n ... 'A(quarterly)-2011': np.random.rand(3),\n ... 'B(quarterly)-2010': np.random.rand(3),\n ... 'B(quarterly)-2011': np.random.rand(3),\n ... 'X' : np.random.randint(3, size=3)})\n >>> df['id'] = df.index\n >>> df # doctest: +NORMALIZE_WHITESPACE, +ELLIPSIS\n A(quarterly)-2010 A(quarterly)-2011 B(quarterly)-2010 ...\n 0 0.548814 0.544883 0.437587 ...\n 1 0.715189 0.423655 0.891773 ...\n 2 0.602763 0.645894 0.963663 ...\n X id\n 0 0 0\n 1 1 1\n 2 1 2\n\n >>> pd.wide_to_long(df, ['A(quarterly)', 'B(quarterly)'], i='id',\n ... j='year', sep='-')\n ... # doctest: +NORMALIZE_WHITESPACE\n X A(quarterly) B(quarterly)\n id year\n 0 2010 0 0.548814 0.437587\n 1 2010 1 0.715189 0.891773\n 2 2010 1 0.602763 0.963663\n 0 2011 0 0.544883 0.383442\n 1 2011 1 0.423655 0.791725\n 2 2011 1 0.645894 0.528895\n\n If we have many columns, we could also use a regex to find our\n stubnames and pass that list on to wide_to_long\n\n >>> stubnames = sorted(\n ... set([match[0] for match in df.columns.str.findall(\n ... r'[A-B]\\(.*\\)').values if match != [] ])\n ... )\n >>> list(stubnames)\n ['A(quarterly)', 'B(quarterly)']\n\n All of the above examples have integers as suffixes. It is possible to\n have non-integers as suffixes.\n\n >>> df = pd.DataFrame({\n ... 'famid': [1, 1, 1, 2, 2, 2, 3, 3, 3],\n ... 'birth': [1, 2, 3, 1, 2, 3, 1, 2, 3],\n ... 'ht_one': [2.8, 2.9, 2.2, 2, 1.8, 1.9, 2.2, 2.3, 2.1],\n ... 'ht_two': [3.4, 3.8, 2.9, 3.2, 2.8, 2.4, 3.3, 3.4, 2.9]\n ... })\n >>> df\n birth famid ht_one ht_two\n 0 1 1 2.8 3.4\n 1 2 1 2.9 3.8\n 2 3 1 2.2 2.9\n 3 1 2 2.0 3.2\n 4 2 2 1.8 2.8\n 5 3 2 1.9 2.4\n 6 1 3 2.2 3.3\n 7 2 3 2.3 3.4\n 8 3 3 2.1 2.9\n\n >>> l = pd.wide_to_long(df, stubnames='ht', i=['famid', 'birth'], j='age',\n sep='_', suffix='\\w')\n >>> l\n ... # doctest: +NORMALIZE_WHITESPACE\n ht\n famid birth age\n 1 1 one 2.8\n two 3.4\n 2 one 2.9\n two 3.8\n 3 one 2.2\n two 2.9\n 2 1 one 2.0\n two 3.2\n 2 one 1.8\n two 2.8\n 3 one 1.9\n two 2.4\n 3 1 one 2.2\n two 3.3\n 2 one 2.3\n two 3.4\n 3 one 2.1\n two 2.9", "output": "def wide_to_long(df, stubnames, i, j, sep=\"\", suffix=r'\\d+'):\n r\"\"\"\n Wide panel to long format. Less flexible but more user-friendly than melt.\n\n With stubnames ['A', 'B'], this function expects to find one or more\n group of columns with format\n A-suffix1, A-suffix2,..., B-suffix1, B-suffix2,...\n You specify what you want to call this suffix in the resulting long format\n with `j` (for example `j='year'`)\n\n Each row of these wide variables are assumed to be uniquely identified by\n `i` (can be a single column name or a list of column names)\n\n All remaining variables in the data frame are left intact.\n\n Parameters\n ----------\n df : DataFrame\n The wide-format DataFrame\n stubnames : str or list-like\n The stub name(s). The wide format variables are assumed to\n start with the stub names.\n i : str or list-like\n Column(s) to use as id variable(s)\n j : str\n The name of the sub-observation variable. What you wish to name your\n suffix in the long format.\n sep : str, default \"\"\n A character indicating the separation of the variable names\n in the wide format, to be stripped from the names in the long format.\n For example, if your column names are A-suffix1, A-suffix2, you\n can strip the hyphen by specifying `sep='-'`\n\n .. versionadded:: 0.20.0\n\n suffix : str, default '\\\\d+'\n A regular expression capturing the wanted suffixes. '\\\\d+' captures\n numeric suffixes. Suffixes with no numbers could be specified with the\n negated character class '\\\\D+'. You can also further disambiguate\n suffixes, for example, if your wide variables are of the form\n A-one, B-two,.., and you have an unrelated column A-rating, you can\n ignore the last one by specifying `suffix='(!?one|two)'`\n\n .. versionadded:: 0.20.0\n\n .. versionchanged:: 0.23.0\n When all suffixes are numeric, they are cast to int64/float64.\n\n Returns\n -------\n DataFrame\n A DataFrame that contains each stub name as a variable, with new index\n (i, j).\n\n Notes\n -----\n All extra variables are left untouched. This simply uses\n `pandas.melt` under the hood, but is hard-coded to \"do the right thing\"\n in a typical case.\n\n Examples\n --------\n >>> np.random.seed(123)\n >>> df = pd.DataFrame({\"A1970\" : {0 : \"a\", 1 : \"b\", 2 : \"c\"},\n ... \"A1980\" : {0 : \"d\", 1 : \"e\", 2 : \"f\"},\n ... \"B1970\" : {0 : 2.5, 1 : 1.2, 2 : .7},\n ... \"B1980\" : {0 : 3.2, 1 : 1.3, 2 : .1},\n ... \"X\" : dict(zip(range(3), np.random.randn(3)))\n ... })\n >>> df[\"id\"] = df.index\n >>> df\n A1970 A1980 B1970 B1980 X id\n 0 a d 2.5 3.2 -1.085631 0\n 1 b e 1.2 1.3 0.997345 1\n 2 c f 0.7 0.1 0.282978 2\n >>> pd.wide_to_long(df, [\"A\", \"B\"], i=\"id\", j=\"year\")\n ... # doctest: +NORMALIZE_WHITESPACE\n X A B\n id year\n 0 1970 -1.085631 a 2.5\n 1 1970 0.997345 b 1.2\n 2 1970 0.282978 c 0.7\n 0 1980 -1.085631 d 3.2\n 1 1980 0.997345 e 1.3\n 2 1980 0.282978 f 0.1\n\n With multiple id columns\n\n >>> df = pd.DataFrame({\n ... 'famid': [1, 1, 1, 2, 2, 2, 3, 3, 3],\n ... 'birth': [1, 2, 3, 1, 2, 3, 1, 2, 3],\n ... 'ht1': [2.8, 2.9, 2.2, 2, 1.8, 1.9, 2.2, 2.3, 2.1],\n ... 'ht2': [3.4, 3.8, 2.9, 3.2, 2.8, 2.4, 3.3, 3.4, 2.9]\n ... })\n >>> df\n birth famid ht1 ht2\n 0 1 1 2.8 3.4\n 1 2 1 2.9 3.8\n 2 3 1 2.2 2.9\n 3 1 2 2.0 3.2\n 4 2 2 1.8 2.8\n 5 3 2 1.9 2.4\n 6 1 3 2.2 3.3\n 7 2 3 2.3 3.4\n 8 3 3 2.1 2.9\n >>> l = pd.wide_to_long(df, stubnames='ht', i=['famid', 'birth'], j='age')\n >>> l\n ... # doctest: +NORMALIZE_WHITESPACE\n ht\n famid birth age\n 1 1 1 2.8\n 2 3.4\n 2 1 2.9\n 2 3.8\n 3 1 2.2\n 2 2.9\n 2 1 1 2.0\n 2 3.2\n 2 1 1.8\n 2 2.8\n 3 1 1.9\n 2 2.4\n 3 1 1 2.2\n 2 3.3\n 2 1 2.3\n 2 3.4\n 3 1 2.1\n 2 2.9\n\n Going from long back to wide just takes some creative use of `unstack`\n\n >>> w = l.unstack()\n >>> w.columns = w.columns.map('{0[0]}{0[1]}'.format)\n >>> w.reset_index()\n famid birth ht1 ht2\n 0 1 1 2.8 3.4\n 1 1 2 2.9 3.8\n 2 1 3 2.2 2.9\n 3 2 1 2.0 3.2\n 4 2 2 1.8 2.8\n 5 2 3 1.9 2.4\n 6 3 1 2.2 3.3\n 7 3 2 2.3 3.4\n 8 3 3 2.1 2.9\n\n Less wieldy column names are also handled\n\n >>> np.random.seed(0)\n >>> df = pd.DataFrame({'A(quarterly)-2010': np.random.rand(3),\n ... 'A(quarterly)-2011': np.random.rand(3),\n ... 'B(quarterly)-2010': np.random.rand(3),\n ... 'B(quarterly)-2011': np.random.rand(3),\n ... 'X' : np.random.randint(3, size=3)})\n >>> df['id'] = df.index\n >>> df # doctest: +NORMALIZE_WHITESPACE, +ELLIPSIS\n A(quarterly)-2010 A(quarterly)-2011 B(quarterly)-2010 ...\n 0 0.548814 0.544883 0.437587 ...\n 1 0.715189 0.423655 0.891773 ...\n 2 0.602763 0.645894 0.963663 ...\n X id\n 0 0 0\n 1 1 1\n 2 1 2\n\n >>> pd.wide_to_long(df, ['A(quarterly)', 'B(quarterly)'], i='id',\n ... j='year', sep='-')\n ... # doctest: +NORMALIZE_WHITESPACE\n X A(quarterly) B(quarterly)\n id year\n 0 2010 0 0.548814 0.437587\n 1 2010 1 0.715189 0.891773\n 2 2010 1 0.602763 0.963663\n 0 2011 0 0.544883 0.383442\n 1 2011 1 0.423655 0.791725\n 2 2011 1 0.645894 0.528895\n\n If we have many columns, we could also use a regex to find our\n stubnames and pass that list on to wide_to_long\n\n >>> stubnames = sorted(\n ... set([match[0] for match in df.columns.str.findall(\n ... r'[A-B]\\(.*\\)').values if match != [] ])\n ... )\n >>> list(stubnames)\n ['A(quarterly)', 'B(quarterly)']\n\n All of the above examples have integers as suffixes. It is possible to\n have non-integers as suffixes.\n\n >>> df = pd.DataFrame({\n ... 'famid': [1, 1, 1, 2, 2, 2, 3, 3, 3],\n ... 'birth': [1, 2, 3, 1, 2, 3, 1, 2, 3],\n ... 'ht_one': [2.8, 2.9, 2.2, 2, 1.8, 1.9, 2.2, 2.3, 2.1],\n ... 'ht_two': [3.4, 3.8, 2.9, 3.2, 2.8, 2.4, 3.3, 3.4, 2.9]\n ... })\n >>> df\n birth famid ht_one ht_two\n 0 1 1 2.8 3.4\n 1 2 1 2.9 3.8\n 2 3 1 2.2 2.9\n 3 1 2 2.0 3.2\n 4 2 2 1.8 2.8\n 5 3 2 1.9 2.4\n 6 1 3 2.2 3.3\n 7 2 3 2.3 3.4\n 8 3 3 2.1 2.9\n\n >>> l = pd.wide_to_long(df, stubnames='ht', i=['famid', 'birth'], j='age',\n sep='_', suffix='\\w')\n >>> l\n ... # doctest: +NORMALIZE_WHITESPACE\n ht\n famid birth age\n 1 1 one 2.8\n two 3.4\n 2 one 2.9\n two 3.8\n 3 one 2.2\n two 2.9\n 2 1 one 2.0\n two 3.2\n 2 one 1.8\n two 2.8\n 3 one 1.9\n two 2.4\n 3 1 one 2.2\n two 3.3\n 2 one 2.3\n two 3.4\n 3 one 2.1\n two 2.9\n \"\"\"\n def get_var_names(df, stub, sep, suffix):\n regex = r'^{stub}{sep}{suffix}$'.format(\n stub=re.escape(stub), sep=re.escape(sep), suffix=suffix)\n pattern = re.compile(regex)\n return [col for col in df.columns if pattern.match(col)]\n\n def melt_stub(df, stub, i, j, value_vars, sep):\n newdf = melt(df, id_vars=i, value_vars=value_vars,\n value_name=stub.rstrip(sep), var_name=j)\n newdf[j] = Categorical(newdf[j])\n newdf[j] = newdf[j].str.replace(re.escape(stub + sep), \"\")\n\n # GH17627 Cast numerics suffixes to int/float\n newdf[j] = to_numeric(newdf[j], errors='ignore')\n\n return newdf.set_index(i + [j])\n\n if not is_list_like(stubnames):\n stubnames = [stubnames]\n else:\n stubnames = list(stubnames)\n\n if any(col in stubnames for col in df.columns):\n raise ValueError(\"stubname can't be identical to a column name\")\n\n if not is_list_like(i):\n i = [i]\n else:\n i = list(i)\n\n if df[i].duplicated().any():\n raise ValueError(\"the id variables need to uniquely identify each row\")\n\n value_vars = [get_var_names(df, stub, sep, suffix) for stub in stubnames]\n\n value_vars_flattened = [e for sublist in value_vars for e in sublist]\n id_vars = list(set(df.columns.tolist()).difference(value_vars_flattened))\n\n melted = [melt_stub(df, s, i, j, v, sep)\n for s, v in zip(stubnames, value_vars)]\n melted = melted[0].join(melted[1:], how='outer')\n\n if len(i) == 1:\n new = df[id_vars].set_index(i).join(melted)\n return new\n\n new = df[id_vars].merge(melted.reset_index(), on=i).set_index(i + [j])\n\n return new" }, { "instruction": "Write or improve a Python function based on this description:\n\nSafe get multiple indices, translate keys for\n datelike to underlying repr.", "output": "def _get_indices(self, names):\n \"\"\"\n Safe get multiple indices, translate keys for\n datelike to underlying repr.\n \"\"\"\n\n def get_converter(s):\n # possibly convert to the actual key types\n # in the indices, could be a Timestamp or a np.datetime64\n if isinstance(s, (Timestamp, datetime.datetime)):\n return lambda key: Timestamp(key)\n elif isinstance(s, np.datetime64):\n return lambda key: Timestamp(key).asm8\n else:\n return lambda key: key\n\n if len(names) == 0:\n return []\n\n if len(self.indices) > 0:\n index_sample = next(iter(self.indices))\n else:\n index_sample = None # Dummy sample\n\n name_sample = names[0]\n if isinstance(index_sample, tuple):\n if not isinstance(name_sample, tuple):\n msg = (\"must supply a tuple to get_group with multiple\"\n \" grouping keys\")\n raise ValueError(msg)\n if not len(name_sample) == len(index_sample):\n try:\n # If the original grouper was a tuple\n return [self.indices[name] for name in names]\n except KeyError:\n # turns out it wasn't a tuple\n msg = (\"must supply a same-length tuple to get_group\"\n \" with multiple grouping keys\")\n raise ValueError(msg)\n\n converters = [get_converter(s) for s in index_sample]\n names = (tuple(f(n) for f, n in zip(converters, name))\n for name in names)\n\n else:\n converter = get_converter(index_sample)\n names = (converter(name) for name in names)\n\n return [self.indices.get(name, []) for name in names]" }, { "instruction": "Write or improve a Python function based on this description:\n\nCreate group based selection.\n\n Used when selection is not passed directly but instead via a grouper.\n\n NOTE: this should be paired with a call to _reset_group_selection", "output": "def _set_group_selection(self):\n \"\"\"\n Create group based selection.\n\n Used when selection is not passed directly but instead via a grouper.\n\n NOTE: this should be paired with a call to _reset_group_selection\n \"\"\"\n grp = self.grouper\n if not (self.as_index and\n getattr(grp, 'groupings', None) is not None and\n self.obj.ndim > 1 and\n self._group_selection is None):\n return\n\n ax = self.obj._info_axis\n groupers = [g.name for g in grp.groupings\n if g.level is None and g.in_axis]\n\n if len(groupers):\n # GH12839 clear selected obj cache when group selection changes\n self._group_selection = ax.difference(Index(groupers),\n sort=False).tolist()\n self._reset_cache('_selected_obj')" }, { "instruction": "Write or improve a Python function based on this description:\n\nConstruct NDFrame from group with provided name.\n\n Parameters\n ----------\n name : object\n the name of the group to get as a DataFrame\n obj : NDFrame, default None\n the NDFrame to take the DataFrame out of. If\n it is None, the object groupby was called on will\n be used\n\n Returns\n -------\n group : same type as obj", "output": "def get_group(self, name, obj=None):\n \"\"\"\n Construct NDFrame from group with provided name.\n\n Parameters\n ----------\n name : object\n the name of the group to get as a DataFrame\n obj : NDFrame, default None\n the NDFrame to take the DataFrame out of. If\n it is None, the object groupby was called on will\n be used\n\n Returns\n -------\n group : same type as obj\n \"\"\"\n if obj is None:\n obj = self._selected_obj\n\n inds = self._get_index(name)\n if not len(inds):\n raise KeyError(name)\n\n return obj._take(inds, axis=self.axis)" }, { "instruction": "Write or improve a Python function based on this description:\n\nParameters\n ----------\n ascending : bool, default True\n If False, number in reverse, from length of group - 1 to 0.\n\n Notes\n -----\n this is currently implementing sort=False\n (though the default is sort=True) for groupby in general", "output": "def _cumcount_array(self, ascending=True):\n \"\"\"\n Parameters\n ----------\n ascending : bool, default True\n If False, number in reverse, from length of group - 1 to 0.\n\n Notes\n -----\n this is currently implementing sort=False\n (though the default is sort=True) for groupby in general\n \"\"\"\n ids, _, ngroups = self.grouper.group_info\n sorter = get_group_index_sorter(ids, ngroups)\n ids, count = ids[sorter], len(ids)\n\n if count == 0:\n return np.empty(0, dtype=np.int64)\n\n run = np.r_[True, ids[:-1] != ids[1:]]\n rep = np.diff(np.r_[np.nonzero(run)[0], count])\n out = (~run).cumsum()\n\n if ascending:\n out -= np.repeat(out[run], rep)\n else:\n out = np.repeat(out[np.r_[run[1:], True]], rep) - out\n\n rev = np.empty(count, dtype=np.intp)\n rev[sorter] = np.arange(count, dtype=np.intp)\n return out[rev].astype(np.int64, copy=False)" }, { "instruction": "Write or improve a Python function based on this description:\n\nTry to cast the result to our obj original type,\n we may have roundtripped through object in the mean-time.\n\n If numeric_only is True, then only try to cast numerics\n and not datetimelikes.", "output": "def _try_cast(self, result, obj, numeric_only=False):\n \"\"\"\n Try to cast the result to our obj original type,\n we may have roundtripped through object in the mean-time.\n\n If numeric_only is True, then only try to cast numerics\n and not datetimelikes.\n\n \"\"\"\n if obj.ndim > 1:\n dtype = obj._values.dtype\n else:\n dtype = obj.dtype\n\n if not is_scalar(result):\n if is_datetime64tz_dtype(dtype):\n # GH 23683\n # Prior results _may_ have been generated in UTC.\n # Ensure we localize to UTC first before converting\n # to the target timezone\n try:\n result = obj._values._from_sequence(\n result, dtype='datetime64[ns, UTC]'\n )\n result = result.astype(dtype)\n except TypeError:\n # _try_cast was called at a point where the result\n # was already tz-aware\n pass\n elif is_extension_array_dtype(dtype):\n # The function can return something of any type, so check\n # if the type is compatible with the calling EA.\n try:\n result = obj._values._from_sequence(result, dtype=dtype)\n except Exception:\n # https://github.com/pandas-dev/pandas/issues/22850\n # pandas has no control over what 3rd-party ExtensionArrays\n # do in _values_from_sequence. We still want ops to work\n # though, so we catch any regular Exception.\n pass\n elif numeric_only and is_numeric_dtype(dtype) or not numeric_only:\n result = maybe_downcast_to_dtype(result, dtype)\n\n return result" }, { "instruction": "Write or improve a Python function based on this description:\n\nParameters:\n -----------\n func_nm: str\n The name of the aggregation function being performed\n\n Returns:\n --------\n bool\n Whether transform should attempt to cast the result of aggregation", "output": "def _transform_should_cast(self, func_nm):\n \"\"\"\n Parameters:\n -----------\n func_nm: str\n The name of the aggregation function being performed\n\n Returns:\n --------\n bool\n Whether transform should attempt to cast the result of aggregation\n \"\"\"\n return (self.size().fillna(0) > 0).any() and (\n func_nm not in base.cython_cast_blacklist)" }, { "instruction": "Write or improve a Python function based on this description:\n\nShared func to call any / all Cython GroupBy implementations.", "output": "def _bool_agg(self, val_test, skipna):\n \"\"\"\n Shared func to call any / all Cython GroupBy implementations.\n \"\"\"\n\n def objs_to_bool(vals: np.ndarray) -> Tuple[np.ndarray, Type]:\n if is_object_dtype(vals):\n vals = np.array([bool(x) for x in vals])\n else:\n vals = vals.astype(np.bool)\n\n return vals.view(np.uint8), np.bool\n\n def result_to_bool(result: np.ndarray, inference: Type) -> np.ndarray:\n return result.astype(inference, copy=False)\n\n return self._get_cythonized_result('group_any_all', self.grouper,\n aggregate=True,\n cython_dtype=np.uint8,\n needs_values=True,\n needs_mask=True,\n pre_processing=objs_to_bool,\n post_processing=result_to_bool,\n val_test=val_test, skipna=skipna)" }, { "instruction": "Write or improve a Python function based on this description:\n\nCompute mean of groups, excluding missing values.\n\n Returns\n -------\n pandas.Series or pandas.DataFrame\n %(see_also)s\n Examples\n --------\n >>> df = pd.DataFrame({'A': [1, 1, 2, 1, 2],\n ... 'B': [np.nan, 2, 3, 4, 5],\n ... 'C': [1, 2, 1, 1, 2]}, columns=['A', 'B', 'C'])\n\n Groupby one column and return the mean of the remaining columns in\n each group.\n\n >>> df.groupby('A').mean()\n >>>\n B C\n A\n 1 3.0 1.333333\n 2 4.0 1.500000\n\n Groupby two columns and return the mean of the remaining column.\n\n >>> df.groupby(['A', 'B']).mean()\n >>>\n C\n A B\n 1 2.0 2\n 4.0 1\n 2 3.0 1\n 5.0 2\n\n Groupby one column and return the mean of only particular column in\n the group.\n\n >>> df.groupby('A')['B'].mean()\n >>>\n A\n 1 3.0\n 2 4.0\n Name: B, dtype: float64", "output": "def mean(self, *args, **kwargs):\n \"\"\"\n Compute mean of groups, excluding missing values.\n\n Returns\n -------\n pandas.Series or pandas.DataFrame\n %(see_also)s\n Examples\n --------\n >>> df = pd.DataFrame({'A': [1, 1, 2, 1, 2],\n ... 'B': [np.nan, 2, 3, 4, 5],\n ... 'C': [1, 2, 1, 1, 2]}, columns=['A', 'B', 'C'])\n\n Groupby one column and return the mean of the remaining columns in\n each group.\n\n >>> df.groupby('A').mean()\n >>>\n B C\n A\n 1 3.0 1.333333\n 2 4.0 1.500000\n\n Groupby two columns and return the mean of the remaining column.\n\n >>> df.groupby(['A', 'B']).mean()\n >>>\n C\n A B\n 1 2.0 2\n 4.0 1\n 2 3.0 1\n 5.0 2\n\n Groupby one column and return the mean of only particular column in\n the group.\n\n >>> df.groupby('A')['B'].mean()\n >>>\n A\n 1 3.0\n 2 4.0\n Name: B, dtype: float64\n \"\"\"\n nv.validate_groupby_func('mean', args, kwargs, ['numeric_only'])\n try:\n return self._cython_agg_general('mean', **kwargs)\n except GroupByError:\n raise\n except Exception: # pragma: no cover\n with _group_selection_context(self):\n f = lambda x: x.mean(axis=self.axis, **kwargs)\n return self._python_agg_general(f)" }, { "instruction": "Write or improve a Python function based on this description:\n\nCompute median of groups, excluding missing values.\n\n For multiple groupings, the result index will be a MultiIndex", "output": "def median(self, **kwargs):\n \"\"\"\n Compute median of groups, excluding missing values.\n\n For multiple groupings, the result index will be a MultiIndex\n \"\"\"\n try:\n return self._cython_agg_general('median', **kwargs)\n except GroupByError:\n raise\n except Exception: # pragma: no cover\n\n def f(x):\n if isinstance(x, np.ndarray):\n x = Series(x)\n return x.median(axis=self.axis, **kwargs)\n with _group_selection_context(self):\n return self._python_agg_general(f)" }, { "instruction": "Write or improve a Python function based on this description:\n\nCompute standard deviation of groups, excluding missing values.\n\n For multiple groupings, the result index will be a MultiIndex.\n\n Parameters\n ----------\n ddof : integer, default 1\n degrees of freedom", "output": "def std(self, ddof=1, *args, **kwargs):\n \"\"\"\n Compute standard deviation of groups, excluding missing values.\n\n For multiple groupings, the result index will be a MultiIndex.\n\n Parameters\n ----------\n ddof : integer, default 1\n degrees of freedom\n \"\"\"\n\n # TODO: implement at Cython level?\n nv.validate_groupby_func('std', args, kwargs)\n return np.sqrt(self.var(ddof=ddof, **kwargs))" }, { "instruction": "Write or improve a Python function based on this description:\n\nCompute variance of groups, excluding missing values.\n\n For multiple groupings, the result index will be a MultiIndex.\n\n Parameters\n ----------\n ddof : integer, default 1\n degrees of freedom", "output": "def var(self, ddof=1, *args, **kwargs):\n \"\"\"\n Compute variance of groups, excluding missing values.\n\n For multiple groupings, the result index will be a MultiIndex.\n\n Parameters\n ----------\n ddof : integer, default 1\n degrees of freedom\n \"\"\"\n nv.validate_groupby_func('var', args, kwargs)\n if ddof == 1:\n try:\n return self._cython_agg_general('var', **kwargs)\n except Exception:\n f = lambda x: x.var(ddof=ddof, **kwargs)\n with _group_selection_context(self):\n return self._python_agg_general(f)\n else:\n f = lambda x: x.var(ddof=ddof, **kwargs)\n with _group_selection_context(self):\n return self._python_agg_general(f)" }, { "instruction": "Write or improve a Python function based on this description:\n\nCompute standard error of the mean of groups, excluding missing values.\n\n For multiple groupings, the result index will be a MultiIndex.\n\n Parameters\n ----------\n ddof : integer, default 1\n degrees of freedom", "output": "def sem(self, ddof=1):\n \"\"\"\n Compute standard error of the mean of groups, excluding missing values.\n\n For multiple groupings, the result index will be a MultiIndex.\n\n Parameters\n ----------\n ddof : integer, default 1\n degrees of freedom\n \"\"\"\n\n return self.std(ddof=ddof) / np.sqrt(self.count())" }, { "instruction": "Write or improve a Python function based on this description:\n\nCompute group sizes.", "output": "def size(self):\n \"\"\"\n Compute group sizes.\n \"\"\"\n result = self.grouper.size()\n\n if isinstance(self.obj, Series):\n result.name = getattr(self.obj, 'name', None)\n return result" }, { "instruction": "Write or improve a Python function based on this description:\n\nAdd numeric operations to the GroupBy generically.", "output": "def _add_numeric_operations(cls):\n \"\"\"\n Add numeric operations to the GroupBy generically.\n \"\"\"\n\n def groupby_function(name, alias, npfunc,\n numeric_only=True, _convert=False,\n min_count=-1):\n\n _local_template = \"Compute %(f)s of group values\"\n\n @Substitution(name='groupby', f=name)\n @Appender(_common_see_also)\n @Appender(_local_template)\n def f(self, **kwargs):\n if 'numeric_only' not in kwargs:\n kwargs['numeric_only'] = numeric_only\n if 'min_count' not in kwargs:\n kwargs['min_count'] = min_count\n\n self._set_group_selection()\n try:\n return self._cython_agg_general(\n alias, alt=npfunc, **kwargs)\n except AssertionError as e:\n raise SpecificationError(str(e))\n except Exception:\n result = self.aggregate(\n lambda x: npfunc(x, axis=self.axis))\n if _convert:\n result = result._convert(datetime=True)\n return result\n\n set_function_name(f, name, cls)\n\n return f\n\n def first_compat(x, axis=0):\n\n def first(x):\n x = x.to_numpy()\n\n x = x[notna(x)]\n if len(x) == 0:\n return np.nan\n return x[0]\n\n if isinstance(x, DataFrame):\n return x.apply(first, axis=axis)\n else:\n return first(x)\n\n def last_compat(x, axis=0):\n\n def last(x):\n x = x.to_numpy()\n x = x[notna(x)]\n if len(x) == 0:\n return np.nan\n return x[-1]\n\n if isinstance(x, DataFrame):\n return x.apply(last, axis=axis)\n else:\n return last(x)\n\n cls.sum = groupby_function('sum', 'add', np.sum, min_count=0)\n cls.prod = groupby_function('prod', 'prod', np.prod, min_count=0)\n cls.min = groupby_function('min', 'min', np.min, numeric_only=False)\n cls.max = groupby_function('max', 'max', np.max, numeric_only=False)\n cls.first = groupby_function('first', 'first', first_compat,\n numeric_only=False)\n cls.last = groupby_function('last', 'last', last_compat,\n numeric_only=False)" }, { "instruction": "Write or improve a Python function based on this description:\n\nProvide resampling when using a TimeGrouper.\n\n Given a grouper, the function resamples it according to a string\n \"string\" -> \"frequency\".\n\n See the :ref:`frequency aliases `\n documentation for more details.\n\n Parameters\n ----------\n rule : str or DateOffset\n The offset string or object representing target grouper conversion.\n *args, **kwargs\n Possible arguments are `how`, `fill_method`, `limit`, `kind` and\n `on`, and other arguments of `TimeGrouper`.\n\n Returns\n -------\n Grouper\n Return a new grouper with our resampler appended.\n\n See Also\n --------\n Grouper : Specify a frequency to resample with when\n grouping by a key.\n DatetimeIndex.resample : Frequency conversion and resampling of\n time series.\n\n Examples\n --------\n >>> idx = pd.date_range('1/1/2000', periods=4, freq='T')\n >>> df = pd.DataFrame(data=4 * [range(2)],\n ... index=idx,\n ... columns=['a', 'b'])\n >>> df.iloc[2, 0] = 5\n >>> df\n a b\n 2000-01-01 00:00:00 0 1\n 2000-01-01 00:01:00 0 1\n 2000-01-01 00:02:00 5 1\n 2000-01-01 00:03:00 0 1\n\n Downsample the DataFrame into 3 minute bins and sum the values of\n the timestamps falling into a bin.\n\n >>> df.groupby('a').resample('3T').sum()\n a b\n a\n 0 2000-01-01 00:00:00 0 2\n 2000-01-01 00:03:00 0 1\n 5 2000-01-01 00:00:00 5 1\n\n Upsample the series into 30 second bins.\n\n >>> df.groupby('a').resample('30S').sum()\n a b\n a\n 0 2000-01-01 00:00:00 0 1\n 2000-01-01 00:00:30 0 0\n 2000-01-01 00:01:00 0 1\n 2000-01-01 00:01:30 0 0\n 2000-01-01 00:02:00 0 0\n 2000-01-01 00:02:30 0 0\n 2000-01-01 00:03:00 0 1\n 5 2000-01-01 00:02:00 5 1\n\n Resample by month. Values are assigned to the month of the period.\n\n >>> df.groupby('a').resample('M').sum()\n a b\n a\n 0 2000-01-31 0 3\n 5 2000-01-31 5 1\n\n Downsample the series into 3 minute bins as above, but close the right\n side of the bin interval.\n\n >>> df.groupby('a').resample('3T', closed='right').sum()\n a b\n a\n 0 1999-12-31 23:57:00 0 1\n 2000-01-01 00:00:00 0 2\n 5 2000-01-01 00:00:00 5 1\n\n Downsample the series into 3 minute bins and close the right side of\n the bin interval, but label each bin using the right edge instead of\n the left.\n\n >>> df.groupby('a').resample('3T', closed='right', label='right').sum()\n a b\n a\n 0 2000-01-01 00:00:00 0 1\n 2000-01-01 00:03:00 0 2\n 5 2000-01-01 00:03:00 5 1\n\n Add an offset of twenty seconds.\n\n >>> df.groupby('a').resample('3T', loffset='20s').sum()\n a b\n a\n 0 2000-01-01 00:00:20 0 2\n 2000-01-01 00:03:20 0 1\n 5 2000-01-01 00:00:20 5 1", "output": "def resample(self, rule, *args, **kwargs):\n \"\"\"\n Provide resampling when using a TimeGrouper.\n\n Given a grouper, the function resamples it according to a string\n \"string\" -> \"frequency\".\n\n See the :ref:`frequency aliases `\n documentation for more details.\n\n Parameters\n ----------\n rule : str or DateOffset\n The offset string or object representing target grouper conversion.\n *args, **kwargs\n Possible arguments are `how`, `fill_method`, `limit`, `kind` and\n `on`, and other arguments of `TimeGrouper`.\n\n Returns\n -------\n Grouper\n Return a new grouper with our resampler appended.\n\n See Also\n --------\n Grouper : Specify a frequency to resample with when\n grouping by a key.\n DatetimeIndex.resample : Frequency conversion and resampling of\n time series.\n\n Examples\n --------\n >>> idx = pd.date_range('1/1/2000', periods=4, freq='T')\n >>> df = pd.DataFrame(data=4 * [range(2)],\n ... index=idx,\n ... columns=['a', 'b'])\n >>> df.iloc[2, 0] = 5\n >>> df\n a b\n 2000-01-01 00:00:00 0 1\n 2000-01-01 00:01:00 0 1\n 2000-01-01 00:02:00 5 1\n 2000-01-01 00:03:00 0 1\n\n Downsample the DataFrame into 3 minute bins and sum the values of\n the timestamps falling into a bin.\n\n >>> df.groupby('a').resample('3T').sum()\n a b\n a\n 0 2000-01-01 00:00:00 0 2\n 2000-01-01 00:03:00 0 1\n 5 2000-01-01 00:00:00 5 1\n\n Upsample the series into 30 second bins.\n\n >>> df.groupby('a').resample('30S').sum()\n a b\n a\n 0 2000-01-01 00:00:00 0 1\n 2000-01-01 00:00:30 0 0\n 2000-01-01 00:01:00 0 1\n 2000-01-01 00:01:30 0 0\n 2000-01-01 00:02:00 0 0\n 2000-01-01 00:02:30 0 0\n 2000-01-01 00:03:00 0 1\n 5 2000-01-01 00:02:00 5 1\n\n Resample by month. Values are assigned to the month of the period.\n\n >>> df.groupby('a').resample('M').sum()\n a b\n a\n 0 2000-01-31 0 3\n 5 2000-01-31 5 1\n\n Downsample the series into 3 minute bins as above, but close the right\n side of the bin interval.\n\n >>> df.groupby('a').resample('3T', closed='right').sum()\n a b\n a\n 0 1999-12-31 23:57:00 0 1\n 2000-01-01 00:00:00 0 2\n 5 2000-01-01 00:00:00 5 1\n\n Downsample the series into 3 minute bins and close the right side of\n the bin interval, but label each bin using the right edge instead of\n the left.\n\n >>> df.groupby('a').resample('3T', closed='right', label='right').sum()\n a b\n a\n 0 2000-01-01 00:00:00 0 1\n 2000-01-01 00:03:00 0 2\n 5 2000-01-01 00:03:00 5 1\n\n Add an offset of twenty seconds.\n\n >>> df.groupby('a').resample('3T', loffset='20s').sum()\n a b\n a\n 0 2000-01-01 00:00:20 0 2\n 2000-01-01 00:03:20 0 1\n 5 2000-01-01 00:00:20 5 1\n \"\"\"\n from pandas.core.resample import get_resampler_for_grouping\n return get_resampler_for_grouping(self, rule, *args, **kwargs)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn a rolling grouper, providing rolling functionality per group.", "output": "def rolling(self, *args, **kwargs):\n \"\"\"\n Return a rolling grouper, providing rolling functionality per group.\n \"\"\"\n from pandas.core.window import RollingGroupby\n return RollingGroupby(self, *args, **kwargs)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn an expanding grouper, providing expanding\n functionality per group.", "output": "def expanding(self, *args, **kwargs):\n \"\"\"\n Return an expanding grouper, providing expanding\n functionality per group.\n \"\"\"\n from pandas.core.window import ExpandingGroupby\n return ExpandingGroupby(self, *args, **kwargs)" }, { "instruction": "Write or improve a Python function based on this description:\n\nShared function for `pad` and `backfill` to call Cython method.\n\n Parameters\n ----------\n direction : {'ffill', 'bfill'}\n Direction passed to underlying Cython function. `bfill` will cause\n values to be filled backwards. `ffill` and any other values will\n default to a forward fill\n limit : int, default None\n Maximum number of consecutive values to fill. If `None`, this\n method will convert to -1 prior to passing to Cython\n\n Returns\n -------\n `Series` or `DataFrame` with filled values\n\n See Also\n --------\n pad\n backfill", "output": "def _fill(self, direction, limit=None):\n \"\"\"\n Shared function for `pad` and `backfill` to call Cython method.\n\n Parameters\n ----------\n direction : {'ffill', 'bfill'}\n Direction passed to underlying Cython function. `bfill` will cause\n values to be filled backwards. `ffill` and any other values will\n default to a forward fill\n limit : int, default None\n Maximum number of consecutive values to fill. If `None`, this\n method will convert to -1 prior to passing to Cython\n\n Returns\n -------\n `Series` or `DataFrame` with filled values\n\n See Also\n --------\n pad\n backfill\n \"\"\"\n # Need int value for Cython\n if limit is None:\n limit = -1\n\n return self._get_cythonized_result('group_fillna_indexer',\n self.grouper, needs_mask=True,\n cython_dtype=np.int64,\n result_is_index=True,\n direction=direction, limit=limit)" }, { "instruction": "Write or improve a Python function based on this description:\n\nTake the nth row from each group if n is an int, or a subset of rows\n if n is a list of ints.\n\n If dropna, will take the nth non-null row, dropna is either\n Truthy (if a Series) or 'all', 'any' (if a DataFrame);\n this is equivalent to calling dropna(how=dropna) before the\n groupby.\n\n Parameters\n ----------\n n : int or list of ints\n a single nth value for the row or a list of nth values\n dropna : None or str, optional\n apply the specified dropna operation before counting which row is\n the nth row. Needs to be None, 'any' or 'all'\n %(see_also)s\n Examples\n --------\n\n >>> df = pd.DataFrame({'A': [1, 1, 2, 1, 2],\n ... 'B': [np.nan, 2, 3, 4, 5]}, columns=['A', 'B'])\n >>> g = df.groupby('A')\n >>> g.nth(0)\n B\n A\n 1 NaN\n 2 3.0\n >>> g.nth(1)\n B\n A\n 1 2.0\n 2 5.0\n >>> g.nth(-1)\n B\n A\n 1 4.0\n 2 5.0\n >>> g.nth([0, 1])\n B\n A\n 1 NaN\n 1 2.0\n 2 3.0\n 2 5.0\n\n Specifying `dropna` allows count ignoring ``NaN``\n\n >>> g.nth(0, dropna='any')\n B\n A\n 1 2.0\n 2 3.0\n\n NaNs denote group exhausted when using dropna\n\n >>> g.nth(3, dropna='any')\n B\n A\n 1 NaN\n 2 NaN\n\n Specifying `as_index=False` in `groupby` keeps the original index.\n\n >>> df.groupby('A', as_index=False).nth(1)\n A B\n 1 1 2.0\n 4 2 5.0", "output": "def nth(self, n, dropna=None):\n \"\"\"\n Take the nth row from each group if n is an int, or a subset of rows\n if n is a list of ints.\n\n If dropna, will take the nth non-null row, dropna is either\n Truthy (if a Series) or 'all', 'any' (if a DataFrame);\n this is equivalent to calling dropna(how=dropna) before the\n groupby.\n\n Parameters\n ----------\n n : int or list of ints\n a single nth value for the row or a list of nth values\n dropna : None or str, optional\n apply the specified dropna operation before counting which row is\n the nth row. Needs to be None, 'any' or 'all'\n %(see_also)s\n Examples\n --------\n\n >>> df = pd.DataFrame({'A': [1, 1, 2, 1, 2],\n ... 'B': [np.nan, 2, 3, 4, 5]}, columns=['A', 'B'])\n >>> g = df.groupby('A')\n >>> g.nth(0)\n B\n A\n 1 NaN\n 2 3.0\n >>> g.nth(1)\n B\n A\n 1 2.0\n 2 5.0\n >>> g.nth(-1)\n B\n A\n 1 4.0\n 2 5.0\n >>> g.nth([0, 1])\n B\n A\n 1 NaN\n 1 2.0\n 2 3.0\n 2 5.0\n\n Specifying `dropna` allows count ignoring ``NaN``\n\n >>> g.nth(0, dropna='any')\n B\n A\n 1 2.0\n 2 3.0\n\n NaNs denote group exhausted when using dropna\n\n >>> g.nth(3, dropna='any')\n B\n A\n 1 NaN\n 2 NaN\n\n Specifying `as_index=False` in `groupby` keeps the original index.\n\n >>> df.groupby('A', as_index=False).nth(1)\n A B\n 1 1 2.0\n 4 2 5.0\n \"\"\"\n\n if isinstance(n, int):\n nth_values = [n]\n elif isinstance(n, (set, list, tuple)):\n nth_values = list(set(n))\n if dropna is not None:\n raise ValueError(\n \"dropna option with a list of nth values is not supported\")\n else:\n raise TypeError(\"n needs to be an int or a list/set/tuple of ints\")\n\n nth_values = np.array(nth_values, dtype=np.intp)\n self._set_group_selection()\n\n if not dropna:\n mask_left = np.in1d(self._cumcount_array(), nth_values)\n mask_right = np.in1d(self._cumcount_array(ascending=False) + 1,\n -nth_values)\n mask = mask_left | mask_right\n\n out = self._selected_obj[mask]\n if not self.as_index:\n return out\n\n ids, _, _ = self.grouper.group_info\n out.index = self.grouper.result_index[ids[mask]]\n\n return out.sort_index() if self.sort else out\n\n if dropna not in ['any', 'all']:\n if isinstance(self._selected_obj, Series) and dropna is True:\n warnings.warn(\"the dropna={dropna} keyword is deprecated,\"\n \"use dropna='all' instead. \"\n \"For a Series groupby, dropna must be \"\n \"either None, 'any' or 'all'.\".format(\n dropna=dropna),\n FutureWarning,\n stacklevel=2)\n dropna = 'all'\n else:\n # Note: when agg-ing picker doesn't raise this,\n # just returns NaN\n raise ValueError(\"For a DataFrame groupby, dropna must be \"\n \"either None, 'any' or 'all', \"\n \"(was passed {dropna}).\".format(\n dropna=dropna))\n\n # old behaviour, but with all and any support for DataFrames.\n # modified in GH 7559 to have better perf\n max_len = n if n >= 0 else - 1 - n\n dropped = self.obj.dropna(how=dropna, axis=self.axis)\n\n # get a new grouper for our dropped obj\n if self.keys is None and self.level is None:\n\n # we don't have the grouper info available\n # (e.g. we have selected out\n # a column that is not in the current object)\n axis = self.grouper.axis\n grouper = axis[axis.isin(dropped.index)]\n\n else:\n\n # create a grouper with the original parameters, but on the dropped\n # object\n from pandas.core.groupby.grouper import _get_grouper\n grouper, _, _ = _get_grouper(dropped, key=self.keys,\n axis=self.axis, level=self.level,\n sort=self.sort,\n mutated=self.mutated)\n\n grb = dropped.groupby(grouper, as_index=self.as_index, sort=self.sort)\n sizes, result = grb.size(), grb.nth(n)\n mask = (sizes < max_len).values\n\n # set the results which don't meet the criteria\n if len(result) and mask.any():\n result.loc[mask] = np.nan\n\n # reset/reindex to the original groups\n if (len(self.obj) == len(dropped) or\n len(result) == len(self.grouper.result_index)):\n result.index = self.grouper.result_index\n else:\n result = result.reindex(self.grouper.result_index)\n\n return result" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn group values at the given quantile, a la numpy.percentile.\n\n Parameters\n ----------\n q : float or array-like, default 0.5 (50% quantile)\n Value(s) between 0 and 1 providing the quantile(s) to compute.\n interpolation : {'linear', 'lower', 'higher', 'midpoint', 'nearest'}\n Method to use when the desired quantile falls between two points.\n\n Returns\n -------\n Series or DataFrame\n Return type determined by caller of GroupBy object.\n\n See Also\n --------\n Series.quantile : Similar method for Series.\n DataFrame.quantile : Similar method for DataFrame.\n numpy.percentile : NumPy method to compute qth percentile.\n\n Examples\n --------\n >>> df = pd.DataFrame([\n ... ['a', 1], ['a', 2], ['a', 3],\n ... ['b', 1], ['b', 3], ['b', 5]\n ... ], columns=['key', 'val'])\n >>> df.groupby('key').quantile()\n val\n key\n a 2.0\n b 3.0", "output": "def quantile(self, q=0.5, interpolation='linear'):\n \"\"\"\n Return group values at the given quantile, a la numpy.percentile.\n\n Parameters\n ----------\n q : float or array-like, default 0.5 (50% quantile)\n Value(s) between 0 and 1 providing the quantile(s) to compute.\n interpolation : {'linear', 'lower', 'higher', 'midpoint', 'nearest'}\n Method to use when the desired quantile falls between two points.\n\n Returns\n -------\n Series or DataFrame\n Return type determined by caller of GroupBy object.\n\n See Also\n --------\n Series.quantile : Similar method for Series.\n DataFrame.quantile : Similar method for DataFrame.\n numpy.percentile : NumPy method to compute qth percentile.\n\n Examples\n --------\n >>> df = pd.DataFrame([\n ... ['a', 1], ['a', 2], ['a', 3],\n ... ['b', 1], ['b', 3], ['b', 5]\n ... ], columns=['key', 'val'])\n >>> df.groupby('key').quantile()\n val\n key\n a 2.0\n b 3.0\n \"\"\"\n\n def pre_processor(\n vals: np.ndarray\n ) -> Tuple[np.ndarray, Optional[Type]]:\n if is_object_dtype(vals):\n raise TypeError(\"'quantile' cannot be performed against \"\n \"'object' dtypes!\")\n\n inference = None\n if is_integer_dtype(vals):\n inference = np.int64\n elif is_datetime64_dtype(vals):\n inference = 'datetime64[ns]'\n vals = vals.astype(np.float)\n\n return vals, inference\n\n def post_processor(\n vals: np.ndarray,\n inference: Optional[Type]\n ) -> np.ndarray:\n if inference:\n # Check for edge case\n if not (is_integer_dtype(inference) and\n interpolation in {'linear', 'midpoint'}):\n vals = vals.astype(inference)\n\n return vals\n\n return self._get_cythonized_result('group_quantile', self.grouper,\n aggregate=True,\n needs_values=True,\n needs_mask=True,\n cython_dtype=np.float64,\n pre_processing=pre_processor,\n post_processing=post_processor,\n q=q, interpolation=interpolation)" }, { "instruction": "Write or improve a Python function based on this description:\n\nNumber each group from 0 to the number of groups - 1.\n\n This is the enumerative complement of cumcount. Note that the\n numbers given to the groups match the order in which the groups\n would be seen when iterating over the groupby object, not the\n order they are first observed.\n\n .. versionadded:: 0.20.2\n\n Parameters\n ----------\n ascending : bool, default True\n If False, number in reverse, from number of group - 1 to 0.\n\n See Also\n --------\n .cumcount : Number the rows in each group.\n\n Examples\n --------\n\n >>> df = pd.DataFrame({\"A\": list(\"aaabba\")})\n >>> df\n A\n 0 a\n 1 a\n 2 a\n 3 b\n 4 b\n 5 a\n >>> df.groupby('A').ngroup()\n 0 0\n 1 0\n 2 0\n 3 1\n 4 1\n 5 0\n dtype: int64\n >>> df.groupby('A').ngroup(ascending=False)\n 0 1\n 1 1\n 2 1\n 3 0\n 4 0\n 5 1\n dtype: int64\n >>> df.groupby([\"A\", [1,1,2,3,2,1]]).ngroup()\n 0 0\n 1 0\n 2 1\n 3 3\n 4 2\n 5 0\n dtype: int64", "output": "def ngroup(self, ascending=True):\n \"\"\"\n Number each group from 0 to the number of groups - 1.\n\n This is the enumerative complement of cumcount. Note that the\n numbers given to the groups match the order in which the groups\n would be seen when iterating over the groupby object, not the\n order they are first observed.\n\n .. versionadded:: 0.20.2\n\n Parameters\n ----------\n ascending : bool, default True\n If False, number in reverse, from number of group - 1 to 0.\n\n See Also\n --------\n .cumcount : Number the rows in each group.\n\n Examples\n --------\n\n >>> df = pd.DataFrame({\"A\": list(\"aaabba\")})\n >>> df\n A\n 0 a\n 1 a\n 2 a\n 3 b\n 4 b\n 5 a\n >>> df.groupby('A').ngroup()\n 0 0\n 1 0\n 2 0\n 3 1\n 4 1\n 5 0\n dtype: int64\n >>> df.groupby('A').ngroup(ascending=False)\n 0 1\n 1 1\n 2 1\n 3 0\n 4 0\n 5 1\n dtype: int64\n >>> df.groupby([\"A\", [1,1,2,3,2,1]]).ngroup()\n 0 0\n 1 0\n 2 1\n 3 3\n 4 2\n 5 0\n dtype: int64\n \"\"\"\n\n with _group_selection_context(self):\n index = self._selected_obj.index\n result = Series(self.grouper.group_info[0], index)\n if not ascending:\n result = self.ngroups - 1 - result\n return result" }, { "instruction": "Write or improve a Python function based on this description:\n\nNumber each item in each group from 0 to the length of that group - 1.\n\n Essentially this is equivalent to\n\n >>> self.apply(lambda x: pd.Series(np.arange(len(x)), x.index))\n\n Parameters\n ----------\n ascending : bool, default True\n If False, number in reverse, from length of group - 1 to 0.\n\n See Also\n --------\n .ngroup : Number the groups themselves.\n\n Examples\n --------\n\n >>> df = pd.DataFrame([['a'], ['a'], ['a'], ['b'], ['b'], ['a']],\n ... columns=['A'])\n >>> df\n A\n 0 a\n 1 a\n 2 a\n 3 b\n 4 b\n 5 a\n >>> df.groupby('A').cumcount()\n 0 0\n 1 1\n 2 2\n 3 0\n 4 1\n 5 3\n dtype: int64\n >>> df.groupby('A').cumcount(ascending=False)\n 0 3\n 1 2\n 2 1\n 3 1\n 4 0\n 5 0\n dtype: int64", "output": "def cumcount(self, ascending=True):\n \"\"\"\n Number each item in each group from 0 to the length of that group - 1.\n\n Essentially this is equivalent to\n\n >>> self.apply(lambda x: pd.Series(np.arange(len(x)), x.index))\n\n Parameters\n ----------\n ascending : bool, default True\n If False, number in reverse, from length of group - 1 to 0.\n\n See Also\n --------\n .ngroup : Number the groups themselves.\n\n Examples\n --------\n\n >>> df = pd.DataFrame([['a'], ['a'], ['a'], ['b'], ['b'], ['a']],\n ... columns=['A'])\n >>> df\n A\n 0 a\n 1 a\n 2 a\n 3 b\n 4 b\n 5 a\n >>> df.groupby('A').cumcount()\n 0 0\n 1 1\n 2 2\n 3 0\n 4 1\n 5 3\n dtype: int64\n >>> df.groupby('A').cumcount(ascending=False)\n 0 3\n 1 2\n 2 1\n 3 1\n 4 0\n 5 0\n dtype: int64\n \"\"\"\n\n with _group_selection_context(self):\n index = self._selected_obj.index\n cumcounts = self._cumcount_array(ascending=ascending)\n return Series(cumcounts, index)" }, { "instruction": "Write or improve a Python function based on this description:\n\nProvide the rank of values within each group.\n\n Parameters\n ----------\n method : {'average', 'min', 'max', 'first', 'dense'}, default 'average'\n * average: average rank of group\n * min: lowest rank in group\n * max: highest rank in group\n * first: ranks assigned in order they appear in the array\n * dense: like 'min', but rank always increases by 1 between groups\n ascending : boolean, default True\n False for ranks by high (1) to low (N)\n na_option : {'keep', 'top', 'bottom'}, default 'keep'\n * keep: leave NA values where they are\n * top: smallest rank if ascending\n * bottom: smallest rank if descending\n pct : boolean, default False\n Compute percentage rank of data within each group\n axis : int, default 0\n The axis of the object over which to compute the rank.\n\n Returns\n -------\n DataFrame with ranking of values within each group", "output": "def rank(self, method='average', ascending=True, na_option='keep',\n pct=False, axis=0):\n \"\"\"\n Provide the rank of values within each group.\n\n Parameters\n ----------\n method : {'average', 'min', 'max', 'first', 'dense'}, default 'average'\n * average: average rank of group\n * min: lowest rank in group\n * max: highest rank in group\n * first: ranks assigned in order they appear in the array\n * dense: like 'min', but rank always increases by 1 between groups\n ascending : boolean, default True\n False for ranks by high (1) to low (N)\n na_option : {'keep', 'top', 'bottom'}, default 'keep'\n * keep: leave NA values where they are\n * top: smallest rank if ascending\n * bottom: smallest rank if descending\n pct : boolean, default False\n Compute percentage rank of data within each group\n axis : int, default 0\n The axis of the object over which to compute the rank.\n\n Returns\n -------\n DataFrame with ranking of values within each group\n \"\"\"\n if na_option not in {'keep', 'top', 'bottom'}:\n msg = \"na_option must be one of 'keep', 'top', or 'bottom'\"\n raise ValueError(msg)\n return self._cython_transform('rank', numeric_only=False,\n ties_method=method, ascending=ascending,\n na_option=na_option, pct=pct, axis=axis)" }, { "instruction": "Write or improve a Python function based on this description:\n\nCumulative product for each group.", "output": "def cumprod(self, axis=0, *args, **kwargs):\n \"\"\"\n Cumulative product for each group.\n \"\"\"\n nv.validate_groupby_func('cumprod', args, kwargs,\n ['numeric_only', 'skipna'])\n if axis != 0:\n return self.apply(lambda x: x.cumprod(axis=axis, **kwargs))\n\n return self._cython_transform('cumprod', **kwargs)" }, { "instruction": "Write or improve a Python function based on this description:\n\nCumulative min for each group.", "output": "def cummin(self, axis=0, **kwargs):\n \"\"\"\n Cumulative min for each group.\n \"\"\"\n if axis != 0:\n return self.apply(lambda x: np.minimum.accumulate(x, axis))\n\n return self._cython_transform('cummin', numeric_only=False)" }, { "instruction": "Write or improve a Python function based on this description:\n\nCumulative max for each group.", "output": "def cummax(self, axis=0, **kwargs):\n \"\"\"\n Cumulative max for each group.\n \"\"\"\n if axis != 0:\n return self.apply(lambda x: np.maximum.accumulate(x, axis))\n\n return self._cython_transform('cummax', numeric_only=False)" }, { "instruction": "Write or improve a Python function based on this description:\n\nGet result for Cythonized functions.\n\n Parameters\n ----------\n how : str, Cythonized function name to be called\n grouper : Grouper object containing pertinent group info\n aggregate : bool, default False\n Whether the result should be aggregated to match the number of\n groups\n cython_dtype : default None\n Type of the array that will be modified by the Cython call. If\n `None`, the type will be inferred from the values of each slice\n needs_values : bool, default False\n Whether the values should be a part of the Cython call\n signature\n needs_mask : bool, default False\n Whether boolean mask needs to be part of the Cython call\n signature\n needs_ngroups : bool, default False\n Whether number of groups is part of the Cython call signature\n result_is_index : bool, default False\n Whether the result of the Cython operation is an index of\n values to be retrieved, instead of the actual values themselves\n pre_processing : function, default None\n Function to be applied to `values` prior to passing to Cython.\n Function should return a tuple where the first element is the\n values to be passed to Cython and the second element is an optional\n type which the values should be converted to after being returned\n by the Cython operation. Raises if `needs_values` is False.\n post_processing : function, default None\n Function to be applied to result of Cython function. Should accept\n an array of values as the first argument and type inferences as its\n second argument, i.e. the signature should be\n (ndarray, Type).\n **kwargs : dict\n Extra arguments to be passed back to Cython funcs\n\n Returns\n -------\n `Series` or `DataFrame` with filled values", "output": "def _get_cythonized_result(self, how, grouper, aggregate=False,\n cython_dtype=None, needs_values=False,\n needs_mask=False, needs_ngroups=False,\n result_is_index=False,\n pre_processing=None, post_processing=None,\n **kwargs):\n \"\"\"\n Get result for Cythonized functions.\n\n Parameters\n ----------\n how : str, Cythonized function name to be called\n grouper : Grouper object containing pertinent group info\n aggregate : bool, default False\n Whether the result should be aggregated to match the number of\n groups\n cython_dtype : default None\n Type of the array that will be modified by the Cython call. If\n `None`, the type will be inferred from the values of each slice\n needs_values : bool, default False\n Whether the values should be a part of the Cython call\n signature\n needs_mask : bool, default False\n Whether boolean mask needs to be part of the Cython call\n signature\n needs_ngroups : bool, default False\n Whether number of groups is part of the Cython call signature\n result_is_index : bool, default False\n Whether the result of the Cython operation is an index of\n values to be retrieved, instead of the actual values themselves\n pre_processing : function, default None\n Function to be applied to `values` prior to passing to Cython.\n Function should return a tuple where the first element is the\n values to be passed to Cython and the second element is an optional\n type which the values should be converted to after being returned\n by the Cython operation. Raises if `needs_values` is False.\n post_processing : function, default None\n Function to be applied to result of Cython function. Should accept\n an array of values as the first argument and type inferences as its\n second argument, i.e. the signature should be\n (ndarray, Type).\n **kwargs : dict\n Extra arguments to be passed back to Cython funcs\n\n Returns\n -------\n `Series` or `DataFrame` with filled values\n \"\"\"\n if result_is_index and aggregate:\n raise ValueError(\"'result_is_index' and 'aggregate' cannot both \"\n \"be True!\")\n if post_processing:\n if not callable(pre_processing):\n raise ValueError(\"'post_processing' must be a callable!\")\n if pre_processing:\n if not callable(pre_processing):\n raise ValueError(\"'pre_processing' must be a callable!\")\n if not needs_values:\n raise ValueError(\"Cannot use 'pre_processing' without \"\n \"specifying 'needs_values'!\")\n\n labels, _, ngroups = grouper.group_info\n output = collections.OrderedDict()\n base_func = getattr(libgroupby, how)\n\n for name, obj in self._iterate_slices():\n if aggregate:\n result_sz = ngroups\n else:\n result_sz = len(obj.values)\n\n if not cython_dtype:\n cython_dtype = obj.values.dtype\n\n result = np.zeros(result_sz, dtype=cython_dtype)\n func = partial(base_func, result, labels)\n inferences = None\n\n if needs_values:\n vals = obj.values\n if pre_processing:\n vals, inferences = pre_processing(vals)\n func = partial(func, vals)\n\n if needs_mask:\n mask = isna(obj.values).view(np.uint8)\n func = partial(func, mask)\n\n if needs_ngroups:\n func = partial(func, ngroups)\n\n func(**kwargs) # Call func to modify indexer values in place\n\n if result_is_index:\n result = algorithms.take_nd(obj.values, result)\n\n if post_processing:\n result = post_processing(result, inferences)\n\n output[name] = result\n\n if aggregate:\n return self._wrap_aggregated_output(output)\n else:\n return self._wrap_transformed_output(output)" }, { "instruction": "Write or improve a Python function based on this description:\n\nShift each group by periods observations.\n\n Parameters\n ----------\n periods : integer, default 1\n number of periods to shift\n freq : frequency string\n axis : axis to shift, default 0\n fill_value : optional\n\n .. versionadded:: 0.24.0", "output": "def shift(self, periods=1, freq=None, axis=0, fill_value=None):\n \"\"\"\n Shift each group by periods observations.\n\n Parameters\n ----------\n periods : integer, default 1\n number of periods to shift\n freq : frequency string\n axis : axis to shift, default 0\n fill_value : optional\n\n .. versionadded:: 0.24.0\n \"\"\"\n\n if freq is not None or axis != 0 or not isna(fill_value):\n return self.apply(lambda x: x.shift(periods, freq,\n axis, fill_value))\n\n return self._get_cythonized_result('group_shift_indexer',\n self.grouper, cython_dtype=np.int64,\n needs_ngroups=True,\n result_is_index=True,\n periods=periods)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn first n rows of each group.\n\n Essentially equivalent to ``.apply(lambda x: x.head(n))``,\n except ignores as_index flag.\n %(see_also)s\n Examples\n --------\n\n >>> df = pd.DataFrame([[1, 2], [1, 4], [5, 6]],\n columns=['A', 'B'])\n >>> df.groupby('A', as_index=False).head(1)\n A B\n 0 1 2\n 2 5 6\n >>> df.groupby('A').head(1)\n A B\n 0 1 2\n 2 5 6", "output": "def head(self, n=5):\n \"\"\"\n Return first n rows of each group.\n\n Essentially equivalent to ``.apply(lambda x: x.head(n))``,\n except ignores as_index flag.\n %(see_also)s\n Examples\n --------\n\n >>> df = pd.DataFrame([[1, 2], [1, 4], [5, 6]],\n columns=['A', 'B'])\n >>> df.groupby('A', as_index=False).head(1)\n A B\n 0 1 2\n 2 5 6\n >>> df.groupby('A').head(1)\n A B\n 0 1 2\n 2 5 6\n \"\"\"\n self._reset_group_selection()\n mask = self._cumcount_array() < n\n return self._selected_obj[mask]" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn last n rows of each group.\n\n Essentially equivalent to ``.apply(lambda x: x.tail(n))``,\n except ignores as_index flag.\n %(see_also)s\n Examples\n --------\n\n >>> df = pd.DataFrame([['a', 1], ['a', 2], ['b', 1], ['b', 2]],\n columns=['A', 'B'])\n >>> df.groupby('A').tail(1)\n A B\n 1 a 2\n 3 b 2\n >>> df.groupby('A').head(1)\n A B\n 0 a 1\n 2 b 1", "output": "def tail(self, n=5):\n \"\"\"\n Return last n rows of each group.\n\n Essentially equivalent to ``.apply(lambda x: x.tail(n))``,\n except ignores as_index flag.\n %(see_also)s\n Examples\n --------\n\n >>> df = pd.DataFrame([['a', 1], ['a', 2], ['b', 1], ['b', 2]],\n columns=['A', 'B'])\n >>> df.groupby('A').tail(1)\n A B\n 1 a 2\n 3 b 2\n >>> df.groupby('A').head(1)\n A B\n 0 a 1\n 2 b 1\n \"\"\"\n self._reset_group_selection()\n mask = self._cumcount_array(ascending=False) < n\n return self._selected_obj[mask]" }, { "instruction": "Write or improve a Python function based on this description:\n\nIf holiday falls on Saturday, use following Monday instead;\n if holiday falls on Sunday, use Monday instead", "output": "def next_monday(dt):\n \"\"\"\n If holiday falls on Saturday, use following Monday instead;\n if holiday falls on Sunday, use Monday instead\n \"\"\"\n if dt.weekday() == 5:\n return dt + timedelta(2)\n elif dt.weekday() == 6:\n return dt + timedelta(1)\n return dt" }, { "instruction": "Write or improve a Python function based on this description:\n\nFor second holiday of two adjacent ones!\n If holiday falls on Saturday, use following Monday instead;\n if holiday falls on Sunday or Monday, use following Tuesday instead\n (because Monday is already taken by adjacent holiday on the day before)", "output": "def next_monday_or_tuesday(dt):\n \"\"\"\n For second holiday of two adjacent ones!\n If holiday falls on Saturday, use following Monday instead;\n if holiday falls on Sunday or Monday, use following Tuesday instead\n (because Monday is already taken by adjacent holiday on the day before)\n \"\"\"\n dow = dt.weekday()\n if dow == 5 or dow == 6:\n return dt + timedelta(2)\n elif dow == 0:\n return dt + timedelta(1)\n return dt" }, { "instruction": "Write or improve a Python function based on this description:\n\nIf holiday falls on Saturday or Sunday, use previous Friday instead.", "output": "def previous_friday(dt):\n \"\"\"\n If holiday falls on Saturday or Sunday, use previous Friday instead.\n \"\"\"\n if dt.weekday() == 5:\n return dt - timedelta(1)\n elif dt.weekday() == 6:\n return dt - timedelta(2)\n return dt" }, { "instruction": "Write or improve a Python function based on this description:\n\nIf holiday falls on Sunday or Saturday,\n use day thereafter (Monday) instead.\n Needed for holidays such as Christmas observation in Europe", "output": "def weekend_to_monday(dt):\n \"\"\"\n If holiday falls on Sunday or Saturday,\n use day thereafter (Monday) instead.\n Needed for holidays such as Christmas observation in Europe\n \"\"\"\n if dt.weekday() == 6:\n return dt + timedelta(1)\n elif dt.weekday() == 5:\n return dt + timedelta(2)\n return dt" }, { "instruction": "Write or improve a Python function based on this description:\n\nIf holiday falls on Saturday, use day before (Friday) instead;\n if holiday falls on Sunday, use day thereafter (Monday) instead.", "output": "def nearest_workday(dt):\n \"\"\"\n If holiday falls on Saturday, use day before (Friday) instead;\n if holiday falls on Sunday, use day thereafter (Monday) instead.\n \"\"\"\n if dt.weekday() == 5:\n return dt - timedelta(1)\n elif dt.weekday() == 6:\n return dt + timedelta(1)\n return dt" }, { "instruction": "Write or improve a Python function based on this description:\n\nreturns next weekday used for observances", "output": "def next_workday(dt):\n \"\"\"\n returns next weekday used for observances\n \"\"\"\n dt += timedelta(days=1)\n while dt.weekday() > 4:\n # Mon-Fri are 0-4\n dt += timedelta(days=1)\n return dt" }, { "instruction": "Write or improve a Python function based on this description:\n\nreturns previous weekday used for observances", "output": "def previous_workday(dt):\n \"\"\"\n returns previous weekday used for observances\n \"\"\"\n dt -= timedelta(days=1)\n while dt.weekday() > 4:\n # Mon-Fri are 0-4\n dt -= timedelta(days=1)\n return dt" }, { "instruction": "Write or improve a Python function based on this description:\n\nCalculate holidays observed between start date and end date\n\n Parameters\n ----------\n start_date : starting date, datetime-like, optional\n end_date : ending date, datetime-like, optional\n return_name : bool, optional, default=False\n If True, return a series that has dates and holiday names.\n False will only return dates.", "output": "def dates(self, start_date, end_date, return_name=False):\n \"\"\"\n Calculate holidays observed between start date and end date\n\n Parameters\n ----------\n start_date : starting date, datetime-like, optional\n end_date : ending date, datetime-like, optional\n return_name : bool, optional, default=False\n If True, return a series that has dates and holiday names.\n False will only return dates.\n \"\"\"\n start_date = Timestamp(start_date)\n end_date = Timestamp(end_date)\n\n filter_start_date = start_date\n filter_end_date = end_date\n\n if self.year is not None:\n dt = Timestamp(datetime(self.year, self.month, self.day))\n if return_name:\n return Series(self.name, index=[dt])\n else:\n return [dt]\n\n dates = self._reference_dates(start_date, end_date)\n holiday_dates = self._apply_rule(dates)\n if self.days_of_week is not None:\n holiday_dates = holiday_dates[np.in1d(holiday_dates.dayofweek,\n self.days_of_week)]\n\n if self.start_date is not None:\n filter_start_date = max(self.start_date.tz_localize(\n filter_start_date.tz), filter_start_date)\n if self.end_date is not None:\n filter_end_date = min(self.end_date.tz_localize(\n filter_end_date.tz), filter_end_date)\n holiday_dates = holiday_dates[(holiday_dates >= filter_start_date) &\n (holiday_dates <= filter_end_date)]\n if return_name:\n return Series(self.name, index=holiday_dates)\n return holiday_dates" }, { "instruction": "Write or improve a Python function based on this description:\n\nGet reference dates for the holiday.\n\n Return reference dates for the holiday also returning the year\n prior to the start_date and year following the end_date. This ensures\n that any offsets to be applied will yield the holidays within\n the passed in dates.", "output": "def _reference_dates(self, start_date, end_date):\n \"\"\"\n Get reference dates for the holiday.\n\n Return reference dates for the holiday also returning the year\n prior to the start_date and year following the end_date. This ensures\n that any offsets to be applied will yield the holidays within\n the passed in dates.\n \"\"\"\n if self.start_date is not None:\n start_date = self.start_date.tz_localize(start_date.tz)\n\n if self.end_date is not None:\n end_date = self.end_date.tz_localize(start_date.tz)\n\n year_offset = DateOffset(years=1)\n reference_start_date = Timestamp(\n datetime(start_date.year - 1, self.month, self.day))\n\n reference_end_date = Timestamp(\n datetime(end_date.year + 1, self.month, self.day))\n # Don't process unnecessary holidays\n dates = date_range(start=reference_start_date,\n end=reference_end_date,\n freq=year_offset, tz=start_date.tz)\n\n return dates" }, { "instruction": "Write or improve a Python function based on this description:\n\nApply the given offset/observance to a DatetimeIndex of dates.\n\n Parameters\n ----------\n dates : DatetimeIndex\n Dates to apply the given offset/observance rule\n\n Returns\n -------\n Dates with rules applied", "output": "def _apply_rule(self, dates):\n \"\"\"\n Apply the given offset/observance to a DatetimeIndex of dates.\n\n Parameters\n ----------\n dates : DatetimeIndex\n Dates to apply the given offset/observance rule\n\n Returns\n -------\n Dates with rules applied\n \"\"\"\n if self.observance is not None:\n return dates.map(lambda d: self.observance(d))\n\n if self.offset is not None:\n if not isinstance(self.offset, list):\n offsets = [self.offset]\n else:\n offsets = self.offset\n for offset in offsets:\n\n # if we are adding a non-vectorized value\n # ignore the PerformanceWarnings:\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\", PerformanceWarning)\n dates += offset\n return dates" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns a curve with holidays between start_date and end_date\n\n Parameters\n ----------\n start : starting date, datetime-like, optional\n end : ending date, datetime-like, optional\n return_name : bool, optional\n If True, return a series that has dates and holiday names.\n False will only return a DatetimeIndex of dates.\n\n Returns\n -------\n DatetimeIndex of holidays", "output": "def holidays(self, start=None, end=None, return_name=False):\n \"\"\"\n Returns a curve with holidays between start_date and end_date\n\n Parameters\n ----------\n start : starting date, datetime-like, optional\n end : ending date, datetime-like, optional\n return_name : bool, optional\n If True, return a series that has dates and holiday names.\n False will only return a DatetimeIndex of dates.\n\n Returns\n -------\n DatetimeIndex of holidays\n \"\"\"\n if self.rules is None:\n raise Exception('Holiday Calendar {name} does not have any '\n 'rules specified'.format(name=self.name))\n\n if start is None:\n start = AbstractHolidayCalendar.start_date\n\n if end is None:\n end = AbstractHolidayCalendar.end_date\n\n start = Timestamp(start)\n end = Timestamp(end)\n\n holidays = None\n # If we don't have a cache or the dates are outside the prior cache, we\n # get them again\n if (self._cache is None or start < self._cache[0] or\n end > self._cache[1]):\n for rule in self.rules:\n rule_holidays = rule.dates(start, end, return_name=True)\n\n if holidays is None:\n holidays = rule_holidays\n else:\n holidays = holidays.append(rule_holidays)\n\n self._cache = (start, end, holidays.sort_index())\n\n holidays = self._cache[2]\n holidays = holidays[start:end]\n\n if return_name:\n return holidays\n else:\n return holidays.index" }, { "instruction": "Write or improve a Python function based on this description:\n\nMerge holiday calendars together. The base calendar\n will take precedence to other. The merge will be done\n based on each holiday's name.\n\n Parameters\n ----------\n base : AbstractHolidayCalendar\n instance/subclass or array of Holiday objects\n other : AbstractHolidayCalendar\n instance/subclass or array of Holiday objects", "output": "def merge_class(base, other):\n \"\"\"\n Merge holiday calendars together. The base calendar\n will take precedence to other. The merge will be done\n based on each holiday's name.\n\n Parameters\n ----------\n base : AbstractHolidayCalendar\n instance/subclass or array of Holiday objects\n other : AbstractHolidayCalendar\n instance/subclass or array of Holiday objects\n \"\"\"\n try:\n other = other.rules\n except AttributeError:\n pass\n\n if not isinstance(other, list):\n other = [other]\n other_holidays = {holiday.name: holiday for holiday in other}\n\n try:\n base = base.rules\n except AttributeError:\n pass\n\n if not isinstance(base, list):\n base = [base]\n base_holidays = {holiday.name: holiday for holiday in base}\n\n other_holidays.update(base_holidays)\n return list(other_holidays.values())" }, { "instruction": "Write or improve a Python function based on this description:\n\nMerge holiday calendars together. The caller's class\n rules take precedence. The merge will be done\n based on each holiday's name.\n\n Parameters\n ----------\n other : holiday calendar\n inplace : bool (default=False)\n If True set rule_table to holidays, else return array of Holidays", "output": "def merge(self, other, inplace=False):\n \"\"\"\n Merge holiday calendars together. The caller's class\n rules take precedence. The merge will be done\n based on each holiday's name.\n\n Parameters\n ----------\n other : holiday calendar\n inplace : bool (default=False)\n If True set rule_table to holidays, else return array of Holidays\n \"\"\"\n holidays = self.merge_class(self, other)\n if inplace:\n self.rules = holidays\n else:\n return holidays" }, { "instruction": "Write or improve a Python function based on this description:\n\nRegister an option in the package-wide pandas config object\n\n Parameters\n ----------\n key - a fully-qualified key, e.g. \"x.y.option - z\".\n defval - the default value of the option\n doc - a string description of the option\n validator - a function of a single argument, should raise `ValueError` if\n called with a value which is not a legal value for the option.\n cb - a function of a single argument \"key\", which is called\n immediately after an option value is set/reset. key is\n the full name of the option.\n\n Returns\n -------\n Nothing.\n\n Raises\n ------\n ValueError if `validator` is specified and `defval` is not a valid value.", "output": "def register_option(key, defval, doc='', validator=None, cb=None):\n \"\"\"Register an option in the package-wide pandas config object\n\n Parameters\n ----------\n key - a fully-qualified key, e.g. \"x.y.option - z\".\n defval - the default value of the option\n doc - a string description of the option\n validator - a function of a single argument, should raise `ValueError` if\n called with a value which is not a legal value for the option.\n cb - a function of a single argument \"key\", which is called\n immediately after an option value is set/reset. key is\n the full name of the option.\n\n Returns\n -------\n Nothing.\n\n Raises\n ------\n ValueError if `validator` is specified and `defval` is not a valid value.\n\n \"\"\"\n import tokenize\n import keyword\n key = key.lower()\n\n if key in _registered_options:\n msg = \"Option '{key}' has already been registered\"\n raise OptionError(msg.format(key=key))\n if key in _reserved_keys:\n msg = \"Option '{key}' is a reserved key\"\n raise OptionError(msg.format(key=key))\n\n # the default value should be legal\n if validator:\n validator(defval)\n\n # walk the nested dict, creating dicts as needed along the path\n path = key.split('.')\n\n for k in path:\n if not bool(re.match('^' + tokenize.Name + '$', k)):\n raise ValueError(\"{k} is not a valid identifier\".format(k=k))\n if keyword.iskeyword(k):\n raise ValueError(\"{k} is a python keyword\".format(k=k))\n\n cursor = _global_config\n msg = \"Path prefix to option '{option}' is already an option\"\n for i, p in enumerate(path[:-1]):\n if not isinstance(cursor, dict):\n raise OptionError(msg.format(option='.'.join(path[:i])))\n if p not in cursor:\n cursor[p] = {}\n cursor = cursor[p]\n\n if not isinstance(cursor, dict):\n raise OptionError(msg.format(option='.'.join(path[:-1])))\n\n cursor[path[-1]] = defval # initialize\n\n # save the option metadata\n _registered_options[key] = RegisteredOption(key=key, defval=defval,\n doc=doc, validator=validator,\n cb=cb)" }, { "instruction": "Write or improve a Python function based on this description:\n\nMark option `key` as deprecated, if code attempts to access this option,\n a warning will be produced, using `msg` if given, or a default message\n if not.\n if `rkey` is given, any access to the key will be re-routed to `rkey`.\n\n Neither the existence of `key` nor that if `rkey` is checked. If they\n do not exist, any subsequence access will fail as usual, after the\n deprecation warning is given.\n\n Parameters\n ----------\n key - the name of the option to be deprecated. must be a fully-qualified\n option name (e.g \"x.y.z.rkey\").\n\n msg - (Optional) a warning message to output when the key is referenced.\n if no message is given a default message will be emitted.\n\n rkey - (Optional) the name of an option to reroute access to.\n If specified, any referenced `key` will be re-routed to `rkey`\n including set/get/reset.\n rkey must be a fully-qualified option name (e.g \"x.y.z.rkey\").\n used by the default message if no `msg` is specified.\n\n removal_ver - (Optional) specifies the version in which this option will\n be removed. used by the default message if no `msg`\n is specified.\n\n Returns\n -------\n Nothing\n\n Raises\n ------\n OptionError - if key has already been deprecated.", "output": "def deprecate_option(key, msg=None, rkey=None, removal_ver=None):\n \"\"\"\n Mark option `key` as deprecated, if code attempts to access this option,\n a warning will be produced, using `msg` if given, or a default message\n if not.\n if `rkey` is given, any access to the key will be re-routed to `rkey`.\n\n Neither the existence of `key` nor that if `rkey` is checked. If they\n do not exist, any subsequence access will fail as usual, after the\n deprecation warning is given.\n\n Parameters\n ----------\n key - the name of the option to be deprecated. must be a fully-qualified\n option name (e.g \"x.y.z.rkey\").\n\n msg - (Optional) a warning message to output when the key is referenced.\n if no message is given a default message will be emitted.\n\n rkey - (Optional) the name of an option to reroute access to.\n If specified, any referenced `key` will be re-routed to `rkey`\n including set/get/reset.\n rkey must be a fully-qualified option name (e.g \"x.y.z.rkey\").\n used by the default message if no `msg` is specified.\n\n removal_ver - (Optional) specifies the version in which this option will\n be removed. used by the default message if no `msg`\n is specified.\n\n Returns\n -------\n Nothing\n\n Raises\n ------\n OptionError - if key has already been deprecated.\n\n \"\"\"\n\n key = key.lower()\n\n if key in _deprecated_options:\n msg = \"Option '{key}' has already been defined as deprecated.\"\n raise OptionError(msg.format(key=key))\n\n _deprecated_options[key] = DeprecatedOption(key, msg, rkey, removal_ver)" }, { "instruction": "Write or improve a Python function based on this description:\n\nreturns a list of keys matching `pat`\n\n if pat==\"all\", returns all registered options", "output": "def _select_options(pat):\n \"\"\"returns a list of keys matching `pat`\n\n if pat==\"all\", returns all registered options\n \"\"\"\n\n # short-circuit for exact key\n if pat in _registered_options:\n return [pat]\n\n # else look through all of them\n keys = sorted(_registered_options.keys())\n if pat == 'all': # reserved key\n return keys\n\n return [k for k in keys if re.search(pat, k, re.I)]" }, { "instruction": "Write or improve a Python function based on this description:\n\nif key id deprecated and a replacement key defined, will return the\n replacement key, otherwise returns `key` as - is", "output": "def _translate_key(key):\n \"\"\"\n if key id deprecated and a replacement key defined, will return the\n replacement key, otherwise returns `key` as - is\n \"\"\"\n\n d = _get_deprecated_option(key)\n if d:\n return d.rkey or key\n else:\n return key" }, { "instruction": "Write or improve a Python function based on this description:\n\nBuilds a formatted description of a registered option and prints it", "output": "def _build_option_description(k):\n \"\"\" Builds a formatted description of a registered option and prints it \"\"\"\n\n o = _get_registered_option(k)\n d = _get_deprecated_option(k)\n\n s = '{k} '.format(k=k)\n\n if o.doc:\n s += '\\n'.join(o.doc.strip().split('\\n'))\n else:\n s += 'No description available.'\n\n if o:\n s += ('\\n [default: {default}] [currently: {current}]'\n .format(default=o.defval, current=_get_option(k, True)))\n\n if d:\n s += '\\n (Deprecated'\n s += (', use `{rkey}` instead.'\n .format(rkey=d.rkey if d.rkey else ''))\n s += ')'\n\n return s" }, { "instruction": "Write or improve a Python function based on this description:\n\ncontextmanager for multiple invocations of API with a common prefix\n\n supported API functions: (register / get / set )__option\n\n Warning: This is not thread - safe, and won't work properly if you import\n the API functions into your module using the \"from x import y\" construct.\n\n Example:\n\n import pandas._config.config as cf\n with cf.config_prefix(\"display.font\"):\n cf.register_option(\"color\", \"red\")\n cf.register_option(\"size\", \" 5 pt\")\n cf.set_option(size, \" 6 pt\")\n cf.get_option(size)\n ...\n\n etc'\n\n will register options \"display.font.color\", \"display.font.size\", set the\n value of \"display.font.size\"... and so on.", "output": "def config_prefix(prefix):\n \"\"\"contextmanager for multiple invocations of API with a common prefix\n\n supported API functions: (register / get / set )__option\n\n Warning: This is not thread - safe, and won't work properly if you import\n the API functions into your module using the \"from x import y\" construct.\n\n Example:\n\n import pandas._config.config as cf\n with cf.config_prefix(\"display.font\"):\n cf.register_option(\"color\", \"red\")\n cf.register_option(\"size\", \" 5 pt\")\n cf.set_option(size, \" 6 pt\")\n cf.get_option(size)\n ...\n\n etc'\n\n will register options \"display.font.color\", \"display.font.size\", set the\n value of \"display.font.size\"... and so on.\n \"\"\"\n\n # Note: reset_option relies on set_option, and on key directly\n # it does not fit in to this monkey-patching scheme\n\n global register_option, get_option, set_option, reset_option\n\n def wrap(func):\n def inner(key, *args, **kwds):\n pkey = '{prefix}.{key}'.format(prefix=prefix, key=key)\n return func(pkey, *args, **kwds)\n\n return inner\n\n _register_option = register_option\n _get_option = get_option\n _set_option = set_option\n set_option = wrap(set_option)\n get_option = wrap(get_option)\n register_option = wrap(register_option)\n yield None\n set_option = _set_option\n get_option = _get_option\n register_option = _register_option" }, { "instruction": "Write or improve a Python function based on this description:\n\nGenerates (prop, value) pairs from declarations\n\n In a future version may generate parsed tokens from tinycss/tinycss2", "output": "def parse(self, declarations_str):\n \"\"\"Generates (prop, value) pairs from declarations\n\n In a future version may generate parsed tokens from tinycss/tinycss2\n \"\"\"\n for decl in declarations_str.split(';'):\n if not decl.strip():\n continue\n prop, sep, val = decl.partition(':')\n prop = prop.strip().lower()\n # TODO: don't lowercase case sensitive parts of values (strings)\n val = val.strip().lower()\n if sep:\n yield prop, val\n else:\n warnings.warn('Ill-formatted attribute: expected a colon '\n 'in {decl!r}'.format(decl=decl), CSSWarning)" }, { "instruction": "Write or improve a Python function based on this description:\n\nCreate an array.\n\n .. versionadded:: 0.24.0\n\n Parameters\n ----------\n data : Sequence of objects\n The scalars inside `data` should be instances of the\n scalar type for `dtype`. It's expected that `data`\n represents a 1-dimensional array of data.\n\n When `data` is an Index or Series, the underlying array\n will be extracted from `data`.\n\n dtype : str, np.dtype, or ExtensionDtype, optional\n The dtype to use for the array. This may be a NumPy\n dtype or an extension type registered with pandas using\n :meth:`pandas.api.extensions.register_extension_dtype`.\n\n If not specified, there are two possibilities:\n\n 1. When `data` is a :class:`Series`, :class:`Index`, or\n :class:`ExtensionArray`, the `dtype` will be taken\n from the data.\n 2. Otherwise, pandas will attempt to infer the `dtype`\n from the data.\n\n Note that when `data` is a NumPy array, ``data.dtype`` is\n *not* used for inferring the array type. This is because\n NumPy cannot represent all the types of data that can be\n held in extension arrays.\n\n Currently, pandas will infer an extension dtype for sequences of\n\n ============================== =====================================\n Scalar Type Array Type\n ============================== =====================================\n :class:`pandas.Interval` :class:`pandas.arrays.IntervalArray`\n :class:`pandas.Period` :class:`pandas.arrays.PeriodArray`\n :class:`datetime.datetime` :class:`pandas.arrays.DatetimeArray`\n :class:`datetime.timedelta` :class:`pandas.arrays.TimedeltaArray`\n ============================== =====================================\n\n For all other cases, NumPy's usual inference rules will be used.\n\n copy : bool, default True\n Whether to copy the data, even if not necessary. Depending\n on the type of `data`, creating the new array may require\n copying data, even if ``copy=False``.\n\n Returns\n -------\n ExtensionArray\n The newly created array.\n\n Raises\n ------\n ValueError\n When `data` is not 1-dimensional.\n\n See Also\n --------\n numpy.array : Construct a NumPy array.\n Series : Construct a pandas Series.\n Index : Construct a pandas Index.\n arrays.PandasArray : ExtensionArray wrapping a NumPy array.\n Series.array : Extract the array stored within a Series.\n\n Notes\n -----\n Omitting the `dtype` argument means pandas will attempt to infer the\n best array type from the values in the data. As new array types are\n added by pandas and 3rd party libraries, the \"best\" array type may\n change. We recommend specifying `dtype` to ensure that\n\n 1. the correct array type for the data is returned\n 2. the returned array type doesn't change as new extension types\n are added by pandas and third-party libraries\n\n Additionally, if the underlying memory representation of the returned\n array matters, we recommend specifying the `dtype` as a concrete object\n rather than a string alias or allowing it to be inferred. For example,\n a future version of pandas or a 3rd-party library may include a\n dedicated ExtensionArray for string data. In this event, the following\n would no longer return a :class:`arrays.PandasArray` backed by a NumPy\n array.\n\n >>> pd.array(['a', 'b'], dtype=str)\n \n ['a', 'b']\n Length: 2, dtype: str32\n\n This would instead return the new ExtensionArray dedicated for string\n data. If you really need the new array to be backed by a NumPy array,\n specify that in the dtype.\n\n >>> pd.array(['a', 'b'], dtype=np.dtype(\"\n ['a', 'b']\n Length: 2, dtype: str32\n\n Or use the dedicated constructor for the array you're expecting, and\n wrap that in a PandasArray\n\n >>> pd.array(np.array(['a', 'b'], dtype='\n ['a', 'b']\n Length: 2, dtype: str32\n\n Finally, Pandas has arrays that mostly overlap with NumPy\n\n * :class:`arrays.DatetimeArray`\n * :class:`arrays.TimedeltaArray`\n\n When data with a ``datetime64[ns]`` or ``timedelta64[ns]`` dtype is\n passed, pandas will always return a ``DatetimeArray`` or ``TimedeltaArray``\n rather than a ``PandasArray``. This is for symmetry with the case of\n timezone-aware data, which NumPy does not natively support.\n\n >>> pd.array(['2015', '2016'], dtype='datetime64[ns]')\n \n ['2015-01-01 00:00:00', '2016-01-01 00:00:00']\n Length: 2, dtype: datetime64[ns]\n\n >>> pd.array([\"1H\", \"2H\"], dtype='timedelta64[ns]')\n \n ['01:00:00', '02:00:00']\n Length: 2, dtype: timedelta64[ns]\n\n Examples\n --------\n If a dtype is not specified, `data` is passed through to\n :meth:`numpy.array`, and a :class:`arrays.PandasArray` is returned.\n\n >>> pd.array([1, 2])\n \n [1, 2]\n Length: 2, dtype: int64\n\n Or the NumPy dtype can be specified\n\n >>> pd.array([1, 2], dtype=np.dtype(\"int32\"))\n \n [1, 2]\n Length: 2, dtype: int32\n\n You can use the string alias for `dtype`\n\n >>> pd.array(['a', 'b', 'a'], dtype='category')\n [a, b, a]\n Categories (2, object): [a, b]\n\n Or specify the actual dtype\n\n >>> pd.array(['a', 'b', 'a'],\n ... dtype=pd.CategoricalDtype(['a', 'b', 'c'], ordered=True))\n [a, b, a]\n Categories (3, object): [a < b < c]\n\n Because omitting the `dtype` passes the data through to NumPy,\n a mixture of valid integers and NA will return a floating-point\n NumPy array.\n\n >>> pd.array([1, 2, np.nan])\n \n [1.0, 2.0, nan]\n Length: 3, dtype: float64\n\n To use pandas' nullable :class:`pandas.arrays.IntegerArray`, specify\n the dtype:\n\n >>> pd.array([1, 2, np.nan], dtype='Int64')\n \n [1, 2, NaN]\n Length: 3, dtype: Int64\n\n Pandas will infer an ExtensionArray for some types of data:\n\n >>> pd.array([pd.Period('2000', freq=\"D\"), pd.Period(\"2000\", freq=\"D\")])\n \n ['2000-01-01', '2000-01-01']\n Length: 2, dtype: period[D]\n\n `data` must be 1-dimensional. A ValueError is raised when the input\n has the wrong dimensionality.\n\n >>> pd.array(1)\n Traceback (most recent call last):\n ...\n ValueError: Cannot pass scalar '1' to 'pandas.array'.", "output": "def array(data: Sequence[object],\n dtype: Optional[Union[str, np.dtype, ExtensionDtype]] = None,\n copy: bool = True,\n ) -> ABCExtensionArray:\n \"\"\"\n Create an array.\n\n .. versionadded:: 0.24.0\n\n Parameters\n ----------\n data : Sequence of objects\n The scalars inside `data` should be instances of the\n scalar type for `dtype`. It's expected that `data`\n represents a 1-dimensional array of data.\n\n When `data` is an Index or Series, the underlying array\n will be extracted from `data`.\n\n dtype : str, np.dtype, or ExtensionDtype, optional\n The dtype to use for the array. This may be a NumPy\n dtype or an extension type registered with pandas using\n :meth:`pandas.api.extensions.register_extension_dtype`.\n\n If not specified, there are two possibilities:\n\n 1. When `data` is a :class:`Series`, :class:`Index`, or\n :class:`ExtensionArray`, the `dtype` will be taken\n from the data.\n 2. Otherwise, pandas will attempt to infer the `dtype`\n from the data.\n\n Note that when `data` is a NumPy array, ``data.dtype`` is\n *not* used for inferring the array type. This is because\n NumPy cannot represent all the types of data that can be\n held in extension arrays.\n\n Currently, pandas will infer an extension dtype for sequences of\n\n ============================== =====================================\n Scalar Type Array Type\n ============================== =====================================\n :class:`pandas.Interval` :class:`pandas.arrays.IntervalArray`\n :class:`pandas.Period` :class:`pandas.arrays.PeriodArray`\n :class:`datetime.datetime` :class:`pandas.arrays.DatetimeArray`\n :class:`datetime.timedelta` :class:`pandas.arrays.TimedeltaArray`\n ============================== =====================================\n\n For all other cases, NumPy's usual inference rules will be used.\n\n copy : bool, default True\n Whether to copy the data, even if not necessary. Depending\n on the type of `data`, creating the new array may require\n copying data, even if ``copy=False``.\n\n Returns\n -------\n ExtensionArray\n The newly created array.\n\n Raises\n ------\n ValueError\n When `data` is not 1-dimensional.\n\n See Also\n --------\n numpy.array : Construct a NumPy array.\n Series : Construct a pandas Series.\n Index : Construct a pandas Index.\n arrays.PandasArray : ExtensionArray wrapping a NumPy array.\n Series.array : Extract the array stored within a Series.\n\n Notes\n -----\n Omitting the `dtype` argument means pandas will attempt to infer the\n best array type from the values in the data. As new array types are\n added by pandas and 3rd party libraries, the \"best\" array type may\n change. We recommend specifying `dtype` to ensure that\n\n 1. the correct array type for the data is returned\n 2. the returned array type doesn't change as new extension types\n are added by pandas and third-party libraries\n\n Additionally, if the underlying memory representation of the returned\n array matters, we recommend specifying the `dtype` as a concrete object\n rather than a string alias or allowing it to be inferred. For example,\n a future version of pandas or a 3rd-party library may include a\n dedicated ExtensionArray for string data. In this event, the following\n would no longer return a :class:`arrays.PandasArray` backed by a NumPy\n array.\n\n >>> pd.array(['a', 'b'], dtype=str)\n \n ['a', 'b']\n Length: 2, dtype: str32\n\n This would instead return the new ExtensionArray dedicated for string\n data. If you really need the new array to be backed by a NumPy array,\n specify that in the dtype.\n\n >>> pd.array(['a', 'b'], dtype=np.dtype(\"\n ['a', 'b']\n Length: 2, dtype: str32\n\n Or use the dedicated constructor for the array you're expecting, and\n wrap that in a PandasArray\n\n >>> pd.array(np.array(['a', 'b'], dtype='\n ['a', 'b']\n Length: 2, dtype: str32\n\n Finally, Pandas has arrays that mostly overlap with NumPy\n\n * :class:`arrays.DatetimeArray`\n * :class:`arrays.TimedeltaArray`\n\n When data with a ``datetime64[ns]`` or ``timedelta64[ns]`` dtype is\n passed, pandas will always return a ``DatetimeArray`` or ``TimedeltaArray``\n rather than a ``PandasArray``. This is for symmetry with the case of\n timezone-aware data, which NumPy does not natively support.\n\n >>> pd.array(['2015', '2016'], dtype='datetime64[ns]')\n \n ['2015-01-01 00:00:00', '2016-01-01 00:00:00']\n Length: 2, dtype: datetime64[ns]\n\n >>> pd.array([\"1H\", \"2H\"], dtype='timedelta64[ns]')\n \n ['01:00:00', '02:00:00']\n Length: 2, dtype: timedelta64[ns]\n\n Examples\n --------\n If a dtype is not specified, `data` is passed through to\n :meth:`numpy.array`, and a :class:`arrays.PandasArray` is returned.\n\n >>> pd.array([1, 2])\n \n [1, 2]\n Length: 2, dtype: int64\n\n Or the NumPy dtype can be specified\n\n >>> pd.array([1, 2], dtype=np.dtype(\"int32\"))\n \n [1, 2]\n Length: 2, dtype: int32\n\n You can use the string alias for `dtype`\n\n >>> pd.array(['a', 'b', 'a'], dtype='category')\n [a, b, a]\n Categories (2, object): [a, b]\n\n Or specify the actual dtype\n\n >>> pd.array(['a', 'b', 'a'],\n ... dtype=pd.CategoricalDtype(['a', 'b', 'c'], ordered=True))\n [a, b, a]\n Categories (3, object): [a < b < c]\n\n Because omitting the `dtype` passes the data through to NumPy,\n a mixture of valid integers and NA will return a floating-point\n NumPy array.\n\n >>> pd.array([1, 2, np.nan])\n \n [1.0, 2.0, nan]\n Length: 3, dtype: float64\n\n To use pandas' nullable :class:`pandas.arrays.IntegerArray`, specify\n the dtype:\n\n >>> pd.array([1, 2, np.nan], dtype='Int64')\n \n [1, 2, NaN]\n Length: 3, dtype: Int64\n\n Pandas will infer an ExtensionArray for some types of data:\n\n >>> pd.array([pd.Period('2000', freq=\"D\"), pd.Period(\"2000\", freq=\"D\")])\n \n ['2000-01-01', '2000-01-01']\n Length: 2, dtype: period[D]\n\n `data` must be 1-dimensional. A ValueError is raised when the input\n has the wrong dimensionality.\n\n >>> pd.array(1)\n Traceback (most recent call last):\n ...\n ValueError: Cannot pass scalar '1' to 'pandas.array'.\n \"\"\"\n from pandas.core.arrays import (\n period_array, ExtensionArray, IntervalArray, PandasArray,\n DatetimeArray,\n TimedeltaArray,\n )\n from pandas.core.internals.arrays import extract_array\n\n if lib.is_scalar(data):\n msg = (\n \"Cannot pass scalar '{}' to 'pandas.array'.\"\n )\n raise ValueError(msg.format(data))\n\n data = extract_array(data, extract_numpy=True)\n\n if dtype is None and isinstance(data, ExtensionArray):\n dtype = data.dtype\n\n # this returns None for not-found dtypes.\n if isinstance(dtype, str):\n dtype = registry.find(dtype) or dtype\n\n if is_extension_array_dtype(dtype):\n cls = dtype.construct_array_type()\n return cls._from_sequence(data, dtype=dtype, copy=copy)\n\n if dtype is None:\n inferred_dtype = lib.infer_dtype(data, skipna=False)\n if inferred_dtype == 'period':\n try:\n return period_array(data, copy=copy)\n except tslibs.IncompatibleFrequency:\n # We may have a mixture of frequencies.\n # We choose to return an ndarray, rather than raising.\n pass\n elif inferred_dtype == 'interval':\n try:\n return IntervalArray(data, copy=copy)\n except ValueError:\n # We may have a mixture of `closed` here.\n # We choose to return an ndarray, rather than raising.\n pass\n\n elif inferred_dtype.startswith('datetime'):\n # datetime, datetime64\n try:\n return DatetimeArray._from_sequence(data, copy=copy)\n except ValueError:\n # Mixture of timezones, fall back to PandasArray\n pass\n\n elif inferred_dtype.startswith('timedelta'):\n # timedelta, timedelta64\n return TimedeltaArray._from_sequence(data, copy=copy)\n\n # TODO(BooleanArray): handle this type\n\n # Pandas overrides NumPy for\n # 1. datetime64[ns]\n # 2. timedelta64[ns]\n # so that a DatetimeArray is returned.\n if is_datetime64_ns_dtype(dtype):\n return DatetimeArray._from_sequence(data, dtype=dtype, copy=copy)\n elif is_timedelta64_ns_dtype(dtype):\n return TimedeltaArray._from_sequence(data, dtype=dtype, copy=copy)\n\n result = PandasArray._from_sequence(data, dtype=dtype, copy=copy)\n return result" }, { "instruction": "Write or improve a Python function based on this description:\n\nTry to do platform conversion, with special casing for IntervalArray.\n Wrapper around maybe_convert_platform that alters the default return\n dtype in certain cases to be compatible with IntervalArray. For example,\n empty lists return with integer dtype instead of object dtype, which is\n prohibited for IntervalArray.\n\n Parameters\n ----------\n values : array-like\n\n Returns\n -------\n array", "output": "def maybe_convert_platform_interval(values):\n \"\"\"\n Try to do platform conversion, with special casing for IntervalArray.\n Wrapper around maybe_convert_platform that alters the default return\n dtype in certain cases to be compatible with IntervalArray. For example,\n empty lists return with integer dtype instead of object dtype, which is\n prohibited for IntervalArray.\n\n Parameters\n ----------\n values : array-like\n\n Returns\n -------\n array\n \"\"\"\n if isinstance(values, (list, tuple)) and len(values) == 0:\n # GH 19016\n # empty lists/tuples get object dtype by default, but this is not\n # prohibited for IntervalArray, so coerce to integer instead\n return np.array([], dtype=np.int64)\n elif is_categorical_dtype(values):\n values = np.asarray(values)\n\n return maybe_convert_platform(values)" }, { "instruction": "Write or improve a Python function based on this description:\n\nCheck if the object is a file-like object.\n\n For objects to be considered file-like, they must\n be an iterator AND have either a `read` and/or `write`\n method as an attribute.\n\n Note: file-like objects must be iterable, but\n iterable objects need not be file-like.\n\n .. versionadded:: 0.20.0\n\n Parameters\n ----------\n obj : The object to check\n\n Returns\n -------\n is_file_like : bool\n Whether `obj` has file-like properties.\n\n Examples\n --------\n >>> buffer(StringIO(\"data\"))\n >>> is_file_like(buffer)\n True\n >>> is_file_like([1, 2, 3])\n False", "output": "def is_file_like(obj):\n \"\"\"\n Check if the object is a file-like object.\n\n For objects to be considered file-like, they must\n be an iterator AND have either a `read` and/or `write`\n method as an attribute.\n\n Note: file-like objects must be iterable, but\n iterable objects need not be file-like.\n\n .. versionadded:: 0.20.0\n\n Parameters\n ----------\n obj : The object to check\n\n Returns\n -------\n is_file_like : bool\n Whether `obj` has file-like properties.\n\n Examples\n --------\n >>> buffer(StringIO(\"data\"))\n >>> is_file_like(buffer)\n True\n >>> is_file_like([1, 2, 3])\n False\n \"\"\"\n\n if not (hasattr(obj, 'read') or hasattr(obj, 'write')):\n return False\n\n if not hasattr(obj, \"__iter__\"):\n return False\n\n return True" }, { "instruction": "Write or improve a Python function based on this description:\n\nCheck if the object is list-like.\n\n Objects that are considered list-like are for example Python\n lists, tuples, sets, NumPy arrays, and Pandas Series.\n\n Strings and datetime objects, however, are not considered list-like.\n\n Parameters\n ----------\n obj : The object to check\n allow_sets : boolean, default True\n If this parameter is False, sets will not be considered list-like\n\n .. versionadded:: 0.24.0\n\n Returns\n -------\n is_list_like : bool\n Whether `obj` has list-like properties.\n\n Examples\n --------\n >>> is_list_like([1, 2, 3])\n True\n >>> is_list_like({1, 2, 3})\n True\n >>> is_list_like(datetime(2017, 1, 1))\n False\n >>> is_list_like(\"foo\")\n False\n >>> is_list_like(1)\n False\n >>> is_list_like(np.array([2]))\n True\n >>> is_list_like(np.array(2)))\n False", "output": "def is_list_like(obj, allow_sets=True):\n \"\"\"\n Check if the object is list-like.\n\n Objects that are considered list-like are for example Python\n lists, tuples, sets, NumPy arrays, and Pandas Series.\n\n Strings and datetime objects, however, are not considered list-like.\n\n Parameters\n ----------\n obj : The object to check\n allow_sets : boolean, default True\n If this parameter is False, sets will not be considered list-like\n\n .. versionadded:: 0.24.0\n\n Returns\n -------\n is_list_like : bool\n Whether `obj` has list-like properties.\n\n Examples\n --------\n >>> is_list_like([1, 2, 3])\n True\n >>> is_list_like({1, 2, 3})\n True\n >>> is_list_like(datetime(2017, 1, 1))\n False\n >>> is_list_like(\"foo\")\n False\n >>> is_list_like(1)\n False\n >>> is_list_like(np.array([2]))\n True\n >>> is_list_like(np.array(2)))\n False\n \"\"\"\n\n return (isinstance(obj, abc.Iterable) and\n # we do not count strings/unicode/bytes as list-like\n not isinstance(obj, (str, bytes)) and\n\n # exclude zero-dimensional numpy arrays, effectively scalars\n not (isinstance(obj, np.ndarray) and obj.ndim == 0) and\n\n # exclude sets if allow_sets is False\n not (allow_sets is False and isinstance(obj, abc.Set)))" }, { "instruction": "Write or improve a Python function based on this description:\n\nCheck if the object is list-like, and that all of its elements\n are also list-like.\n\n .. versionadded:: 0.20.0\n\n Parameters\n ----------\n obj : The object to check\n\n Returns\n -------\n is_list_like : bool\n Whether `obj` has list-like properties.\n\n Examples\n --------\n >>> is_nested_list_like([[1, 2, 3]])\n True\n >>> is_nested_list_like([{1, 2, 3}, {1, 2, 3}])\n True\n >>> is_nested_list_like([\"foo\"])\n False\n >>> is_nested_list_like([])\n False\n >>> is_nested_list_like([[1, 2, 3], 1])\n False\n\n Notes\n -----\n This won't reliably detect whether a consumable iterator (e. g.\n a generator) is a nested-list-like without consuming the iterator.\n To avoid consuming it, we always return False if the outer container\n doesn't define `__len__`.\n\n See Also\n --------\n is_list_like", "output": "def is_nested_list_like(obj):\n \"\"\"\n Check if the object is list-like, and that all of its elements\n are also list-like.\n\n .. versionadded:: 0.20.0\n\n Parameters\n ----------\n obj : The object to check\n\n Returns\n -------\n is_list_like : bool\n Whether `obj` has list-like properties.\n\n Examples\n --------\n >>> is_nested_list_like([[1, 2, 3]])\n True\n >>> is_nested_list_like([{1, 2, 3}, {1, 2, 3}])\n True\n >>> is_nested_list_like([\"foo\"])\n False\n >>> is_nested_list_like([])\n False\n >>> is_nested_list_like([[1, 2, 3], 1])\n False\n\n Notes\n -----\n This won't reliably detect whether a consumable iterator (e. g.\n a generator) is a nested-list-like without consuming the iterator.\n To avoid consuming it, we always return False if the outer container\n doesn't define `__len__`.\n\n See Also\n --------\n is_list_like\n \"\"\"\n return (is_list_like(obj) and hasattr(obj, '__len__') and\n len(obj) > 0 and all(is_list_like(item) for item in obj))" }, { "instruction": "Write or improve a Python function based on this description:\n\nCheck if the object is dict-like.\n\n Parameters\n ----------\n obj : The object to check\n\n Returns\n -------\n is_dict_like : bool\n Whether `obj` has dict-like properties.\n\n Examples\n --------\n >>> is_dict_like({1: 2})\n True\n >>> is_dict_like([1, 2, 3])\n False\n >>> is_dict_like(dict)\n False\n >>> is_dict_like(dict())\n True", "output": "def is_dict_like(obj):\n \"\"\"\n Check if the object is dict-like.\n\n Parameters\n ----------\n obj : The object to check\n\n Returns\n -------\n is_dict_like : bool\n Whether `obj` has dict-like properties.\n\n Examples\n --------\n >>> is_dict_like({1: 2})\n True\n >>> is_dict_like([1, 2, 3])\n False\n >>> is_dict_like(dict)\n False\n >>> is_dict_like(dict())\n True\n \"\"\"\n dict_like_attrs = (\"__getitem__\", \"keys\", \"__contains__\")\n return (all(hasattr(obj, attr) for attr in dict_like_attrs)\n # [GH 25196] exclude classes\n and not isinstance(obj, type))" }, { "instruction": "Write or improve a Python function based on this description:\n\nCheck if the object is a sequence of objects.\n String types are not included as sequences here.\n\n Parameters\n ----------\n obj : The object to check\n\n Returns\n -------\n is_sequence : bool\n Whether `obj` is a sequence of objects.\n\n Examples\n --------\n >>> l = [1, 2, 3]\n >>>\n >>> is_sequence(l)\n True\n >>> is_sequence(iter(l))\n False", "output": "def is_sequence(obj):\n \"\"\"\n Check if the object is a sequence of objects.\n String types are not included as sequences here.\n\n Parameters\n ----------\n obj : The object to check\n\n Returns\n -------\n is_sequence : bool\n Whether `obj` is a sequence of objects.\n\n Examples\n --------\n >>> l = [1, 2, 3]\n >>>\n >>> is_sequence(l)\n True\n >>> is_sequence(iter(l))\n False\n \"\"\"\n\n try:\n iter(obj) # Can iterate over it.\n len(obj) # Has a length associated with it.\n return not isinstance(obj, (str, bytes))\n except (TypeError, AttributeError):\n return False" }, { "instruction": "Write or improve a Python function based on this description:\n\nThis is called upon unpickling, rather than the default which doesn't\n have arguments and breaks __new__", "output": "def _new_DatetimeIndex(cls, d):\n \"\"\" This is called upon unpickling, rather than the default which doesn't\n have arguments and breaks __new__ \"\"\"\n\n if \"data\" in d and not isinstance(d[\"data\"], DatetimeIndex):\n # Avoid need to verify integrity by calling simple_new directly\n data = d.pop(\"data\")\n result = cls._simple_new(data, **d)\n else:\n with warnings.catch_warnings():\n # we ignore warnings from passing verify_integrity=False\n # TODO: If we knew what was going in to **d, we might be able to\n # go through _simple_new instead\n warnings.simplefilter(\"ignore\")\n result = cls.__new__(cls, verify_integrity=False, **d)\n\n return result" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn a fixed frequency DatetimeIndex.\n\n Parameters\n ----------\n start : str or datetime-like, optional\n Left bound for generating dates.\n end : str or datetime-like, optional\n Right bound for generating dates.\n periods : integer, optional\n Number of periods to generate.\n freq : str or DateOffset, default 'D'\n Frequency strings can have multiples, e.g. '5H'. See\n :ref:`here ` for a list of\n frequency aliases.\n tz : str or tzinfo, optional\n Time zone name for returning localized DatetimeIndex, for example\n 'Asia/Hong_Kong'. By default, the resulting DatetimeIndex is\n timezone-naive.\n normalize : bool, default False\n Normalize start/end dates to midnight before generating date range.\n name : str, default None\n Name of the resulting DatetimeIndex.\n closed : {None, 'left', 'right'}, optional\n Make the interval closed with respect to the given frequency to\n the 'left', 'right', or both sides (None, the default).\n **kwargs\n For compatibility. Has no effect on the result.\n\n Returns\n -------\n rng : DatetimeIndex\n\n See Also\n --------\n DatetimeIndex : An immutable container for datetimes.\n timedelta_range : Return a fixed frequency TimedeltaIndex.\n period_range : Return a fixed frequency PeriodIndex.\n interval_range : Return a fixed frequency IntervalIndex.\n\n Notes\n -----\n Of the four parameters ``start``, ``end``, ``periods``, and ``freq``,\n exactly three must be specified. If ``freq`` is omitted, the resulting\n ``DatetimeIndex`` will have ``periods`` linearly spaced elements between\n ``start`` and ``end`` (closed on both sides).\n\n To learn more about the frequency strings, please see `this link\n `__.\n\n Examples\n --------\n **Specifying the values**\n\n The next four examples generate the same `DatetimeIndex`, but vary\n the combination of `start`, `end` and `periods`.\n\n Specify `start` and `end`, with the default daily frequency.\n\n >>> pd.date_range(start='1/1/2018', end='1/08/2018')\n DatetimeIndex(['2018-01-01', '2018-01-02', '2018-01-03', '2018-01-04',\n '2018-01-05', '2018-01-06', '2018-01-07', '2018-01-08'],\n dtype='datetime64[ns]', freq='D')\n\n Specify `start` and `periods`, the number of periods (days).\n\n >>> pd.date_range(start='1/1/2018', periods=8)\n DatetimeIndex(['2018-01-01', '2018-01-02', '2018-01-03', '2018-01-04',\n '2018-01-05', '2018-01-06', '2018-01-07', '2018-01-08'],\n dtype='datetime64[ns]', freq='D')\n\n Specify `end` and `periods`, the number of periods (days).\n\n >>> pd.date_range(end='1/1/2018', periods=8)\n DatetimeIndex(['2017-12-25', '2017-12-26', '2017-12-27', '2017-12-28',\n '2017-12-29', '2017-12-30', '2017-12-31', '2018-01-01'],\n dtype='datetime64[ns]', freq='D')\n\n Specify `start`, `end`, and `periods`; the frequency is generated\n automatically (linearly spaced).\n\n >>> pd.date_range(start='2018-04-24', end='2018-04-27', periods=3)\n DatetimeIndex(['2018-04-24 00:00:00', '2018-04-25 12:00:00',\n '2018-04-27 00:00:00'],\n dtype='datetime64[ns]', freq=None)\n\n **Other Parameters**\n\n Changed the `freq` (frequency) to ``'M'`` (month end frequency).\n\n >>> pd.date_range(start='1/1/2018', periods=5, freq='M')\n DatetimeIndex(['2018-01-31', '2018-02-28', '2018-03-31', '2018-04-30',\n '2018-05-31'],\n dtype='datetime64[ns]', freq='M')\n\n Multiples are allowed\n\n >>> pd.date_range(start='1/1/2018', periods=5, freq='3M')\n DatetimeIndex(['2018-01-31', '2018-04-30', '2018-07-31', '2018-10-31',\n '2019-01-31'],\n dtype='datetime64[ns]', freq='3M')\n\n `freq` can also be specified as an Offset object.\n\n >>> pd.date_range(start='1/1/2018', periods=5, freq=pd.offsets.MonthEnd(3))\n DatetimeIndex(['2018-01-31', '2018-04-30', '2018-07-31', '2018-10-31',\n '2019-01-31'],\n dtype='datetime64[ns]', freq='3M')\n\n Specify `tz` to set the timezone.\n\n >>> pd.date_range(start='1/1/2018', periods=5, tz='Asia/Tokyo')\n DatetimeIndex(['2018-01-01 00:00:00+09:00', '2018-01-02 00:00:00+09:00',\n '2018-01-03 00:00:00+09:00', '2018-01-04 00:00:00+09:00',\n '2018-01-05 00:00:00+09:00'],\n dtype='datetime64[ns, Asia/Tokyo]', freq='D')\n\n `closed` controls whether to include `start` and `end` that are on the\n boundary. The default includes boundary points on either end.\n\n >>> pd.date_range(start='2017-01-01', end='2017-01-04', closed=None)\n DatetimeIndex(['2017-01-01', '2017-01-02', '2017-01-03', '2017-01-04'],\n dtype='datetime64[ns]', freq='D')\n\n Use ``closed='left'`` to exclude `end` if it falls on the boundary.\n\n >>> pd.date_range(start='2017-01-01', end='2017-01-04', closed='left')\n DatetimeIndex(['2017-01-01', '2017-01-02', '2017-01-03'],\n dtype='datetime64[ns]', freq='D')\n\n Use ``closed='right'`` to exclude `start` if it falls on the boundary.\n\n >>> pd.date_range(start='2017-01-01', end='2017-01-04', closed='right')\n DatetimeIndex(['2017-01-02', '2017-01-03', '2017-01-04'],\n dtype='datetime64[ns]', freq='D')", "output": "def date_range(start=None, end=None, periods=None, freq=None, tz=None,\n normalize=False, name=None, closed=None, **kwargs):\n \"\"\"\n Return a fixed frequency DatetimeIndex.\n\n Parameters\n ----------\n start : str or datetime-like, optional\n Left bound for generating dates.\n end : str or datetime-like, optional\n Right bound for generating dates.\n periods : integer, optional\n Number of periods to generate.\n freq : str or DateOffset, default 'D'\n Frequency strings can have multiples, e.g. '5H'. See\n :ref:`here ` for a list of\n frequency aliases.\n tz : str or tzinfo, optional\n Time zone name for returning localized DatetimeIndex, for example\n 'Asia/Hong_Kong'. By default, the resulting DatetimeIndex is\n timezone-naive.\n normalize : bool, default False\n Normalize start/end dates to midnight before generating date range.\n name : str, default None\n Name of the resulting DatetimeIndex.\n closed : {None, 'left', 'right'}, optional\n Make the interval closed with respect to the given frequency to\n the 'left', 'right', or both sides (None, the default).\n **kwargs\n For compatibility. Has no effect on the result.\n\n Returns\n -------\n rng : DatetimeIndex\n\n See Also\n --------\n DatetimeIndex : An immutable container for datetimes.\n timedelta_range : Return a fixed frequency TimedeltaIndex.\n period_range : Return a fixed frequency PeriodIndex.\n interval_range : Return a fixed frequency IntervalIndex.\n\n Notes\n -----\n Of the four parameters ``start``, ``end``, ``periods``, and ``freq``,\n exactly three must be specified. If ``freq`` is omitted, the resulting\n ``DatetimeIndex`` will have ``periods`` linearly spaced elements between\n ``start`` and ``end`` (closed on both sides).\n\n To learn more about the frequency strings, please see `this link\n `__.\n\n Examples\n --------\n **Specifying the values**\n\n The next four examples generate the same `DatetimeIndex`, but vary\n the combination of `start`, `end` and `periods`.\n\n Specify `start` and `end`, with the default daily frequency.\n\n >>> pd.date_range(start='1/1/2018', end='1/08/2018')\n DatetimeIndex(['2018-01-01', '2018-01-02', '2018-01-03', '2018-01-04',\n '2018-01-05', '2018-01-06', '2018-01-07', '2018-01-08'],\n dtype='datetime64[ns]', freq='D')\n\n Specify `start` and `periods`, the number of periods (days).\n\n >>> pd.date_range(start='1/1/2018', periods=8)\n DatetimeIndex(['2018-01-01', '2018-01-02', '2018-01-03', '2018-01-04',\n '2018-01-05', '2018-01-06', '2018-01-07', '2018-01-08'],\n dtype='datetime64[ns]', freq='D')\n\n Specify `end` and `periods`, the number of periods (days).\n\n >>> pd.date_range(end='1/1/2018', periods=8)\n DatetimeIndex(['2017-12-25', '2017-12-26', '2017-12-27', '2017-12-28',\n '2017-12-29', '2017-12-30', '2017-12-31', '2018-01-01'],\n dtype='datetime64[ns]', freq='D')\n\n Specify `start`, `end`, and `periods`; the frequency is generated\n automatically (linearly spaced).\n\n >>> pd.date_range(start='2018-04-24', end='2018-04-27', periods=3)\n DatetimeIndex(['2018-04-24 00:00:00', '2018-04-25 12:00:00',\n '2018-04-27 00:00:00'],\n dtype='datetime64[ns]', freq=None)\n\n **Other Parameters**\n\n Changed the `freq` (frequency) to ``'M'`` (month end frequency).\n\n >>> pd.date_range(start='1/1/2018', periods=5, freq='M')\n DatetimeIndex(['2018-01-31', '2018-02-28', '2018-03-31', '2018-04-30',\n '2018-05-31'],\n dtype='datetime64[ns]', freq='M')\n\n Multiples are allowed\n\n >>> pd.date_range(start='1/1/2018', periods=5, freq='3M')\n DatetimeIndex(['2018-01-31', '2018-04-30', '2018-07-31', '2018-10-31',\n '2019-01-31'],\n dtype='datetime64[ns]', freq='3M')\n\n `freq` can also be specified as an Offset object.\n\n >>> pd.date_range(start='1/1/2018', periods=5, freq=pd.offsets.MonthEnd(3))\n DatetimeIndex(['2018-01-31', '2018-04-30', '2018-07-31', '2018-10-31',\n '2019-01-31'],\n dtype='datetime64[ns]', freq='3M')\n\n Specify `tz` to set the timezone.\n\n >>> pd.date_range(start='1/1/2018', periods=5, tz='Asia/Tokyo')\n DatetimeIndex(['2018-01-01 00:00:00+09:00', '2018-01-02 00:00:00+09:00',\n '2018-01-03 00:00:00+09:00', '2018-01-04 00:00:00+09:00',\n '2018-01-05 00:00:00+09:00'],\n dtype='datetime64[ns, Asia/Tokyo]', freq='D')\n\n `closed` controls whether to include `start` and `end` that are on the\n boundary. The default includes boundary points on either end.\n\n >>> pd.date_range(start='2017-01-01', end='2017-01-04', closed=None)\n DatetimeIndex(['2017-01-01', '2017-01-02', '2017-01-03', '2017-01-04'],\n dtype='datetime64[ns]', freq='D')\n\n Use ``closed='left'`` to exclude `end` if it falls on the boundary.\n\n >>> pd.date_range(start='2017-01-01', end='2017-01-04', closed='left')\n DatetimeIndex(['2017-01-01', '2017-01-02', '2017-01-03'],\n dtype='datetime64[ns]', freq='D')\n\n Use ``closed='right'`` to exclude `start` if it falls on the boundary.\n\n >>> pd.date_range(start='2017-01-01', end='2017-01-04', closed='right')\n DatetimeIndex(['2017-01-02', '2017-01-03', '2017-01-04'],\n dtype='datetime64[ns]', freq='D')\n \"\"\"\n\n if freq is None and com._any_none(periods, start, end):\n freq = 'D'\n\n dtarr = DatetimeArray._generate_range(\n start=start, end=end, periods=periods,\n freq=freq, tz=tz, normalize=normalize,\n closed=closed, **kwargs)\n return DatetimeIndex._simple_new(\n dtarr, tz=dtarr.tz, freq=dtarr.freq, name=name)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn a fixed frequency DatetimeIndex, with business day as the default\n frequency\n\n Parameters\n ----------\n start : string or datetime-like, default None\n Left bound for generating dates.\n end : string or datetime-like, default None\n Right bound for generating dates.\n periods : integer, default None\n Number of periods to generate.\n freq : string or DateOffset, default 'B' (business daily)\n Frequency strings can have multiples, e.g. '5H'.\n tz : string or None\n Time zone name for returning localized DatetimeIndex, for example\n Asia/Beijing.\n normalize : bool, default False\n Normalize start/end dates to midnight before generating date range.\n name : string, default None\n Name of the resulting DatetimeIndex.\n weekmask : string or None, default None\n Weekmask of valid business days, passed to ``numpy.busdaycalendar``,\n only used when custom frequency strings are passed. The default\n value None is equivalent to 'Mon Tue Wed Thu Fri'.\n\n .. versionadded:: 0.21.0\n\n holidays : list-like or None, default None\n Dates to exclude from the set of valid business days, passed to\n ``numpy.busdaycalendar``, only used when custom frequency strings\n are passed.\n\n .. versionadded:: 0.21.0\n\n closed : string, default None\n Make the interval closed with respect to the given frequency to\n the 'left', 'right', or both sides (None).\n **kwargs\n For compatibility. Has no effect on the result.\n\n Returns\n -------\n DatetimeIndex\n\n Notes\n -----\n Of the four parameters: ``start``, ``end``, ``periods``, and ``freq``,\n exactly three must be specified. Specifying ``freq`` is a requirement\n for ``bdate_range``. Use ``date_range`` if specifying ``freq`` is not\n desired.\n\n To learn more about the frequency strings, please see `this link\n `__.\n\n Examples\n --------\n Note how the two weekend days are skipped in the result.\n\n >>> pd.bdate_range(start='1/1/2018', end='1/08/2018')\n DatetimeIndex(['2018-01-01', '2018-01-02', '2018-01-03', '2018-01-04',\n '2018-01-05', '2018-01-08'],\n dtype='datetime64[ns]', freq='B')", "output": "def bdate_range(start=None, end=None, periods=None, freq='B', tz=None,\n normalize=True, name=None, weekmask=None, holidays=None,\n closed=None, **kwargs):\n \"\"\"\n Return a fixed frequency DatetimeIndex, with business day as the default\n frequency\n\n Parameters\n ----------\n start : string or datetime-like, default None\n Left bound for generating dates.\n end : string or datetime-like, default None\n Right bound for generating dates.\n periods : integer, default None\n Number of periods to generate.\n freq : string or DateOffset, default 'B' (business daily)\n Frequency strings can have multiples, e.g. '5H'.\n tz : string or None\n Time zone name for returning localized DatetimeIndex, for example\n Asia/Beijing.\n normalize : bool, default False\n Normalize start/end dates to midnight before generating date range.\n name : string, default None\n Name of the resulting DatetimeIndex.\n weekmask : string or None, default None\n Weekmask of valid business days, passed to ``numpy.busdaycalendar``,\n only used when custom frequency strings are passed. The default\n value None is equivalent to 'Mon Tue Wed Thu Fri'.\n\n .. versionadded:: 0.21.0\n\n holidays : list-like or None, default None\n Dates to exclude from the set of valid business days, passed to\n ``numpy.busdaycalendar``, only used when custom frequency strings\n are passed.\n\n .. versionadded:: 0.21.0\n\n closed : string, default None\n Make the interval closed with respect to the given frequency to\n the 'left', 'right', or both sides (None).\n **kwargs\n For compatibility. Has no effect on the result.\n\n Returns\n -------\n DatetimeIndex\n\n Notes\n -----\n Of the four parameters: ``start``, ``end``, ``periods``, and ``freq``,\n exactly three must be specified. Specifying ``freq`` is a requirement\n for ``bdate_range``. Use ``date_range`` if specifying ``freq`` is not\n desired.\n\n To learn more about the frequency strings, please see `this link\n `__.\n\n Examples\n --------\n Note how the two weekend days are skipped in the result.\n\n >>> pd.bdate_range(start='1/1/2018', end='1/08/2018')\n DatetimeIndex(['2018-01-01', '2018-01-02', '2018-01-03', '2018-01-04',\n '2018-01-05', '2018-01-08'],\n dtype='datetime64[ns]', freq='B')\n \"\"\"\n if freq is None:\n msg = 'freq must be specified for bdate_range; use date_range instead'\n raise TypeError(msg)\n\n if is_string_like(freq) and freq.startswith('C'):\n try:\n weekmask = weekmask or 'Mon Tue Wed Thu Fri'\n freq = prefix_mapping[freq](holidays=holidays, weekmask=weekmask)\n except (KeyError, TypeError):\n msg = 'invalid custom frequency string: {freq}'.format(freq=freq)\n raise ValueError(msg)\n elif holidays or weekmask:\n msg = ('a custom frequency string is required when holidays or '\n 'weekmask are passed, got frequency {freq}').format(freq=freq)\n raise ValueError(msg)\n\n return date_range(start=start, end=end, periods=periods,\n freq=freq, tz=tz, normalize=normalize, name=name,\n closed=closed, **kwargs)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn a fixed frequency DatetimeIndex, with CustomBusinessDay as the\n default frequency\n\n .. deprecated:: 0.21.0\n\n Parameters\n ----------\n start : string or datetime-like, default None\n Left bound for generating dates\n end : string or datetime-like, default None\n Right bound for generating dates\n periods : integer, default None\n Number of periods to generate\n freq : string or DateOffset, default 'C' (CustomBusinessDay)\n Frequency strings can have multiples, e.g. '5H'\n tz : string, default None\n Time zone name for returning localized DatetimeIndex, for example\n Asia/Beijing\n normalize : bool, default False\n Normalize start/end dates to midnight before generating date range\n name : string, default None\n Name of the resulting DatetimeIndex\n weekmask : string, Default 'Mon Tue Wed Thu Fri'\n weekmask of valid business days, passed to ``numpy.busdaycalendar``\n holidays : list\n list/array of dates to exclude from the set of valid business days,\n passed to ``numpy.busdaycalendar``\n closed : string, default None\n Make the interval closed with respect to the given frequency to\n the 'left', 'right', or both sides (None)\n\n Notes\n -----\n Of the three parameters: ``start``, ``end``, and ``periods``, exactly two\n must be specified.\n\n To learn more about the frequency strings, please see `this link\n `__.\n\n Returns\n -------\n rng : DatetimeIndex", "output": "def cdate_range(start=None, end=None, periods=None, freq='C', tz=None,\n normalize=True, name=None, closed=None, **kwargs):\n \"\"\"\n Return a fixed frequency DatetimeIndex, with CustomBusinessDay as the\n default frequency\n\n .. deprecated:: 0.21.0\n\n Parameters\n ----------\n start : string or datetime-like, default None\n Left bound for generating dates\n end : string or datetime-like, default None\n Right bound for generating dates\n periods : integer, default None\n Number of periods to generate\n freq : string or DateOffset, default 'C' (CustomBusinessDay)\n Frequency strings can have multiples, e.g. '5H'\n tz : string, default None\n Time zone name for returning localized DatetimeIndex, for example\n Asia/Beijing\n normalize : bool, default False\n Normalize start/end dates to midnight before generating date range\n name : string, default None\n Name of the resulting DatetimeIndex\n weekmask : string, Default 'Mon Tue Wed Thu Fri'\n weekmask of valid business days, passed to ``numpy.busdaycalendar``\n holidays : list\n list/array of dates to exclude from the set of valid business days,\n passed to ``numpy.busdaycalendar``\n closed : string, default None\n Make the interval closed with respect to the given frequency to\n the 'left', 'right', or both sides (None)\n\n Notes\n -----\n Of the three parameters: ``start``, ``end``, and ``periods``, exactly two\n must be specified.\n\n To learn more about the frequency strings, please see `this link\n `__.\n\n Returns\n -------\n rng : DatetimeIndex\n \"\"\"\n warnings.warn(\"cdate_range is deprecated and will be removed in a future \"\n \"version, instead use pd.bdate_range(..., freq='{freq}')\"\n .format(freq=freq), FutureWarning, stacklevel=2)\n\n if freq == 'C':\n holidays = kwargs.pop('holidays', [])\n weekmask = kwargs.pop('weekmask', 'Mon Tue Wed Thu Fri')\n freq = CDay(holidays=holidays, weekmask=weekmask)\n\n return date_range(start=start, end=end, periods=periods, freq=freq,\n tz=tz, normalize=normalize, name=name,\n closed=closed, **kwargs)" }, { "instruction": "Write or improve a Python function based on this description:\n\nSplit data into blocks & return conformed data.", "output": "def _create_blocks(self):\n \"\"\"\n Split data into blocks & return conformed data.\n \"\"\"\n\n obj, index = self._convert_freq()\n if index is not None:\n index = self._on\n\n # filter out the on from the object\n if self.on is not None:\n if obj.ndim == 2:\n obj = obj.reindex(columns=obj.columns.difference([self.on]),\n copy=False)\n blocks = obj._to_dict_of_blocks(copy=False).values()\n\n return blocks, obj, index" }, { "instruction": "Write or improve a Python function based on this description:\n\nSub-classes to define. Return a sliced object.\n\n Parameters\n ----------\n key : str / list of selections\n ndim : 1,2\n requested ndim of result\n subset : object, default None\n subset to act on", "output": "def _gotitem(self, key, ndim, subset=None):\n \"\"\"\n Sub-classes to define. Return a sliced object.\n\n Parameters\n ----------\n key : str / list of selections\n ndim : 1,2\n requested ndim of result\n subset : object, default None\n subset to act on\n \"\"\"\n\n # create a new object to prevent aliasing\n if subset is None:\n subset = self.obj\n self = self._shallow_copy(subset)\n self._reset_cache()\n if subset.ndim == 2:\n if is_scalar(key) and key in subset or is_list_like(key):\n self._selection = key\n return self" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn index as ndarrays.\n\n Returns\n -------\n tuple of (index, index_as_ndarray)", "output": "def _get_index(self, index=None):\n \"\"\"\n Return index as ndarrays.\n\n Returns\n -------\n tuple of (index, index_as_ndarray)\n \"\"\"\n\n if self.is_freq_type:\n if index is None:\n index = self._on\n return index, index.asi8\n return index, index" }, { "instruction": "Write or improve a Python function based on this description:\n\nWrap a single result.", "output": "def _wrap_result(self, result, block=None, obj=None):\n \"\"\"\n Wrap a single result.\n \"\"\"\n\n if obj is None:\n obj = self._selected_obj\n index = obj.index\n\n if isinstance(result, np.ndarray):\n\n # coerce if necessary\n if block is not None:\n if is_timedelta64_dtype(block.values.dtype):\n from pandas import to_timedelta\n result = to_timedelta(\n result.ravel(), unit='ns').values.reshape(result.shape)\n\n if result.ndim == 1:\n from pandas import Series\n return Series(result, index, name=obj.name)\n\n return type(obj)(result, index=index, columns=block.columns)\n return result" }, { "instruction": "Write or improve a Python function based on this description:\n\nWrap the results.\n\n Parameters\n ----------\n results : list of ndarrays\n blocks : list of blocks\n obj : conformed data (may be resampled)", "output": "def _wrap_results(self, results, blocks, obj):\n \"\"\"\n Wrap the results.\n\n Parameters\n ----------\n results : list of ndarrays\n blocks : list of blocks\n obj : conformed data (may be resampled)\n \"\"\"\n\n from pandas import Series, concat\n from pandas.core.index import ensure_index\n\n final = []\n for result, block in zip(results, blocks):\n\n result = self._wrap_result(result, block=block, obj=obj)\n if result.ndim == 1:\n return result\n final.append(result)\n\n # if we have an 'on' column\n # we want to put it back into the results\n # in the same location\n columns = self._selected_obj.columns\n if self.on is not None and not self._on.equals(obj.index):\n\n name = self._on.name\n final.append(Series(self._on, index=obj.index, name=name))\n\n if self._selection is not None:\n\n selection = ensure_index(self._selection)\n\n # need to reorder to include original location of\n # the on column (if its not already there)\n if name not in selection:\n columns = self.obj.columns\n indexer = columns.get_indexer(selection.tolist() + [name])\n columns = columns.take(sorted(indexer))\n\n if not len(final):\n return obj.astype('float64')\n return concat(final, axis=1).reindex(columns=columns, copy=False)" }, { "instruction": "Write or improve a Python function based on this description:\n\nCenter the result in the window.", "output": "def _center_window(self, result, window):\n \"\"\"\n Center the result in the window.\n \"\"\"\n if self.axis > result.ndim - 1:\n raise ValueError(\"Requested axis is larger then no. of argument \"\n \"dimensions\")\n\n offset = _offset(window, True)\n if offset > 0:\n if isinstance(result, (ABCSeries, ABCDataFrame)):\n result = result.slice_shift(-offset, axis=self.axis)\n else:\n lead_indexer = [slice(None)] * result.ndim\n lead_indexer[self.axis] = slice(offset, None)\n result = np.copy(result[tuple(lead_indexer)])\n return result" }, { "instruction": "Write or improve a Python function based on this description:\n\nProvide validation for our window type, return the window\n we have already been validated.", "output": "def _prep_window(self, **kwargs):\n \"\"\"\n Provide validation for our window type, return the window\n we have already been validated.\n \"\"\"\n\n window = self._get_window()\n if isinstance(window, (list, tuple, np.ndarray)):\n return com.asarray_tuplesafe(window).astype(float)\n elif is_integer(window):\n import scipy.signal as sig\n\n # the below may pop from kwargs\n def _validate_win_type(win_type, kwargs):\n arg_map = {'kaiser': ['beta'],\n 'gaussian': ['std'],\n 'general_gaussian': ['power', 'width'],\n 'slepian': ['width']}\n if win_type in arg_map:\n return tuple([win_type] + _pop_args(win_type,\n arg_map[win_type],\n kwargs))\n return win_type\n\n def _pop_args(win_type, arg_names, kwargs):\n msg = '%s window requires %%s' % win_type\n all_args = []\n for n in arg_names:\n if n not in kwargs:\n raise ValueError(msg % n)\n all_args.append(kwargs.pop(n))\n return all_args\n\n win_type = _validate_win_type(self.win_type, kwargs)\n # GH #15662. `False` makes symmetric window, rather than periodic.\n return sig.get_window(win_type, window, False).astype(float)" }, { "instruction": "Write or improve a Python function based on this description:\n\nApplies a moving window of type ``window_type`` on the data.\n\n Parameters\n ----------\n mean : bool, default True\n If True computes weighted mean, else weighted sum\n\n Returns\n -------\n y : same type as input argument", "output": "def _apply_window(self, mean=True, **kwargs):\n \"\"\"\n Applies a moving window of type ``window_type`` on the data.\n\n Parameters\n ----------\n mean : bool, default True\n If True computes weighted mean, else weighted sum\n\n Returns\n -------\n y : same type as input argument\n\n \"\"\"\n window = self._prep_window(**kwargs)\n center = self.center\n\n blocks, obj, index = self._create_blocks()\n results = []\n for b in blocks:\n try:\n values = self._prep_values(b.values)\n except TypeError:\n results.append(b.values.copy())\n continue\n\n if values.size == 0:\n results.append(values.copy())\n continue\n\n offset = _offset(window, center)\n additional_nans = np.array([np.NaN] * offset)\n\n def f(arg, *args, **kwargs):\n minp = _use_window(self.min_periods, len(window))\n return libwindow.roll_window(np.concatenate((arg,\n additional_nans))\n if center else arg, window, minp,\n avg=mean)\n\n result = np.apply_along_axis(f, self.axis, values)\n\n if center:\n result = self._center_window(result, window)\n results.append(result)\n\n return self._wrap_results(results, blocks, obj)" }, { "instruction": "Write or improve a Python function based on this description:\n\nDispatch to apply; we are stripping all of the _apply kwargs and\n performing the original function call on the grouped object.", "output": "def _apply(self, func, name, window=None, center=None,\n check_minp=None, **kwargs):\n \"\"\"\n Dispatch to apply; we are stripping all of the _apply kwargs and\n performing the original function call on the grouped object.\n \"\"\"\n\n def f(x, name=name, *args):\n x = self._shallow_copy(x)\n\n if isinstance(name, str):\n return getattr(x, name)(*args, **kwargs)\n\n return x.apply(name, *args, **kwargs)\n\n return self._groupby.apply(f)" }, { "instruction": "Write or improve a Python function based on this description:\n\nRolling statistical measure using supplied function.\n\n Designed to be used with passed-in Cython array-based functions.\n\n Parameters\n ----------\n func : str/callable to apply\n name : str, optional\n name of this function\n window : int/array, default to _get_window()\n center : bool, default to self.center\n check_minp : function, default to _use_window\n\n Returns\n -------\n y : type of input", "output": "def _apply(self, func, name=None, window=None, center=None,\n check_minp=None, **kwargs):\n \"\"\"\n Rolling statistical measure using supplied function.\n\n Designed to be used with passed-in Cython array-based functions.\n\n Parameters\n ----------\n func : str/callable to apply\n name : str, optional\n name of this function\n window : int/array, default to _get_window()\n center : bool, default to self.center\n check_minp : function, default to _use_window\n\n Returns\n -------\n y : type of input\n \"\"\"\n if center is None:\n center = self.center\n if window is None:\n window = self._get_window()\n\n if check_minp is None:\n check_minp = _use_window\n\n blocks, obj, index = self._create_blocks()\n index, indexi = self._get_index(index=index)\n results = []\n for b in blocks:\n values = self._prep_values(b.values)\n\n if values.size == 0:\n results.append(values.copy())\n continue\n\n # if we have a string function name, wrap it\n if isinstance(func, str):\n cfunc = getattr(libwindow, func, None)\n if cfunc is None:\n raise ValueError(\"we do not support this function \"\n \"in libwindow.{func}\".format(func=func))\n\n def func(arg, window, min_periods=None, closed=None):\n minp = check_minp(min_periods, window)\n # ensure we are only rolling on floats\n arg = ensure_float64(arg)\n return cfunc(arg,\n window, minp, indexi, closed, **kwargs)\n\n # calculation function\n if center:\n offset = _offset(window, center)\n additional_nans = np.array([np.NaN] * offset)\n\n def calc(x):\n return func(np.concatenate((x, additional_nans)),\n window, min_periods=self.min_periods,\n closed=self.closed)\n else:\n\n def calc(x):\n return func(x, window, min_periods=self.min_periods,\n closed=self.closed)\n\n with np.errstate(all='ignore'):\n if values.ndim > 1:\n result = np.apply_along_axis(calc, self.axis, values)\n else:\n result = calc(values)\n\n if center:\n result = self._center_window(result, window)\n\n results.append(result)\n\n return self._wrap_results(results, blocks, obj)" }, { "instruction": "Write or improve a Python function based on this description:\n\nValidate on is_monotonic.", "output": "def _validate_monotonic(self):\n \"\"\"\n Validate on is_monotonic.\n \"\"\"\n if not self._on.is_monotonic:\n formatted = self.on or 'index'\n raise ValueError(\"{0} must be \"\n \"monotonic\".format(formatted))" }, { "instruction": "Write or improve a Python function based on this description:\n\nValidate & return window frequency.", "output": "def _validate_freq(self):\n \"\"\"\n Validate & return window frequency.\n \"\"\"\n from pandas.tseries.frequencies import to_offset\n try:\n return to_offset(self.window)\n except (TypeError, ValueError):\n raise ValueError(\"passed window {0} is not \"\n \"compatible with a datetimelike \"\n \"index\".format(self.window))" }, { "instruction": "Write or improve a Python function based on this description:\n\nGet the window length over which to perform some operation.\n\n Parameters\n ----------\n other : object, default None\n The other object that is involved in the operation.\n Such an object is involved for operations like covariance.\n\n Returns\n -------\n window : int\n The window length.", "output": "def _get_window(self, other=None):\n \"\"\"\n Get the window length over which to perform some operation.\n\n Parameters\n ----------\n other : object, default None\n The other object that is involved in the operation.\n Such an object is involved for operations like covariance.\n\n Returns\n -------\n window : int\n The window length.\n \"\"\"\n axis = self.obj._get_axis(self.axis)\n length = len(axis) + (other is not None) * len(axis)\n\n other = self.min_periods or -1\n return max(length, other)" }, { "instruction": "Write or improve a Python function based on this description:\n\nRolling statistical measure using supplied function. Designed to be\n used with passed-in Cython array-based functions.\n\n Parameters\n ----------\n func : str/callable to apply\n\n Returns\n -------\n y : same type as input argument", "output": "def _apply(self, func, **kwargs):\n \"\"\"\n Rolling statistical measure using supplied function. Designed to be\n used with passed-in Cython array-based functions.\n\n Parameters\n ----------\n func : str/callable to apply\n\n Returns\n -------\n y : same type as input argument\n \"\"\"\n blocks, obj, index = self._create_blocks()\n results = []\n for b in blocks:\n try:\n values = self._prep_values(b.values)\n except TypeError:\n results.append(b.values.copy())\n continue\n\n if values.size == 0:\n results.append(values.copy())\n continue\n\n # if we have a string function name, wrap it\n if isinstance(func, str):\n cfunc = getattr(libwindow, func, None)\n if cfunc is None:\n raise ValueError(\"we do not support this function \"\n \"in libwindow.{func}\".format(func=func))\n\n def func(arg):\n return cfunc(arg, self.com, int(self.adjust),\n int(self.ignore_na), int(self.min_periods))\n\n results.append(np.apply_along_axis(func, self.axis, values))\n\n return self._wrap_results(results, blocks, obj)" }, { "instruction": "Write or improve a Python function based on this description:\n\nExponential weighted moving average.\n\n Parameters\n ----------\n *args, **kwargs\n Arguments and keyword arguments to be passed into func.", "output": "def mean(self, *args, **kwargs):\n \"\"\"\n Exponential weighted moving average.\n\n Parameters\n ----------\n *args, **kwargs\n Arguments and keyword arguments to be passed into func.\n \"\"\"\n nv.validate_window_func('mean', args, kwargs)\n return self._apply('ewma', **kwargs)" }, { "instruction": "Write or improve a Python function based on this description:\n\nExponential weighted moving stddev.", "output": "def std(self, bias=False, *args, **kwargs):\n \"\"\"\n Exponential weighted moving stddev.\n \"\"\"\n nv.validate_window_func('std', args, kwargs)\n return _zsqrt(self.var(bias=bias, **kwargs))" }, { "instruction": "Write or improve a Python function based on this description:\n\nExponential weighted moving variance.", "output": "def var(self, bias=False, *args, **kwargs):\n \"\"\"\n Exponential weighted moving variance.\n \"\"\"\n nv.validate_window_func('var', args, kwargs)\n\n def f(arg):\n return libwindow.ewmcov(arg, arg, self.com, int(self.adjust),\n int(self.ignore_na), int(self.min_periods),\n int(bias))\n\n return self._apply(f, **kwargs)" }, { "instruction": "Write or improve a Python function based on this description:\n\nExponential weighted sample covariance.", "output": "def cov(self, other=None, pairwise=None, bias=False, **kwargs):\n \"\"\"\n Exponential weighted sample covariance.\n \"\"\"\n if other is None:\n other = self._selected_obj\n # only default unset\n pairwise = True if pairwise is None else pairwise\n other = self._shallow_copy(other)\n\n def _get_cov(X, Y):\n X = self._shallow_copy(X)\n Y = self._shallow_copy(Y)\n cov = libwindow.ewmcov(X._prep_values(), Y._prep_values(),\n self.com, int(self.adjust),\n int(self.ignore_na), int(self.min_periods),\n int(bias))\n return X._wrap_result(cov)\n\n return _flex_binary_moment(self._selected_obj, other._selected_obj,\n _get_cov, pairwise=bool(pairwise))" }, { "instruction": "Write or improve a Python function based on this description:\n\nExponential weighted sample correlation.", "output": "def corr(self, other=None, pairwise=None, **kwargs):\n \"\"\"\n Exponential weighted sample correlation.\n \"\"\"\n if other is None:\n other = self._selected_obj\n # only default unset\n pairwise = True if pairwise is None else pairwise\n other = self._shallow_copy(other)\n\n def _get_corr(X, Y):\n X = self._shallow_copy(X)\n Y = self._shallow_copy(Y)\n\n def _cov(x, y):\n return libwindow.ewmcov(x, y, self.com, int(self.adjust),\n int(self.ignore_na),\n int(self.min_periods),\n 1)\n\n x_values = X._prep_values()\n y_values = Y._prep_values()\n with np.errstate(all='ignore'):\n cov = _cov(x_values, y_values)\n x_var = _cov(x_values, x_values)\n y_var = _cov(y_values, y_values)\n corr = cov / _zsqrt(x_var * y_var)\n return X._wrap_result(corr)\n\n return _flex_binary_moment(self._selected_obj, other._selected_obj,\n _get_corr, pairwise=bool(pairwise))" }, { "instruction": "Write or improve a Python function based on this description:\n\nMakes sure that time and panels are conformable.", "output": "def _ensure_like_indices(time, panels):\n \"\"\"\n Makes sure that time and panels are conformable.\n \"\"\"\n n_time = len(time)\n n_panel = len(panels)\n u_panels = np.unique(panels) # this sorts!\n u_time = np.unique(time)\n if len(u_time) == n_time:\n time = np.tile(u_time, len(u_panels))\n if len(u_panels) == n_panel:\n panels = np.repeat(u_panels, len(u_time))\n return time, panels" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturns a multi-index suitable for a panel-like DataFrame.\n\n Parameters\n ----------\n time : array-like\n Time index, does not have to repeat\n panels : array-like\n Panel index, does not have to repeat\n names : list, optional\n List containing the names of the indices\n\n Returns\n -------\n multi_index : MultiIndex\n Time index is the first level, the panels are the second level.\n\n Examples\n --------\n >>> years = range(1960,1963)\n >>> panels = ['A', 'B', 'C']\n >>> panel_idx = panel_index(years, panels)\n >>> panel_idx\n MultiIndex([(1960, 'A'), (1961, 'A'), (1962, 'A'), (1960, 'B'),\n (1961, 'B'), (1962, 'B'), (1960, 'C'), (1961, 'C'),\n (1962, 'C')], dtype=object)\n\n or\n\n >>> years = np.repeat(range(1960,1963), 3)\n >>> panels = np.tile(['A', 'B', 'C'], 3)\n >>> panel_idx = panel_index(years, panels)\n >>> panel_idx\n MultiIndex([(1960, 'A'), (1960, 'B'), (1960, 'C'), (1961, 'A'),\n (1961, 'B'), (1961, 'C'), (1962, 'A'), (1962, 'B'),\n (1962, 'C')], dtype=object)", "output": "def panel_index(time, panels, names=None):\n \"\"\"\n Returns a multi-index suitable for a panel-like DataFrame.\n\n Parameters\n ----------\n time : array-like\n Time index, does not have to repeat\n panels : array-like\n Panel index, does not have to repeat\n names : list, optional\n List containing the names of the indices\n\n Returns\n -------\n multi_index : MultiIndex\n Time index is the first level, the panels are the second level.\n\n Examples\n --------\n >>> years = range(1960,1963)\n >>> panels = ['A', 'B', 'C']\n >>> panel_idx = panel_index(years, panels)\n >>> panel_idx\n MultiIndex([(1960, 'A'), (1961, 'A'), (1962, 'A'), (1960, 'B'),\n (1961, 'B'), (1962, 'B'), (1960, 'C'), (1961, 'C'),\n (1962, 'C')], dtype=object)\n\n or\n\n >>> years = np.repeat(range(1960,1963), 3)\n >>> panels = np.tile(['A', 'B', 'C'], 3)\n >>> panel_idx = panel_index(years, panels)\n >>> panel_idx\n MultiIndex([(1960, 'A'), (1960, 'B'), (1960, 'C'), (1961, 'A'),\n (1961, 'B'), (1961, 'C'), (1962, 'A'), (1962, 'B'),\n (1962, 'C')], dtype=object)\n \"\"\"\n if names is None:\n names = ['time', 'panel']\n time, panels = _ensure_like_indices(time, panels)\n return MultiIndex.from_arrays([time, panels], sortorder=None, names=names)" }, { "instruction": "Write or improve a Python function based on this description:\n\nGenerate ND initialization; axes are passed\n as required objects to __init__.", "output": "def _init_data(self, data, copy, dtype, **kwargs):\n \"\"\"\n Generate ND initialization; axes are passed\n as required objects to __init__.\n \"\"\"\n if data is None:\n data = {}\n if dtype is not None:\n dtype = self._validate_dtype(dtype)\n\n passed_axes = [kwargs.pop(a, None) for a in self._AXIS_ORDERS]\n\n if kwargs:\n raise TypeError('_init_data() got an unexpected keyword '\n 'argument \"{0}\"'.format(list(kwargs.keys())[0]))\n\n axes = None\n if isinstance(data, BlockManager):\n if com._any_not_none(*passed_axes):\n axes = [x if x is not None else y\n for x, y in zip(passed_axes, data.axes)]\n mgr = data\n elif isinstance(data, dict):\n mgr = self._init_dict(data, passed_axes, dtype=dtype)\n copy = False\n dtype = None\n elif isinstance(data, (np.ndarray, list)):\n mgr = self._init_matrix(data, passed_axes, dtype=dtype, copy=copy)\n copy = False\n dtype = None\n elif is_scalar(data) and com._all_not_none(*passed_axes):\n values = cast_scalar_to_array([len(x) for x in passed_axes],\n data, dtype=dtype)\n mgr = self._init_matrix(values, passed_axes, dtype=values.dtype,\n copy=False)\n copy = False\n else: # pragma: no cover\n raise ValueError('Panel constructor not properly called!')\n\n NDFrame.__init__(self, mgr, axes=axes, copy=copy, dtype=dtype)" }, { "instruction": "Write or improve a Python function based on this description:\n\nConstruct Panel from dict of DataFrame objects.\n\n Parameters\n ----------\n data : dict\n {field : DataFrame}\n intersect : boolean\n Intersect indexes of input DataFrames\n orient : {'items', 'minor'}, default 'items'\n The \"orientation\" of the data. If the keys of the passed dict\n should be the items of the result panel, pass 'items'\n (default). Otherwise if the columns of the values of the passed\n DataFrame objects should be the items (which in the case of\n mixed-dtype data you should do), instead pass 'minor'\n dtype : dtype, default None\n Data type to force, otherwise infer\n\n Returns\n -------\n Panel", "output": "def from_dict(cls, data, intersect=False, orient='items', dtype=None):\n \"\"\"\n Construct Panel from dict of DataFrame objects.\n\n Parameters\n ----------\n data : dict\n {field : DataFrame}\n intersect : boolean\n Intersect indexes of input DataFrames\n orient : {'items', 'minor'}, default 'items'\n The \"orientation\" of the data. If the keys of the passed dict\n should be the items of the result panel, pass 'items'\n (default). Otherwise if the columns of the values of the passed\n DataFrame objects should be the items (which in the case of\n mixed-dtype data you should do), instead pass 'minor'\n dtype : dtype, default None\n Data type to force, otherwise infer\n\n Returns\n -------\n Panel\n \"\"\"\n from collections import defaultdict\n\n orient = orient.lower()\n if orient == 'minor':\n new_data = defaultdict(OrderedDict)\n for col, df in data.items():\n for item, s in df.items():\n new_data[item][col] = s\n data = new_data\n elif orient != 'items': # pragma: no cover\n raise ValueError('Orientation must be one of {items, minor}.')\n\n d = cls._homogenize_dict(cls, data, intersect=intersect, dtype=dtype)\n ks = list(d['data'].keys())\n if not isinstance(d['data'], OrderedDict):\n ks = list(sorted(ks))\n d[cls._info_axis_name] = Index(ks)\n return cls(**d)" }, { "instruction": "Write or improve a Python function based on this description:\n\nGet my plane axes indexes: these are already\n (as compared with higher level planes),\n as we are returning a DataFrame axes indexes.", "output": "def _get_plane_axes_index(self, axis):\n \"\"\"\n Get my plane axes indexes: these are already\n (as compared with higher level planes),\n as we are returning a DataFrame axes indexes.\n \"\"\"\n axis_name = self._get_axis_name(axis)\n\n if axis_name == 'major_axis':\n index = 'minor_axis'\n columns = 'items'\n if axis_name == 'minor_axis':\n index = 'major_axis'\n columns = 'items'\n elif axis_name == 'items':\n index = 'major_axis'\n columns = 'minor_axis'\n\n return index, columns" }, { "instruction": "Write or improve a Python function based on this description:\n\nGet my plane axes indexes: these are already\n (as compared with higher level planes),\n as we are returning a DataFrame axes.", "output": "def _get_plane_axes(self, axis):\n \"\"\"\n Get my plane axes indexes: these are already\n (as compared with higher level planes),\n as we are returning a DataFrame axes.\n \"\"\"\n return [self._get_axis(axi)\n for axi in self._get_plane_axes_index(axis)]" }, { "instruction": "Write or improve a Python function based on this description:\n\nWrite each DataFrame in Panel to a separate excel sheet.\n\n Parameters\n ----------\n path : string or ExcelWriter object\n File path or existing ExcelWriter\n na_rep : string, default ''\n Missing data representation\n engine : string, default None\n write engine to use - you can also set this via the options\n ``io.excel.xlsx.writer``, ``io.excel.xls.writer``, and\n ``io.excel.xlsm.writer``.\n\n Other Parameters\n ----------------\n float_format : string, default None\n Format string for floating point numbers\n cols : sequence, optional\n Columns to write\n header : boolean or list of string, default True\n Write out column names. If a list of string is given it is\n assumed to be aliases for the column names\n index : boolean, default True\n Write row names (index)\n index_label : string or sequence, default None\n Column label for index column(s) if desired. If None is given, and\n `header` and `index` are True, then the index names are used. A\n sequence should be given if the DataFrame uses MultiIndex.\n startrow : upper left cell row to dump data frame\n startcol : upper left cell column to dump data frame\n\n Notes\n -----\n Keyword arguments (and na_rep) are passed to the ``to_excel`` method\n for each DataFrame written.", "output": "def to_excel(self, path, na_rep='', engine=None, **kwargs):\n \"\"\"\n Write each DataFrame in Panel to a separate excel sheet.\n\n Parameters\n ----------\n path : string or ExcelWriter object\n File path or existing ExcelWriter\n na_rep : string, default ''\n Missing data representation\n engine : string, default None\n write engine to use - you can also set this via the options\n ``io.excel.xlsx.writer``, ``io.excel.xls.writer``, and\n ``io.excel.xlsm.writer``.\n\n Other Parameters\n ----------------\n float_format : string, default None\n Format string for floating point numbers\n cols : sequence, optional\n Columns to write\n header : boolean or list of string, default True\n Write out column names. If a list of string is given it is\n assumed to be aliases for the column names\n index : boolean, default True\n Write row names (index)\n index_label : string or sequence, default None\n Column label for index column(s) if desired. If None is given, and\n `header` and `index` are True, then the index names are used. A\n sequence should be given if the DataFrame uses MultiIndex.\n startrow : upper left cell row to dump data frame\n startcol : upper left cell column to dump data frame\n\n Notes\n -----\n Keyword arguments (and na_rep) are passed to the ``to_excel`` method\n for each DataFrame written.\n \"\"\"\n from pandas.io.excel import ExcelWriter\n\n if isinstance(path, str):\n writer = ExcelWriter(path, engine=engine)\n else:\n writer = path\n kwargs['na_rep'] = na_rep\n\n for item, df in self.iteritems():\n name = str(item)\n df.to_excel(writer, name, **kwargs)\n writer.save()" }, { "instruction": "Write or improve a Python function based on this description:\n\nQuickly retrieve single value at (item, major, minor) location.\n\n .. deprecated:: 0.21.0\n\n Please use .at[] or .iat[] accessors.\n\n Parameters\n ----------\n item : item label (panel item)\n major : major axis label (panel item row)\n minor : minor axis label (panel item column)\n takeable : interpret the passed labels as indexers, default False\n\n Returns\n -------\n value : scalar value", "output": "def get_value(self, *args, **kwargs):\n \"\"\"\n Quickly retrieve single value at (item, major, minor) location.\n\n .. deprecated:: 0.21.0\n\n Please use .at[] or .iat[] accessors.\n\n Parameters\n ----------\n item : item label (panel item)\n major : major axis label (panel item row)\n minor : minor axis label (panel item column)\n takeable : interpret the passed labels as indexers, default False\n\n Returns\n -------\n value : scalar value\n \"\"\"\n warnings.warn(\"get_value is deprecated and will be removed \"\n \"in a future release. Please use \"\n \".at[] or .iat[] accessors instead\", FutureWarning,\n stacklevel=2)\n return self._get_value(*args, **kwargs)" }, { "instruction": "Write or improve a Python function based on this description:\n\nQuickly set single value at (item, major, minor) location.\n\n .. deprecated:: 0.21.0\n\n Please use .at[] or .iat[] accessors.\n\n Parameters\n ----------\n item : item label (panel item)\n major : major axis label (panel item row)\n minor : minor axis label (panel item column)\n value : scalar\n takeable : interpret the passed labels as indexers, default False\n\n Returns\n -------\n panel : Panel\n If label combo is contained, will be reference to calling Panel,\n otherwise a new object.", "output": "def set_value(self, *args, **kwargs):\n \"\"\"\n Quickly set single value at (item, major, minor) location.\n\n .. deprecated:: 0.21.0\n\n Please use .at[] or .iat[] accessors.\n\n Parameters\n ----------\n item : item label (panel item)\n major : major axis label (panel item row)\n minor : minor axis label (panel item column)\n value : scalar\n takeable : interpret the passed labels as indexers, default False\n\n Returns\n -------\n panel : Panel\n If label combo is contained, will be reference to calling Panel,\n otherwise a new object.\n \"\"\"\n warnings.warn(\"set_value is deprecated and will be removed \"\n \"in a future release. Please use \"\n \".at[] or .iat[] accessors instead\", FutureWarning,\n stacklevel=2)\n return self._set_value(*args, **kwargs)" }, { "instruction": "Write or improve a Python function based on this description:\n\nUnpickle the panel.", "output": "def _unpickle_panel_compat(self, state): # pragma: no cover\n \"\"\"\n Unpickle the panel.\n \"\"\"\n from pandas.io.pickle import _unpickle_array\n\n _unpickle = _unpickle_array\n vals, items, major, minor = state\n\n items = _unpickle(items)\n major = _unpickle(major)\n minor = _unpickle(minor)\n values = _unpickle(vals)\n wp = Panel(values, items, major, minor)\n self._data = wp._data" }, { "instruction": "Write or improve a Python function based on this description:\n\nConform input DataFrame to align with chosen axis pair.\n\n Parameters\n ----------\n frame : DataFrame\n axis : {'items', 'major', 'minor'}\n\n Axis the input corresponds to. E.g., if axis='major', then\n the frame's columns would be items, and the index would be\n values of the minor axis\n\n Returns\n -------\n DataFrame", "output": "def conform(self, frame, axis='items'):\n \"\"\"\n Conform input DataFrame to align with chosen axis pair.\n\n Parameters\n ----------\n frame : DataFrame\n axis : {'items', 'major', 'minor'}\n\n Axis the input corresponds to. E.g., if axis='major', then\n the frame's columns would be items, and the index would be\n values of the minor axis\n\n Returns\n -------\n DataFrame\n \"\"\"\n axes = self._get_plane_axes(axis)\n return frame.reindex(**self._extract_axes_for_slice(self, axes))" }, { "instruction": "Write or improve a Python function based on this description:\n\nRound each value in Panel to a specified number of decimal places.\n\n .. versionadded:: 0.18.0\n\n Parameters\n ----------\n decimals : int\n Number of decimal places to round to (default: 0).\n If decimals is negative, it specifies the number of\n positions to the left of the decimal point.\n\n Returns\n -------\n Panel object\n\n See Also\n --------\n numpy.around", "output": "def round(self, decimals=0, *args, **kwargs):\n \"\"\"\n Round each value in Panel to a specified number of decimal places.\n\n .. versionadded:: 0.18.0\n\n Parameters\n ----------\n decimals : int\n Number of decimal places to round to (default: 0).\n If decimals is negative, it specifies the number of\n positions to the left of the decimal point.\n\n Returns\n -------\n Panel object\n\n See Also\n --------\n numpy.around\n \"\"\"\n nv.validate_round(args, kwargs)\n\n if is_integer(decimals):\n result = np.apply_along_axis(np.round, 0, self.values)\n return self._wrap_result(result, axis=0)\n raise TypeError(\"decimals must be an integer\")" }, { "instruction": "Write or improve a Python function based on this description:\n\nDrop 2D from panel, holding passed axis constant.\n\n Parameters\n ----------\n axis : int, default 0\n Axis to hold constant. E.g. axis=1 will drop major_axis entries\n having a certain amount of NA data\n how : {'all', 'any'}, default 'any'\n 'any': one or more values are NA in the DataFrame along the\n axis. For 'all' they all must be.\n inplace : bool, default False\n If True, do operation inplace and return None.\n\n Returns\n -------\n dropped : Panel", "output": "def dropna(self, axis=0, how='any', inplace=False):\n \"\"\"\n Drop 2D from panel, holding passed axis constant.\n\n Parameters\n ----------\n axis : int, default 0\n Axis to hold constant. E.g. axis=1 will drop major_axis entries\n having a certain amount of NA data\n how : {'all', 'any'}, default 'any'\n 'any': one or more values are NA in the DataFrame along the\n axis. For 'all' they all must be.\n inplace : bool, default False\n If True, do operation inplace and return None.\n\n Returns\n -------\n dropped : Panel\n \"\"\"\n axis = self._get_axis_number(axis)\n\n values = self.values\n mask = notna(values)\n\n for ax in reversed(sorted(set(range(self._AXIS_LEN)) - {axis})):\n mask = mask.sum(ax)\n\n per_slice = np.prod(values.shape[:axis] + values.shape[axis + 1:])\n\n if how == 'all':\n cond = mask > 0\n else:\n cond = mask == per_slice\n\n new_ax = self._get_axis(axis)[cond]\n result = self.reindex_axis(new_ax, axis=axis)\n if inplace:\n self._update_inplace(result)\n else:\n return result" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn slice of panel along selected axis.\n\n Parameters\n ----------\n key : object\n Label\n axis : {'items', 'major', 'minor}, default 1/'major'\n\n Returns\n -------\n y : ndim(self)-1\n\n Notes\n -----\n xs is only for getting, not setting values.\n\n MultiIndex Slicers is a generic way to get/set values on any level or\n levels and is a superset of xs functionality, see\n :ref:`MultiIndex Slicers `", "output": "def xs(self, key, axis=1):\n \"\"\"\n Return slice of panel along selected axis.\n\n Parameters\n ----------\n key : object\n Label\n axis : {'items', 'major', 'minor}, default 1/'major'\n\n Returns\n -------\n y : ndim(self)-1\n\n Notes\n -----\n xs is only for getting, not setting values.\n\n MultiIndex Slicers is a generic way to get/set values on any level or\n levels and is a superset of xs functionality, see\n :ref:`MultiIndex Slicers `\n \"\"\"\n axis = self._get_axis_number(axis)\n if axis == 0:\n return self[key]\n\n self._consolidate_inplace()\n axis_number = self._get_axis_number(axis)\n new_data = self._data.xs(key, axis=axis_number, copy=False)\n result = self._construct_return_type(new_data)\n copy = new_data.is_mixed_type\n result._set_is_copy(self, copy=copy)\n return result" }, { "instruction": "Write or improve a Python function based on this description:\n\nParameters\n ----------\n i : int, slice, or sequence of integers\n axis : int", "output": "def _ixs(self, i, axis=0):\n \"\"\"\n Parameters\n ----------\n i : int, slice, or sequence of integers\n axis : int\n \"\"\"\n\n ax = self._get_axis(axis)\n key = ax[i]\n\n # xs cannot handle a non-scalar key, so just reindex here\n # if we have a multi-index and a single tuple, then its a reduction\n # (GH 7516)\n if not (isinstance(ax, MultiIndex) and isinstance(key, tuple)):\n if is_list_like(key):\n indexer = {self._get_axis_name(axis): key}\n return self.reindex(**indexer)\n\n # a reduction\n if axis == 0:\n values = self._data.iget(i)\n return self._box_item_values(key, values)\n\n # xs by position\n self._consolidate_inplace()\n new_data = self._data.xs(i, axis=axis, copy=True, takeable=True)\n return self._construct_return_type(new_data)" }, { "instruction": "Write or improve a Python function based on this description:\n\nTransform wide format into long (stacked) format as DataFrame whose\n columns are the Panel's items and whose index is a MultiIndex formed\n of the Panel's major and minor axes.\n\n Parameters\n ----------\n filter_observations : boolean, default True\n Drop (major, minor) pairs without a complete set of observations\n across all the items\n\n Returns\n -------\n y : DataFrame", "output": "def to_frame(self, filter_observations=True):\n \"\"\"\n Transform wide format into long (stacked) format as DataFrame whose\n columns are the Panel's items and whose index is a MultiIndex formed\n of the Panel's major and minor axes.\n\n Parameters\n ----------\n filter_observations : boolean, default True\n Drop (major, minor) pairs without a complete set of observations\n across all the items\n\n Returns\n -------\n y : DataFrame\n \"\"\"\n _, N, K = self.shape\n\n if filter_observations:\n # shaped like the return DataFrame\n mask = notna(self.values).all(axis=0)\n # size = mask.sum()\n selector = mask.ravel()\n else:\n # size = N * K\n selector = slice(None, None)\n\n data = {item: self[item].values.ravel()[selector]\n for item in self.items}\n\n def construct_multi_parts(idx, n_repeat, n_shuffle=1):\n # Replicates and shuffles MultiIndex, returns individual attributes\n codes = [np.repeat(x, n_repeat) for x in idx.codes]\n # Assumes that each label is divisible by n_shuffle\n codes = [x.reshape(n_shuffle, -1).ravel(order='F')\n for x in codes]\n codes = [x[selector] for x in codes]\n levels = idx.levels\n names = idx.names\n return codes, levels, names\n\n def construct_index_parts(idx, major=True):\n levels = [idx]\n if major:\n codes = [np.arange(N).repeat(K)[selector]]\n names = idx.name or 'major'\n else:\n codes = np.arange(K).reshape(1, K)[np.zeros(N, dtype=int)]\n codes = [codes.ravel()[selector]]\n names = idx.name or 'minor'\n names = [names]\n return codes, levels, names\n\n if isinstance(self.major_axis, MultiIndex):\n major_codes, major_levels, major_names = construct_multi_parts(\n self.major_axis, n_repeat=K)\n else:\n major_codes, major_levels, major_names = construct_index_parts(\n self.major_axis)\n\n if isinstance(self.minor_axis, MultiIndex):\n minor_codes, minor_levels, minor_names = construct_multi_parts(\n self.minor_axis, n_repeat=N, n_shuffle=K)\n else:\n minor_codes, minor_levels, minor_names = construct_index_parts(\n self.minor_axis, major=False)\n\n levels = major_levels + minor_levels\n codes = major_codes + minor_codes\n names = major_names + minor_names\n\n index = MultiIndex(levels=levels, codes=codes, names=names,\n verify_integrity=False)\n\n return DataFrame(data, index=index, columns=self.items)" }, { "instruction": "Write or improve a Python function based on this description:\n\nApply function along axis (or axes) of the Panel.\n\n Parameters\n ----------\n func : function\n Function to apply to each combination of 'other' axes\n e.g. if axis = 'items', the combination of major_axis/minor_axis\n will each be passed as a Series; if axis = ('items', 'major'),\n DataFrames of items & major axis will be passed\n axis : {'items', 'minor', 'major'}, or {0, 1, 2}, or a tuple with two\n axes\n **kwargs\n Additional keyword arguments will be passed to the function.\n\n Returns\n -------\n result : Panel, DataFrame, or Series\n\n Examples\n --------\n\n Returns a Panel with the square root of each element\n\n >>> p = pd.Panel(np.random.rand(4, 3, 2)) # doctest: +SKIP\n >>> p.apply(np.sqrt)\n\n Equivalent to p.sum(1), returning a DataFrame\n\n >>> p.apply(lambda x: x.sum(), axis=1) # doctest: +SKIP\n\n Equivalent to previous:\n\n >>> p.apply(lambda x: x.sum(), axis='major') # doctest: +SKIP\n\n Return the shapes of each DataFrame over axis 2 (i.e the shapes of\n items x major), as a Series\n\n >>> p.apply(lambda x: x.shape, axis=(0,1)) # doctest: +SKIP", "output": "def apply(self, func, axis='major', **kwargs):\n \"\"\"\n Apply function along axis (or axes) of the Panel.\n\n Parameters\n ----------\n func : function\n Function to apply to each combination of 'other' axes\n e.g. if axis = 'items', the combination of major_axis/minor_axis\n will each be passed as a Series; if axis = ('items', 'major'),\n DataFrames of items & major axis will be passed\n axis : {'items', 'minor', 'major'}, or {0, 1, 2}, or a tuple with two\n axes\n **kwargs\n Additional keyword arguments will be passed to the function.\n\n Returns\n -------\n result : Panel, DataFrame, or Series\n\n Examples\n --------\n\n Returns a Panel with the square root of each element\n\n >>> p = pd.Panel(np.random.rand(4, 3, 2)) # doctest: +SKIP\n >>> p.apply(np.sqrt)\n\n Equivalent to p.sum(1), returning a DataFrame\n\n >>> p.apply(lambda x: x.sum(), axis=1) # doctest: +SKIP\n\n Equivalent to previous:\n\n >>> p.apply(lambda x: x.sum(), axis='major') # doctest: +SKIP\n\n Return the shapes of each DataFrame over axis 2 (i.e the shapes of\n items x major), as a Series\n\n >>> p.apply(lambda x: x.shape, axis=(0,1)) # doctest: +SKIP\n \"\"\"\n\n if kwargs and not isinstance(func, np.ufunc):\n f = lambda x: func(x, **kwargs)\n else:\n f = func\n\n # 2d-slabs\n if isinstance(axis, (tuple, list)) and len(axis) == 2:\n return self._apply_2d(f, axis=axis)\n\n axis = self._get_axis_number(axis)\n\n # try ufunc like\n if isinstance(f, np.ufunc):\n try:\n with np.errstate(all='ignore'):\n result = np.apply_along_axis(func, axis, self.values)\n return self._wrap_result(result, axis=axis)\n except (AttributeError):\n pass\n\n # 1d\n return self._apply_1d(f, axis=axis)" }, { "instruction": "Write or improve a Python function based on this description:\n\nHandle 2-d slices, equiv to iterating over the other axis.", "output": "def _apply_2d(self, func, axis):\n \"\"\"\n Handle 2-d slices, equiv to iterating over the other axis.\n \"\"\"\n ndim = self.ndim\n axis = [self._get_axis_number(a) for a in axis]\n\n # construct slabs, in 2-d this is a DataFrame result\n indexer_axis = list(range(ndim))\n for a in axis:\n indexer_axis.remove(a)\n indexer_axis = indexer_axis[0]\n\n slicer = [slice(None, None)] * ndim\n ax = self._get_axis(indexer_axis)\n\n results = []\n for i, e in enumerate(ax):\n slicer[indexer_axis] = i\n sliced = self.iloc[tuple(slicer)]\n\n obj = func(sliced)\n results.append((e, obj))\n\n return self._construct_return_type(dict(results))" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn the type for the ndim of the result.", "output": "def _construct_return_type(self, result, axes=None):\n \"\"\"\n Return the type for the ndim of the result.\n \"\"\"\n ndim = getattr(result, 'ndim', None)\n\n # need to assume they are the same\n if ndim is None:\n if isinstance(result, dict):\n ndim = getattr(list(result.values())[0], 'ndim', 0)\n\n # have a dict, so top-level is +1 dim\n if ndim != 0:\n ndim += 1\n\n # scalar\n if ndim == 0:\n return Series(result)\n\n # same as self\n elif self.ndim == ndim:\n # return the construction dictionary for these axes\n if axes is None:\n return self._constructor(result)\n return self._constructor(result, **self._construct_axes_dict())\n\n # sliced\n elif self.ndim == ndim + 1:\n if axes is None:\n return self._constructor_sliced(result)\n return self._constructor_sliced(\n result, **self._extract_axes_for_slice(self, axes))\n\n raise ValueError('invalid _construct_return_type [self->{self}] '\n '[result->{result}]'.format(self=self, result=result))" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn number of observations over requested axis.\n\n Parameters\n ----------\n axis : {'items', 'major', 'minor'} or {0, 1, 2}\n\n Returns\n -------\n count : DataFrame", "output": "def count(self, axis='major'):\n \"\"\"\n Return number of observations over requested axis.\n\n Parameters\n ----------\n axis : {'items', 'major', 'minor'} or {0, 1, 2}\n\n Returns\n -------\n count : DataFrame\n \"\"\"\n i = self._get_axis_number(axis)\n\n values = self.values\n mask = np.isfinite(values)\n result = mask.sum(axis=i, dtype='int64')\n\n return self._wrap_result(result, axis)" }, { "instruction": "Write or improve a Python function based on this description:\n\nShift index by desired number of periods with an optional time freq.\n\n The shifted data will not include the dropped periods and the\n shifted axis will be smaller than the original. This is different\n from the behavior of DataFrame.shift()\n\n Parameters\n ----------\n periods : int\n Number of periods to move, can be positive or negative\n freq : DateOffset, timedelta, or time rule string, optional\n axis : {'items', 'major', 'minor'} or {0, 1, 2}\n\n Returns\n -------\n shifted : Panel", "output": "def shift(self, periods=1, freq=None, axis='major'):\n \"\"\"\n Shift index by desired number of periods with an optional time freq.\n\n The shifted data will not include the dropped periods and the\n shifted axis will be smaller than the original. This is different\n from the behavior of DataFrame.shift()\n\n Parameters\n ----------\n periods : int\n Number of periods to move, can be positive or negative\n freq : DateOffset, timedelta, or time rule string, optional\n axis : {'items', 'major', 'minor'} or {0, 1, 2}\n\n Returns\n -------\n shifted : Panel\n \"\"\"\n if freq:\n return self.tshift(periods, freq, axis=axis)\n\n return super().slice_shift(periods, axis=axis)" }, { "instruction": "Write or improve a Python function based on this description:\n\nJoin items with other Panel either on major and minor axes column.\n\n Parameters\n ----------\n other : Panel or list of Panels\n Index should be similar to one of the columns in this one\n how : {'left', 'right', 'outer', 'inner'}\n How to handle indexes of the two objects. Default: 'left'\n for joining on index, None otherwise\n * left: use calling frame's index\n * right: use input frame's index\n * outer: form union of indexes\n * inner: use intersection of indexes\n lsuffix : string\n Suffix to use from left frame's overlapping columns\n rsuffix : string\n Suffix to use from right frame's overlapping columns\n\n Returns\n -------\n joined : Panel", "output": "def join(self, other, how='left', lsuffix='', rsuffix=''):\n \"\"\"\n Join items with other Panel either on major and minor axes column.\n\n Parameters\n ----------\n other : Panel or list of Panels\n Index should be similar to one of the columns in this one\n how : {'left', 'right', 'outer', 'inner'}\n How to handle indexes of the two objects. Default: 'left'\n for joining on index, None otherwise\n * left: use calling frame's index\n * right: use input frame's index\n * outer: form union of indexes\n * inner: use intersection of indexes\n lsuffix : string\n Suffix to use from left frame's overlapping columns\n rsuffix : string\n Suffix to use from right frame's overlapping columns\n\n Returns\n -------\n joined : Panel\n \"\"\"\n from pandas.core.reshape.concat import concat\n\n if isinstance(other, Panel):\n join_major, join_minor = self._get_join_index(other, how)\n this = self.reindex(major=join_major, minor=join_minor)\n other = other.reindex(major=join_major, minor=join_minor)\n merged_data = this._data.merge(other._data, lsuffix, rsuffix)\n return self._constructor(merged_data)\n else:\n if lsuffix or rsuffix:\n raise ValueError('Suffixes not supported when passing '\n 'multiple panels')\n\n if how == 'left':\n how = 'outer'\n join_axes = [self.major_axis, self.minor_axis]\n elif how == 'right':\n raise ValueError('Right join not supported with multiple '\n 'panels')\n else:\n join_axes = None\n\n return concat([self] + list(other), axis=0, join=how,\n join_axes=join_axes, verify_integrity=True)" }, { "instruction": "Write or improve a Python function based on this description:\n\nModify Panel in place using non-NA values from other Panel.\n\n May also use object coercible to Panel. Will align on items.\n\n Parameters\n ----------\n other : Panel, or object coercible to Panel\n The object from which the caller will be udpated.\n join : {'left', 'right', 'outer', 'inner'}, default 'left'\n How individual DataFrames are joined.\n overwrite : bool, default True\n If True then overwrite values for common keys in the calling Panel.\n filter_func : callable(1d-array) -> 1d-array, default None\n Can choose to replace values other than NA. Return True for values\n that should be updated.\n errors : {'raise', 'ignore'}, default 'ignore'\n If 'raise', will raise an error if a DataFrame and other both.\n\n .. versionchanged :: 0.24.0\n Changed from `raise_conflict=False|True`\n to `errors='ignore'|'raise'`.\n\n See Also\n --------\n DataFrame.update : Similar method for DataFrames.\n dict.update : Similar method for dictionaries.", "output": "def update(self, other, join='left', overwrite=True, filter_func=None,\n errors='ignore'):\n \"\"\"\n Modify Panel in place using non-NA values from other Panel.\n\n May also use object coercible to Panel. Will align on items.\n\n Parameters\n ----------\n other : Panel, or object coercible to Panel\n The object from which the caller will be udpated.\n join : {'left', 'right', 'outer', 'inner'}, default 'left'\n How individual DataFrames are joined.\n overwrite : bool, default True\n If True then overwrite values for common keys in the calling Panel.\n filter_func : callable(1d-array) -> 1d-array, default None\n Can choose to replace values other than NA. Return True for values\n that should be updated.\n errors : {'raise', 'ignore'}, default 'ignore'\n If 'raise', will raise an error if a DataFrame and other both.\n\n .. versionchanged :: 0.24.0\n Changed from `raise_conflict=False|True`\n to `errors='ignore'|'raise'`.\n\n See Also\n --------\n DataFrame.update : Similar method for DataFrames.\n dict.update : Similar method for dictionaries.\n \"\"\"\n\n if not isinstance(other, self._constructor):\n other = self._constructor(other)\n\n axis_name = self._info_axis_name\n axis_values = self._info_axis\n other = other.reindex(**{axis_name: axis_values})\n\n for frame in axis_values:\n self[frame].update(other[frame], join=join, overwrite=overwrite,\n filter_func=filter_func, errors=errors)" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn a list of the axis indices.", "output": "def _extract_axes(self, data, axes, **kwargs):\n \"\"\"\n Return a list of the axis indices.\n \"\"\"\n return [self._extract_axis(self, data, axis=i, **kwargs)\n for i, a in enumerate(axes)]" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn the slice dictionary for these axes.", "output": "def _extract_axes_for_slice(self, axes):\n \"\"\"\n Return the slice dictionary for these axes.\n \"\"\"\n return {self._AXIS_SLICEMAP[i]: a for i, a in\n zip(self._AXIS_ORDERS[self._AXIS_LEN - len(axes):], axes)}" }, { "instruction": "Write or improve a Python function based on this description:\n\nConform set of _constructor_sliced-like objects to either\n an intersection of indices / columns or a union.\n\n Parameters\n ----------\n frames : dict\n intersect : boolean, default True\n\n Returns\n -------\n dict of aligned results & indices", "output": "def _homogenize_dict(self, frames, intersect=True, dtype=None):\n \"\"\"\n Conform set of _constructor_sliced-like objects to either\n an intersection of indices / columns or a union.\n\n Parameters\n ----------\n frames : dict\n intersect : boolean, default True\n\n Returns\n -------\n dict of aligned results & indices\n \"\"\"\n\n result = dict()\n # caller differs dict/ODict, preserved type\n if isinstance(frames, OrderedDict):\n result = OrderedDict()\n\n adj_frames = OrderedDict()\n for k, v in frames.items():\n if isinstance(v, dict):\n adj_frames[k] = self._constructor_sliced(v)\n else:\n adj_frames[k] = v\n\n axes = self._AXIS_ORDERS[1:]\n axes_dict = {a: ax for a, ax in zip(axes, self._extract_axes(\n self, adj_frames, axes, intersect=intersect))}\n\n reindex_dict = {self._AXIS_SLICEMAP[a]: axes_dict[a] for a in axes}\n reindex_dict['copy'] = False\n for key, frame in adj_frames.items():\n if frame is not None:\n result[key] = frame.reindex(**reindex_dict)\n else:\n result[key] = None\n\n axes_dict['data'] = result\n axes_dict['dtype'] = dtype\n return axes_dict" }, { "instruction": "Write or improve a Python function based on this description:\n\nFor the particular label_list, gets the offsets into the hypothetical list\n representing the totally ordered cartesian product of all possible label\n combinations, *as long as* this space fits within int64 bounds;\n otherwise, though group indices identify unique combinations of\n labels, they cannot be deconstructed.\n - If `sort`, rank of returned ids preserve lexical ranks of labels.\n i.e. returned id's can be used to do lexical sort on labels;\n - If `xnull` nulls (-1 labels) are passed through.\n\n Parameters\n ----------\n labels: sequence of arrays\n Integers identifying levels at each location\n shape: sequence of ints same length as labels\n Number of unique levels at each location\n sort: boolean\n If the ranks of returned ids should match lexical ranks of labels\n xnull: boolean\n If true nulls are excluded. i.e. -1 values in the labels are\n passed through\n Returns\n -------\n An array of type int64 where two elements are equal if their corresponding\n labels are equal at all location.", "output": "def get_group_index(labels, shape, sort, xnull):\n \"\"\"\n For the particular label_list, gets the offsets into the hypothetical list\n representing the totally ordered cartesian product of all possible label\n combinations, *as long as* this space fits within int64 bounds;\n otherwise, though group indices identify unique combinations of\n labels, they cannot be deconstructed.\n - If `sort`, rank of returned ids preserve lexical ranks of labels.\n i.e. returned id's can be used to do lexical sort on labels;\n - If `xnull` nulls (-1 labels) are passed through.\n\n Parameters\n ----------\n labels: sequence of arrays\n Integers identifying levels at each location\n shape: sequence of ints same length as labels\n Number of unique levels at each location\n sort: boolean\n If the ranks of returned ids should match lexical ranks of labels\n xnull: boolean\n If true nulls are excluded. i.e. -1 values in the labels are\n passed through\n Returns\n -------\n An array of type int64 where two elements are equal if their corresponding\n labels are equal at all location.\n \"\"\"\n def _int64_cut_off(shape):\n acc = 1\n for i, mul in enumerate(shape):\n acc *= int(mul)\n if not acc < _INT64_MAX:\n return i\n return len(shape)\n\n def maybe_lift(lab, size):\n # promote nan values (assigned -1 label in lab array)\n # so that all output values are non-negative\n return (lab + 1, size + 1) if (lab == -1).any() else (lab, size)\n\n labels = map(ensure_int64, labels)\n if not xnull:\n labels, shape = map(list, zip(*map(maybe_lift, labels, shape)))\n\n labels = list(labels)\n shape = list(shape)\n\n # Iteratively process all the labels in chunks sized so less\n # than _INT64_MAX unique int ids will be required for each chunk\n while True:\n # how many levels can be done without overflow:\n nlev = _int64_cut_off(shape)\n\n # compute flat ids for the first `nlev` levels\n stride = np.prod(shape[1:nlev], dtype='i8')\n out = stride * labels[0].astype('i8', subok=False, copy=False)\n\n for i in range(1, nlev):\n if shape[i] == 0:\n stride = 0\n else:\n stride //= shape[i]\n out += labels[i] * stride\n\n if xnull: # exclude nulls\n mask = labels[0] == -1\n for lab in labels[1:nlev]:\n mask |= lab == -1\n out[mask] = -1\n\n if nlev == len(shape): # all levels done!\n break\n\n # compress what has been done so far in order to avoid overflow\n # to retain lexical ranks, obs_ids should be sorted\n comp_ids, obs_ids = compress_group_index(out, sort=sort)\n\n labels = [comp_ids] + labels[nlev:]\n shape = [len(obs_ids)] + shape[nlev:]\n\n return out" }, { "instruction": "Write or improve a Python function based on this description:\n\nreconstruct labels from observed group ids\n\n Parameters\n ----------\n xnull: boolean,\n if nulls are excluded; i.e. -1 labels are passed through", "output": "def decons_obs_group_ids(comp_ids, obs_ids, shape, labels, xnull):\n \"\"\"\n reconstruct labels from observed group ids\n\n Parameters\n ----------\n xnull: boolean,\n if nulls are excluded; i.e. -1 labels are passed through\n \"\"\"\n\n if not xnull:\n lift = np.fromiter(((a == -1).any() for a in labels), dtype='i8')\n shape = np.asarray(shape, dtype='i8') + lift\n\n if not is_int64_overflow_possible(shape):\n # obs ids are deconstructable! take the fast route!\n out = decons_group_index(obs_ids, shape)\n return out if xnull or not lift.any() \\\n else [x - y for x, y in zip(out, lift)]\n\n i = unique_label_indices(comp_ids)\n i8copy = lambda a: a.astype('i8', subok=False, copy=True)\n return [i8copy(lab[i]) for lab in labels]" }, { "instruction": "Write or improve a Python function based on this description:\n\nThis is intended to be a drop-in replacement for np.argsort which\n handles NaNs. It adds ascending and na_position parameters.\n GH #6399, #5231", "output": "def nargsort(items, kind='quicksort', ascending=True, na_position='last'):\n \"\"\"\n This is intended to be a drop-in replacement for np.argsort which\n handles NaNs. It adds ascending and na_position parameters.\n GH #6399, #5231\n \"\"\"\n\n # specially handle Categorical\n if is_categorical_dtype(items):\n if na_position not in {'first', 'last'}:\n raise ValueError('invalid na_position: {!r}'.format(na_position))\n\n mask = isna(items)\n cnt_null = mask.sum()\n sorted_idx = items.argsort(ascending=ascending, kind=kind)\n if ascending and na_position == 'last':\n # NaN is coded as -1 and is listed in front after sorting\n sorted_idx = np.roll(sorted_idx, -cnt_null)\n elif not ascending and na_position == 'first':\n # NaN is coded as -1 and is listed in the end after sorting\n sorted_idx = np.roll(sorted_idx, cnt_null)\n return sorted_idx\n\n with warnings.catch_warnings():\n # https://github.com/pandas-dev/pandas/issues/25439\n # can be removed once ExtensionArrays are properly handled by nargsort\n warnings.filterwarnings(\n \"ignore\", category=FutureWarning,\n message=\"Converting timezone-aware DatetimeArray to\")\n items = np.asanyarray(items)\n idx = np.arange(len(items))\n mask = isna(items)\n non_nans = items[~mask]\n non_nan_idx = idx[~mask]\n nan_idx = np.nonzero(mask)[0]\n if not ascending:\n non_nans = non_nans[::-1]\n non_nan_idx = non_nan_idx[::-1]\n indexer = non_nan_idx[non_nans.argsort(kind=kind)]\n if not ascending:\n indexer = indexer[::-1]\n # Finally, place the NaNs at the end or the beginning according to\n # na_position\n if na_position == 'last':\n indexer = np.concatenate([indexer, nan_idx])\n elif na_position == 'first':\n indexer = np.concatenate([nan_idx, indexer])\n else:\n raise ValueError('invalid na_position: {!r}'.format(na_position))\n return indexer" }, { "instruction": "Write or improve a Python function based on this description:\n\nreturn a diction of {labels} -> {indexers}", "output": "def get_indexer_dict(label_list, keys):\n \"\"\" return a diction of {labels} -> {indexers} \"\"\"\n shape = list(map(len, keys))\n\n group_index = get_group_index(label_list, shape, sort=True, xnull=True)\n ngroups = ((group_index.size and group_index.max()) + 1) \\\n if is_int64_overflow_possible(shape) \\\n else np.prod(shape, dtype='i8')\n\n sorter = get_group_index_sorter(group_index, ngroups)\n\n sorted_labels = [lab.take(sorter) for lab in label_list]\n group_index = group_index.take(sorter)\n\n return lib.indices_fast(sorter, group_index, keys, sorted_labels)" }, { "instruction": "Write or improve a Python function based on this description:\n\nalgos.groupsort_indexer implements `counting sort` and it is at least\n O(ngroups), where\n ngroups = prod(shape)\n shape = map(len, keys)\n that is, linear in the number of combinations (cartesian product) of unique\n values of groupby keys. This can be huge when doing multi-key groupby.\n np.argsort(kind='mergesort') is O(count x log(count)) where count is the\n length of the data-frame;\n Both algorithms are `stable` sort and that is necessary for correctness of\n groupby operations. e.g. consider:\n df.groupby(key)[col].transform('first')", "output": "def get_group_index_sorter(group_index, ngroups):\n \"\"\"\n algos.groupsort_indexer implements `counting sort` and it is at least\n O(ngroups), where\n ngroups = prod(shape)\n shape = map(len, keys)\n that is, linear in the number of combinations (cartesian product) of unique\n values of groupby keys. This can be huge when doing multi-key groupby.\n np.argsort(kind='mergesort') is O(count x log(count)) where count is the\n length of the data-frame;\n Both algorithms are `stable` sort and that is necessary for correctness of\n groupby operations. e.g. consider:\n df.groupby(key)[col].transform('first')\n \"\"\"\n count = len(group_index)\n alpha = 0.0 # taking complexities literally; there may be\n beta = 1.0 # some room for fine-tuning these parameters\n do_groupsort = (count > 0 and ((alpha + beta * ngroups) <\n (count * np.log(count))))\n if do_groupsort:\n sorter, _ = algos.groupsort_indexer(ensure_int64(group_index),\n ngroups)\n return ensure_platform_int(sorter)\n else:\n return group_index.argsort(kind='mergesort')" }, { "instruction": "Write or improve a Python function based on this description:\n\nGroup_index is offsets into cartesian product of all possible labels. This\n space can be huge, so this function compresses it, by computing offsets\n (comp_ids) into the list of unique labels (obs_group_ids).", "output": "def compress_group_index(group_index, sort=True):\n \"\"\"\n Group_index is offsets into cartesian product of all possible labels. This\n space can be huge, so this function compresses it, by computing offsets\n (comp_ids) into the list of unique labels (obs_group_ids).\n \"\"\"\n\n size_hint = min(len(group_index), hashtable._SIZE_HINT_LIMIT)\n table = hashtable.Int64HashTable(size_hint)\n\n group_index = ensure_int64(group_index)\n\n # note, group labels come out ascending (ie, 1,2,3 etc)\n comp_ids, obs_group_ids = table.get_labels_groupby(group_index)\n\n if sort and len(obs_group_ids) > 0:\n obs_group_ids, comp_ids = _reorder_by_uniques(obs_group_ids, comp_ids)\n\n return comp_ids, obs_group_ids" }, { "instruction": "Write or improve a Python function based on this description:\n\nSort ``values`` and reorder corresponding ``labels``.\n ``values`` should be unique if ``labels`` is not None.\n Safe for use with mixed types (int, str), orders ints before strs.\n\n .. versionadded:: 0.19.0\n\n Parameters\n ----------\n values : list-like\n Sequence; must be unique if ``labels`` is not None.\n labels : list_like\n Indices to ``values``. All out of bound indices are treated as\n \"not found\" and will be masked with ``na_sentinel``.\n na_sentinel : int, default -1\n Value in ``labels`` to mark \"not found\".\n Ignored when ``labels`` is None.\n assume_unique : bool, default False\n When True, ``values`` are assumed to be unique, which can speed up\n the calculation. Ignored when ``labels`` is None.\n\n Returns\n -------\n ordered : ndarray\n Sorted ``values``\n new_labels : ndarray\n Reordered ``labels``; returned when ``labels`` is not None.\n\n Raises\n ------\n TypeError\n * If ``values`` is not list-like or if ``labels`` is neither None\n nor list-like\n * If ``values`` cannot be sorted\n ValueError\n * If ``labels`` is not None and ``values`` contain duplicates.", "output": "def safe_sort(values, labels=None, na_sentinel=-1, assume_unique=False):\n \"\"\"\n Sort ``values`` and reorder corresponding ``labels``.\n ``values`` should be unique if ``labels`` is not None.\n Safe for use with mixed types (int, str), orders ints before strs.\n\n .. versionadded:: 0.19.0\n\n Parameters\n ----------\n values : list-like\n Sequence; must be unique if ``labels`` is not None.\n labels : list_like\n Indices to ``values``. All out of bound indices are treated as\n \"not found\" and will be masked with ``na_sentinel``.\n na_sentinel : int, default -1\n Value in ``labels`` to mark \"not found\".\n Ignored when ``labels`` is None.\n assume_unique : bool, default False\n When True, ``values`` are assumed to be unique, which can speed up\n the calculation. Ignored when ``labels`` is None.\n\n Returns\n -------\n ordered : ndarray\n Sorted ``values``\n new_labels : ndarray\n Reordered ``labels``; returned when ``labels`` is not None.\n\n Raises\n ------\n TypeError\n * If ``values`` is not list-like or if ``labels`` is neither None\n nor list-like\n * If ``values`` cannot be sorted\n ValueError\n * If ``labels`` is not None and ``values`` contain duplicates.\n \"\"\"\n if not is_list_like(values):\n raise TypeError(\"Only list-like objects are allowed to be passed to\"\n \"safe_sort as values\")\n\n if not isinstance(values, np.ndarray):\n\n # don't convert to string types\n dtype, _ = infer_dtype_from_array(values)\n values = np.asarray(values, dtype=dtype)\n\n def sort_mixed(values):\n # order ints before strings, safe in py3\n str_pos = np.array([isinstance(x, str) for x in values],\n dtype=bool)\n nums = np.sort(values[~str_pos])\n strs = np.sort(values[str_pos])\n return np.concatenate([nums, np.asarray(strs, dtype=object)])\n\n sorter = None\n if lib.infer_dtype(values, skipna=False) == 'mixed-integer':\n # unorderable in py3 if mixed str/int\n ordered = sort_mixed(values)\n else:\n try:\n sorter = values.argsort()\n ordered = values.take(sorter)\n except TypeError:\n # try this anyway\n ordered = sort_mixed(values)\n\n # labels:\n\n if labels is None:\n return ordered\n\n if not is_list_like(labels):\n raise TypeError(\"Only list-like objects or None are allowed to be\"\n \"passed to safe_sort as labels\")\n labels = ensure_platform_int(np.asarray(labels))\n\n from pandas import Index\n if not assume_unique and not Index(values).is_unique:\n raise ValueError(\"values should be unique if labels is not None\")\n\n if sorter is None:\n # mixed types\n (hash_klass, _), values = algorithms._get_data_algo(\n values, algorithms._hashtables)\n t = hash_klass(len(values))\n t.map_locations(values)\n sorter = ensure_platform_int(t.lookup(ordered))\n\n reverse_indexer = np.empty(len(sorter), dtype=np.int_)\n reverse_indexer.put(sorter, np.arange(len(sorter)))\n\n mask = (labels < -len(values)) | (labels >= len(values)) | \\\n (labels == na_sentinel)\n\n # (Out of bound indices will be masked with `na_sentinel` next, so we may\n # deal with them here without performance loss using `mode='wrap'`.)\n new_labels = reverse_indexer.take(labels, mode='wrap')\n np.putmask(new_labels, mask, na_sentinel)\n\n return ordered, ensure_platform_int(new_labels)" }, { "instruction": "Write or improve a Python function based on this description:\n\nAttempt to prevent foot-shooting in a helpful way.\n\n Parameters\n ----------\n terms : Term\n Terms can contain", "output": "def _check_ne_builtin_clash(expr):\n \"\"\"Attempt to prevent foot-shooting in a helpful way.\n\n Parameters\n ----------\n terms : Term\n Terms can contain\n \"\"\"\n names = expr.names\n overlap = names & _ne_builtins\n\n if overlap:\n s = ', '.join(map(repr, overlap))\n raise NumExprClobberingError('Variables in expression \"{expr}\" '\n 'overlap with builtins: ({s})'\n .format(expr=expr, s=s))" }, { "instruction": "Write or improve a Python function based on this description:\n\nRun the engine on the expression\n\n This method performs alignment which is necessary no matter what engine\n is being used, thus its implementation is in the base class.\n\n Returns\n -------\n obj : object\n The result of the passed expression.", "output": "def evaluate(self):\n \"\"\"Run the engine on the expression\n\n This method performs alignment which is necessary no matter what engine\n is being used, thus its implementation is in the base class.\n\n Returns\n -------\n obj : object\n The result of the passed expression.\n \"\"\"\n if not self._is_aligned:\n self.result_type, self.aligned_axes = _align(self.expr.terms)\n\n # make sure no names in resolvers and locals/globals clash\n res = self._evaluate()\n return _reconstruct_object(self.result_type, res, self.aligned_axes,\n self.expr.terms.return_type)" }, { "instruction": "Write or improve a Python function based on this description:\n\nFind the appropriate Block subclass to use for the given values and dtype.\n\n Parameters\n ----------\n values : ndarray-like\n dtype : numpy or pandas dtype\n\n Returns\n -------\n cls : class, subclass of Block", "output": "def get_block_type(values, dtype=None):\n \"\"\"\n Find the appropriate Block subclass to use for the given values and dtype.\n\n Parameters\n ----------\n values : ndarray-like\n dtype : numpy or pandas dtype\n\n Returns\n -------\n cls : class, subclass of Block\n \"\"\"\n dtype = dtype or values.dtype\n vtype = dtype.type\n\n if is_sparse(dtype):\n # Need this first(ish) so that Sparse[datetime] is sparse\n cls = ExtensionBlock\n elif is_categorical(values):\n cls = CategoricalBlock\n elif issubclass(vtype, np.datetime64):\n assert not is_datetime64tz_dtype(values)\n cls = DatetimeBlock\n elif is_datetime64tz_dtype(values):\n cls = DatetimeTZBlock\n elif is_interval_dtype(dtype) or is_period_dtype(dtype):\n cls = ObjectValuesExtensionBlock\n elif is_extension_array_dtype(values):\n cls = ExtensionBlock\n elif issubclass(vtype, np.floating):\n cls = FloatBlock\n elif issubclass(vtype, np.timedelta64):\n assert issubclass(vtype, np.integer)\n cls = TimeDeltaBlock\n elif issubclass(vtype, np.complexfloating):\n cls = ComplexBlock\n elif issubclass(vtype, np.integer):\n cls = IntBlock\n elif dtype == np.bool_:\n cls = BoolBlock\n else:\n cls = ObjectBlock\n return cls" }, { "instruction": "Write or improve a Python function based on this description:\n\nreturn a new extended blocks, givin the result", "output": "def _extend_blocks(result, blocks=None):\n \"\"\" return a new extended blocks, givin the result \"\"\"\n from pandas.core.internals import BlockManager\n if blocks is None:\n blocks = []\n if isinstance(result, list):\n for r in result:\n if isinstance(r, list):\n blocks.extend(r)\n else:\n blocks.append(r)\n elif isinstance(result, BlockManager):\n blocks.extend(result.blocks)\n else:\n blocks.append(result)\n return blocks" }, { "instruction": "Write or improve a Python function based on this description:\n\nguarantee the shape of the values to be at least 1 d", "output": "def _block_shape(values, ndim=1, shape=None):\n \"\"\" guarantee the shape of the values to be at least 1 d \"\"\"\n if values.ndim < ndim:\n if shape is None:\n shape = values.shape\n if not is_extension_array_dtype(values):\n # TODO: https://github.com/pandas-dev/pandas/issues/23023\n # block.shape is incorrect for \"2D\" ExtensionArrays\n # We can't, and don't need to, reshape.\n values = values.reshape(tuple((1, ) + shape))\n return values" }, { "instruction": "Write or improve a Python function based on this description:\n\nIf possible, reshape `arr` to have shape `new_shape`,\n with a couple of exceptions (see gh-13012):\n\n 1) If `arr` is a ExtensionArray or Index, `arr` will be\n returned as is.\n 2) If `arr` is a Series, the `_values` attribute will\n be reshaped and returned.\n\n Parameters\n ----------\n arr : array-like, object to be reshaped\n new_shape : int or tuple of ints, the new shape", "output": "def _safe_reshape(arr, new_shape):\n \"\"\"\n If possible, reshape `arr` to have shape `new_shape`,\n with a couple of exceptions (see gh-13012):\n\n 1) If `arr` is a ExtensionArray or Index, `arr` will be\n returned as is.\n 2) If `arr` is a Series, the `_values` attribute will\n be reshaped and returned.\n\n Parameters\n ----------\n arr : array-like, object to be reshaped\n new_shape : int or tuple of ints, the new shape\n \"\"\"\n if isinstance(arr, ABCSeries):\n arr = arr._values\n if not isinstance(arr, ABCExtensionArray):\n arr = arr.reshape(new_shape)\n return arr" }, { "instruction": "Write or improve a Python function based on this description:\n\nReturn a new ndarray, try to preserve dtype if possible.\n\n Parameters\n ----------\n v : `values`, updated in-place (array like)\n m : `mask`, applies to both sides (array like)\n n : `new values` either scalar or an array like aligned with `values`\n\n Returns\n -------\n values : ndarray with updated values\n this *may* be a copy of the original\n\n See Also\n --------\n ndarray.putmask", "output": "def _putmask_smart(v, m, n):\n \"\"\"\n Return a new ndarray, try to preserve dtype if possible.\n\n Parameters\n ----------\n v : `values`, updated in-place (array like)\n m : `mask`, applies to both sides (array like)\n n : `new values` either scalar or an array like aligned with `values`\n\n Returns\n -------\n values : ndarray with updated values\n this *may* be a copy of the original\n\n See Also\n --------\n ndarray.putmask\n \"\"\"\n\n # we cannot use np.asarray() here as we cannot have conversions\n # that numpy does when numeric are mixed with strings\n\n # n should be the length of the mask or a scalar here\n if not is_list_like(n):\n n = np.repeat(n, len(m))\n elif isinstance(n, np.ndarray) and n.ndim == 0: # numpy scalar\n n = np.repeat(np.array(n, ndmin=1), len(m))\n\n # see if we are only masking values that if putted\n # will work in the current dtype\n try:\n nn = n[m]\n\n # make sure that we have a nullable type\n # if we have nulls\n if not _isna_compat(v, nn[0]):\n raise ValueError\n\n # we ignore ComplexWarning here\n with warnings.catch_warnings(record=True):\n warnings.simplefilter(\"ignore\", np.ComplexWarning)\n nn_at = nn.astype(v.dtype)\n\n # avoid invalid dtype comparisons\n # between numbers & strings\n\n # only compare integers/floats\n # don't compare integers to datetimelikes\n if (not is_numeric_v_string_like(nn, nn_at) and\n (is_float_dtype(nn.dtype) or\n is_integer_dtype(nn.dtype) and\n is_float_dtype(nn_at.dtype) or\n is_integer_dtype(nn_at.dtype))):\n\n comp = (nn == nn_at)\n if is_list_like(comp) and comp.all():\n nv = v.copy()\n nv[m] = nn_at\n return nv\n except (ValueError, IndexError, TypeError, OverflowError):\n pass\n\n n = np.asarray(n)\n\n def _putmask_preserve(nv, n):\n try:\n nv[m] = n[m]\n except (IndexError, ValueError):\n nv[m] = n\n return nv\n\n # preserves dtype if possible\n if v.dtype.kind == n.dtype.kind:\n return _putmask_preserve(v, n)\n\n # change the dtype if needed\n dtype, _ = maybe_promote(n.dtype)\n\n if is_extension_type(v.dtype) and is_object_dtype(dtype):\n v = v.get_values(dtype)\n else:\n v = v.astype(dtype)\n\n return _putmask_preserve(v, n)" }, { "instruction": "Write or improve a Python function based on this description:\n\nndim inference and validation.\n\n Infers ndim from 'values' if not provided to __init__.\n Validates that values.ndim and ndim are consistent if and only if\n the class variable '_validate_ndim' is True.\n\n Parameters\n ----------\n values : array-like\n ndim : int or None\n\n Returns\n -------\n ndim : int\n\n Raises\n ------\n ValueError : the number of dimensions do not match", "output": "def _check_ndim(self, values, ndim):\n \"\"\"\n ndim inference and validation.\n\n Infers ndim from 'values' if not provided to __init__.\n Validates that values.ndim and ndim are consistent if and only if\n the class variable '_validate_ndim' is True.\n\n Parameters\n ----------\n values : array-like\n ndim : int or None\n\n Returns\n -------\n ndim : int\n\n Raises\n ------\n ValueError : the number of dimensions do not match\n \"\"\"\n if ndim is None:\n ndim = values.ndim\n\n if self._validate_ndim and values.ndim != ndim:\n msg = (\"Wrong number of dimensions. values.ndim != ndim \"\n \"[{} != {}]\")\n raise ValueError(msg.format(values.ndim, ndim))\n\n return ndim" }, { "instruction": "Write or improve a Python function based on this description:\n\nvalidate that we have a astypeable to categorical,\n returns a boolean if we are a categorical", "output": "def is_categorical_astype(self, dtype):\n \"\"\"\n validate that we have a astypeable to categorical,\n returns a boolean if we are a categorical\n \"\"\"\n if dtype is Categorical or dtype is CategoricalDtype:\n # this is a pd.Categorical, but is not\n # a valid type for astypeing\n raise TypeError(\"invalid type {0} for astype\".format(dtype))\n\n elif is_categorical_dtype(dtype):\n return True\n\n return False" }, { "instruction": "Write or improve a Python function based on this description:\n\nreturn an internal format, currently just the ndarray\n this is often overridden to handle to_dense like operations", "output": "def get_values(self, dtype=None):\n \"\"\"\n return an internal format, currently just the ndarray\n this is often overridden to handle to_dense like operations\n \"\"\"\n if is_object_dtype(dtype):\n return self.values.astype(object)\n return self.values" }, { "instruction": "Write or improve a Python function based on this description:\n\nCreate a new block, with type inference propagate any values that are\n not specified", "output": "def make_block(self, values, placement=None, ndim=None):\n \"\"\"\n Create a new block, with type inference propagate any values that are\n not specified\n \"\"\"\n if placement is None:\n placement = self.mgr_locs\n if ndim is None:\n ndim = self.ndim\n\n return make_block(values, placement=placement, ndim=ndim)" }, { "instruction": "Write or improve a Python function based on this description:\n\nWrap given values in a block of same type as self.", "output": "def make_block_same_class(self, values, placement=None, ndim=None,\n dtype=None):\n \"\"\" Wrap given values in a block of same type as self. \"\"\"\n if dtype is not None:\n # issue 19431 fastparquet is passing this\n warnings.warn(\"dtype argument is deprecated, will be removed \"\n \"in a future release.\", DeprecationWarning)\n if placement is None:\n placement = self.mgr_locs\n return make_block(values, placement=placement, ndim=ndim,\n klass=self.__class__, dtype=dtype)" }, { "instruction": "Write or improve a Python function based on this description:\n\nPerform __getitem__-like, return result as block.\n\n As of now, only supports slices that preserve dimensionality.", "output": "def getitem_block(self, slicer, new_mgr_locs=None):\n \"\"\"\n Perform __getitem__-like, return result as block.\n\n As of now, only supports slices that preserve dimensionality.\n \"\"\"\n if new_mgr_locs is None:\n if isinstance(slicer, tuple):\n axis0_slicer = slicer[0]\n else:\n axis0_slicer = slicer\n new_mgr_locs = self.mgr_locs[axis0_slicer]\n\n new_values = self._slice(slicer)\n\n if self._validate_ndim and new_values.ndim != self.ndim:\n raise ValueError(\"Only same dim slicing is allowed\")\n\n return self.make_block_same_class(new_values, new_mgr_locs)" }, { "instruction": "Write or improve a Python function based on this description:\n\nConcatenate list of single blocks of the same type.", "output": "def concat_same_type(self, to_concat, placement=None):\n \"\"\"\n Concatenate list of single blocks of the same type.\n \"\"\"\n values = self._concatenator([blk.values for blk in to_concat],\n axis=self.ndim - 1)\n return self.make_block_same_class(\n values, placement=placement or slice(0, len(values), 1))" }, { "instruction": "Write or improve a Python function based on this description:\n\nDelete given loc(-s) from block in-place.", "output": "def delete(self, loc):\n \"\"\"\n Delete given loc(-s) from block in-place.\n \"\"\"\n self.values = np.delete(self.values, loc, 0)\n self.mgr_locs = self.mgr_locs.delete(loc)" } ]