cuDF API Reference

DataFrame

class cudf.core.dataframe.DataFrame(data=None, index=None, columns=None, dtype=None)

A GPU Dataframe object.

Parameters
dataarray-like, Iterable, dict, or DataFrame.

Dict can contain Series, arrays, constants, or list-like objects.

indexIndex or array-like

Index to use for resulting frame. Will default to RangeIndex if no indexing information part of input data and no index provided.

columnsIndex or array-like

Column labels to use for resulting frame. Will default to RangeIndex (0, 1, 2, …, n) if no column labels are provided.

dtypedtype, default None

Data type to force. Only a single dtype is allowed. If None, infer.

Examples

Build dataframe with __setitem__:

>>> import cudf
>>> df = cudf.DataFrame()
>>> df['key'] = [0, 1, 2, 3, 4]
>>> df['val'] = [float(i + 10) for i in range(5)]  # insert column
>>> print(df)
key   val
0    0  10.0
1    1  11.0
2    2  12.0
3    3  13.0
4    4  14.0

Build DataFrame via dict of columns:

>>> import cudf
>>> import numpy as np
>>> from datetime import datetime, timedelta
>>> t0 = datetime.strptime('2018-10-07 12:00:00', '%Y-%m-%d %H:%M:%S')
>>> n = 5
>>> df = cudf.DataFrame({
... 'id': np.arange(n),
... 'datetimes': np.array(
... [(t0+ timedelta(seconds=x)) for x in range(n)])
... })
>>> df
    id                datetimes
0    0  2018-10-07T12:00:00.000
1    1  2018-10-07T12:00:01.000
2    2  2018-10-07T12:00:02.000
3    3  2018-10-07T12:00:03.000
4    4  2018-10-07T12:00:04.000

Build DataFrame via list of rows as tuples:

>>> import cudf
>>> df = cudf.DataFrame([
... (5, "cats", "jump", np.nan),
... (2, "dogs", "dig", 7.5),
... (3, "cows", "moo", -2.1, "occasionally"),
... ])
>>> df
0     1     2     3             4
0  5  cats  jump  null          None
1  2  dogs   dig   7.5          None
2  3  cows   moo  -2.1  occasionally

Convert from a Pandas DataFrame:

>>> import pandas as pd
>>> import cudf
>>> pdf = pd.DataFrame({'a': [0, 1, 2, 3],'b': [0.1, 0.2, None, 0.3]})
>>> df = cudf.from_pandas(pdf)
>>> df
a b
0 0 0.1
1 1 0.2
2 2 nan
3 3 0.3
Attributes
T

Transpose index and columns.

at

Alias for DataFrame.loc; provided for compatibility with Pandas.

columns

Returns a tuple of columns

dtypes

Return the dtypes in this object.

empty

Indicator whether DataFrame or Series is empty.

iat

Alias for DataFrame.iloc; provided for compatibility with Pandas.

iloc

Selecting rows and column by position.

index

Returns the index of the DataFrame

loc

Selecting rows and columns by label or boolean mask.

ndim

Dimension of the data.

shape

Returns a tuple representing the dimensionality of the DataFrame.

size

Return the number of elements in the underlying data.

values

Return a CuPy representation of the DataFrame.

Methods

acos()

Get Trigonometric inverse cosine, element-wise.

add(other[, axis, level, fill_value])

Get Addition of dataframe and other, element-wise (binary operator add).

add_column(name, data[, forceindex])

Add a column

all([axis, bool_only, skipna, level])

Return whether all elements are True in DataFrame.

any([axis, bool_only, skipna, level])

Return whether any elements is True in DataFrame.

append(other[, ignore_index, …])

Append rows of other to the end of caller, returning a new object.

apply_chunks(func, incols, outcols[, …])

Transform user-specified chunks using the user-provided function.

apply_rows(func, incols, outcols, kwargs[, …])

Apply a row-wise user defined function.

argsort([ascending, na_position])

Sort by the values.

as_gpu_matrix([columns, order])

Convert to a matrix in device memory.

as_matrix([columns])

Convert to a matrix in host memory.

asin()

Get Trigonometric inverse sine, element-wise.

assign(**kwargs)

Assign columns to DataFrame from keyword arguments.

astype(dtype[, copy, errors])

Cast the DataFrame to the given dtype

atan()

Get Trigonometric inverse tangent, element-wise.

clip([lower, upper, inplace, axis])

Trim values at input threshold(s).

copy([deep])

Returns a copy of this dataframe

corr()

Compute the correlation matrix of a DataFrame.

cos()

Get Trigonometric cosine, element-wise.

count([axis, level, numeric_only])

Count non-NA cells for each column or row.

cov(**kwargs)

Compute the covariance matrix of a DataFrame.

cummax([axis, skipna])

Return cumulative maximum of the DataFrame.

cummin([axis, skipna])

Return cumulative minimum of the DataFrame.

cumprod([axis, skipna])

Return cumulative product of the DataFrame.

cumsum([axis, skipna])

Return cumulative sum of the DataFrame.

describe([percentiles, include, exclude, …])

Generate descriptive statistics.

div(other[, axis, level, fill_value])

Get Floating division of dataframe and other, element-wise (binary operator truediv).

drop([labels, axis, index, columns, level, …])

Drop specified labels from rows or columns.

drop_duplicates([subset, keep, inplace, …])

Return DataFrame with duplicate rows removed, optionally only considering certain subset of columns.

dropna([axis, how, thresh, subset, inplace])

Drops rows (or columns) containing nulls from a Column.

equals(other)

Test whether two objects contain the same elements.

exp()

Get the exponential of all elements, element-wise.

fillna(value[, method, axis, inplace, limit])

Fill null values with value.

floordiv(other[, axis, level, fill_value])

Get Integer division of dataframe and other, element-wise (binary operator floordiv).

from_arrow(table)

Convert from PyArrow Table to DataFrame.

from_gpu_matrix(data[, index, columns, …])

Convert from a numba gpu ndarray.

from_pandas(dataframe[, nan_as_null])

Convert from a Pandas DataFrame.

from_records(data[, index, columns, nan_as_null])

Convert structured or record ndarray to DataFrame.

groupby([by, axis, level, as_index, sort, …])

Group DataFrame using a mapper or by a Series of columns.

hash_columns([columns])

Hash the given columns and return a new device array

head([n])

Returns the first n rows as a new DataFrame

info([verbose, buf, max_cols, memory_usage, …])

Print a concise summary of a DataFrame.

insert(loc, name, value)

Add a column to DataFrame at the index specified by loc.

interleave_columns()

Interleave Series columns of a table into a single column.

isin(values)

Whether each element in the DataFrame is contained in values.

isna()

Identify missing values.

isnull()

Identify missing values.

iteritems()

Iterate over column names and series pairs

join(other[, on, how, lsuffix, rsuffix, …])

Join columns with other DataFrame on index or on a key column.

keys()

Get the columns.

kurt([axis, skipna, level, numeric_only])

Return Fisher’s unbiased kurtosis of a sample.

kurtosis([axis, skipna, level, numeric_only])

Return Fisher’s unbiased kurtosis of a sample.

label_encoding(column, prefix, cats[, …])

Encode labels in a column with label encoding.

log()

Get the natural logarithm of all elements, element-wise.

mask(cond[, other, inplace])

Replace values where the condition is True.

max([axis, skipna, level, numeric_only])

Return the maximum of the values in the DataFrame.

mean([axis, skipna, level, numeric_only])

Return the mean of the values for the requested axis.

melt(**kwargs)

Unpivots a DataFrame from wide format to long format, optionally leaving identifier variables set.

memory_usage([index, deep])

Return the memory usage of each column in bytes.

merge(right[, on, left_on, right_on, …])

Merge GPU DataFrame objects by performing a database-style join operation by columns or indexes.

min([axis, skipna, level, numeric_only])

Return the minimum of the values in the DataFrame.

mod(other[, axis, level, fill_value])

Get Modulo division of dataframe and other, element-wise (binary operator mod).

mode([axis, numeric_only, dropna])

Get the mode(s) of each element along the selected axis.

mul(other[, axis, level, fill_value])

Get Multiplication of dataframe and other, element-wise (binary operator mul).

nans_to_nulls()

Convert nans (if any) to nulls.

nlargest(n, columns[, keep])

Get the rows of the DataFrame sorted by the n largest value of columns

notna()

Identify non-missing values.

notnull()

Identify non-missing values.

nsmallest(n, columns[, keep])

Get the rows of the DataFrame sorted by the n smallest value of columns

one_hot_encoding(column, prefix, cats[, …])

Expand a column with one-hot-encoding.

partition_by_hash(columns, nparts[, keep_index])

Partition the dataframe by the hashed value of data in columns.

pivot(index, columns[, values])

Return reshaped DataFrame organized by the given index and column values.

pop(item)

Return a column and drop it from the DataFrame.

pow(other[, axis, level, fill_value])

Get Exponential power of dataframe and other, element-wise (binary operator pow).

prod([axis, skipna, dtype, level, …])

Return product of the values in the DataFrame.

product([axis, skipna, dtype, level, …])

Return product of the values in the DataFrame.

quantile([q, axis, numeric_only, …])

Return values at the given quantile.

quantiles([q, interpolation])

Return values at the given quantile.

query(expr[, local_dict])

Query with a boolean expression using Numba to compile a GPU kernel.

radd(other[, axis, level, fill_value])

Get Addition of dataframe and other, element-wise (binary operator radd).

rank([axis, method, numeric_only, …])

Compute numerical data ranks (1 through n) along axis.

rdiv(other[, axis, level, fill_value])

Get Floating division of dataframe and other, element-wise (binary operator rtruediv).

reindex([labels, axis, index, columns, copy])

Return a new DataFrame whose axes conform to a new index

rename([mapper, index, columns, axis, copy, …])

Alter column and index labels.

repeat(repeats[, axis])

Repeats elements consecutively.

replace([to_replace, value, inplace, limit, …])

Replace values given in to_replace with replacement.

reset_index([level, drop, inplace, …])

Reset the index.

rfloordiv(other[, axis, level, fill_value])

Get Integer division of dataframe and other, element-wise (binary operator rfloordiv).

rmod(other[, axis, level, fill_value])

Get Modulo division of dataframe and other, element-wise (binary operator rmod).

rmul(other[, axis, level, fill_value])

Get Multiplication of dataframe and other, element-wise (binary operator rmul).

rolling(window[, min_periods, center, axis, …])

Rolling window calculations.

rpow(other[, axis, level, fill_value])

Get Exponential power of dataframe and other, element-wise (binary operator pow).

rsub(other[, axis, level, fill_value])

Get Subtraction of dataframe and other, element-wise (binary operator rsub).

rtruediv(other[, axis, level, fill_value])

Get Floating division of dataframe and other, element-wise (binary operator rtruediv).

sample([n, frac, replace, weights, …])

Return a random sample of items from an axis of object.

scatter_by_map(map_index[, map_size, keep_index])

Scatter to a list of dataframes.

searchsorted(values[, side, ascending, …])

Find indices where elements should be inserted to maintain order

select_dtypes([include, exclude])

Return a subset of the DataFrame’s columns based on the column dtypes.

set_index(index[, drop, append, inplace, …])

Return a new DataFrame with a new index

shift([periods, freq, axis, fill_value])

Shift values by periods positions.

sin()

Get Trigonometric sine, element-wise.

skew([axis, skipna, level, numeric_only])

Return unbiased Fisher-Pearson skew of a sample.

sort_index([axis, level, ascending, …])

Sort object by labels (along an axis).

sort_values(by[, axis, ascending, inplace, …])

Sort by the values row-wise.

sqrt()

Get the non-negative square-root of all elements, element-wise.

stack([level, dropna])

Stack the prescribed level(s) from columns to index

std([axis, skipna, level, ddof, numeric_only])

Return sample standard deviation of the DataFrame.

sub(other[, axis, level, fill_value])

Get Subtraction of dataframe and other, element-wise (binary operator sub).

sum([axis, skipna, dtype, level, …])

Return sum of the values in the DataFrame.

tail([n])

Returns the last n rows as a new DataFrame

take(positions[, keep_index])

Return a new DataFrame containing the rows specified by positions

tan()

Get Trigonometric tangent, element-wise.

tile(count)

Repeats the rows from self DataFrame count times to form a new DataFrame.

to_arrow([preserve_index])

Convert to a PyArrow Table.

to_csv([path, sep, na_rep, columns, header, …])

Write a dataframe to csv file format.

to_dlpack()

Converts a cuDF object into a DLPack tensor.

to_feather(path, *args, **kwargs)

Write a DataFrame to the feather format.

to_gpu_matrix()

Convert to a numba gpu ndarray

to_hdf(path_or_buf, key, *args, **kwargs)

Write the contained data to an HDF5 file using HDFStore.

to_json([path_or_buf])

Convert the cuDF object to a JSON string.

to_orc(fname[, compression])

Write a DataFrame to the ORC format.

to_pandas(**kwargs)

Convert to a Pandas DataFrame.

to_parquet(path, *args, **kwargs)

Write a DataFrame to the parquet format.

to_records([index])

Convert to a numpy recarray

to_string()

Convert to string

transpose()

Transpose index and columns.

truediv(other[, axis, level, fill_value])

Get Floating division of dataframe and other, element-wise (binary operator truediv).

unstack([level, fill_value])

Pivot one or more levels of the (necessarily hierarchical) index labels.

var([axis, skipna, level, ddof, numeric_only])

Return unbiased variance of the DataFrame.

where(cond[, other, inplace])

Replace values where the condition is False.

property T

Transpose index and columns.

Reflect the DataFrame over its main diagonal by writing rows as columns and vice-versa. The property T is an accessor to the method transpose().

Returns
outDataFrame

The transposed DataFrame.

acos()

Get Trigonometric inverse cosine, element-wise.

The inverse of cos so that, if y = x.cos(), then x = y.acos()

Returns
DataFrame/Series/Index

Result of the trigonometric operation.

Examples

>>> import cudf
>>> ser = cudf.Series([-1, 0, 1, 0.32434, 0.5])
>>> ser.acos()
0    3.141593
1    1.570796
2    0.000000
3    1.240482
4    1.047198
dtype: float64

acos operation on DataFrame:

>>> df = cudf.DataFrame({'first': [-1, 0, 0.5],
...                      'second': [0.234, 0.3, 0.1]})
>>> df
   first  second
0   -1.0   0.234
1    0.0   0.300
2    0.5   0.100
>>> df.acos()
      first    second
0  3.141593  1.334606
1  1.570796  1.266104
2  1.047198  1.470629

acos operation on Index:

>>> index = cudf.Index([-1, 0.4, 1, 0, 0.3])
>>> index
Float64Index([-1.0, 0.4, 1.0, 0.0, 0.3], dtype='float64')
>>> index.acos()
Float64Index([ 3.141592653589793, 1.1592794807274085, 0.0,
            1.5707963267948966,  1.266103672779499],
            dtype='float64')
add(other, axis='columns', level=None, fill_value=None)

Get Addition of dataframe and other, element-wise (binary operator add).

Equivalent to dataframe + other, but with support to substitute a fill_value for missing data in one of the inputs. With reverse version, radd.

Among flexible wrappers (add, sub, mul, div, mod, pow) to arithmetic operators: +, -, *, /, //, %, **.

Parameters
otherscalar, sequence, Series, or DataFrame

Any single or multiple element data structure, or list-like object.

fill_valuefloat or None, default None

Fill existing missing (NaN) values, and any new element needed for successful DataFrame alignment, with this value before computation. If data in both corresponding DataFrame locations is missing the result will be missing.

Returns
DataFrame

Result of the arithmetic operation.

Examples

>>> import cudf
>>> df = cudf.DataFrame({'angles': [0, 3, 4],
...                    'degrees': [360, 180, 360]},
...                   index=['circle', 'triangle', 'rectangle'])
>>> df + 1
        angles  degrees
circle          1      361
triangle        4      181
rectangle       5      361
>>> df.add(1)
        angles  degrees
circle          1      361
triangle        4      181
rectangle       5      361
add_column(name, data, forceindex=False)

Add a column

Parameters
namestr

Name of column to be added.

dataSeries, array-like

Values to be added.

all(axis=0, bool_only=None, skipna=True, level=None, **kwargs)

Return whether all elements are True in DataFrame.

Parameters
skipna: bool, default True

Exclude NA/null values. If the entire row/column is NA and skipna is True, then the result will be True, as for an empty row/column. If skipna is False, then NA are treated as True, because these are not equal to zero.

Returns
Series

Notes

Parameters currently not supported are axis, bool_only, level.

Examples

>>> import cudf
>>> df = cudf.DataFrame({'a': [3, 2, 3, 4], 'b': [7, 0, 10, 10]})
>>> df.all()
a     True
b    False
dtype: bool
any(axis=0, bool_only=None, skipna=True, level=None, **kwargs)

Return whether any elements is True in DataFrame.

Parameters
skipna: bool, default True

Exclude NA/null values. If the entire row/column is NA and skipna is True, then the result will be False, as for an empty row/column. If skipna is False, then NA are treated as True, because these are not equal to zero.

Returns
Series

Notes

Parameters currently not supported are axis, bool_only, level.

Examples

>>> import cudf
>>> df = cudf.DataFrame({'a': [3, 2, 3, 4], 'b': [7, 0, 10, 10]})
>>> df.any()
a    True
b    True
dtype: bool
append(other, ignore_index=False, verify_integrity=False, sort=False)

Append rows of other to the end of caller, returning a new object. Columns in other that are not in the caller are added as new columns.

Parameters
otherDataFrame or Series/dict-like object, or list of these

The data to append.

ignore_indexbool, default False

If True, do not use the index labels.

sortbool, default False

Sort columns ordering if the columns of self and other are not aligned.

verify_integritybool, default False

This Parameter is currently not supported.

Returns
DataFrame

See also

cudf.core.reshape.concat

General function to concatenate DataFrame or objects.

Notes

If a list of dict/series is passed and the keys are all contained in the DataFrame’s index, the order of the columns in the resulting DataFrame will be unchanged. Iteratively appending rows to a cudf DataFrame can be more computationally intensive than a single concatenate. A better solution is to append those rows to a list and then concatenate the list with the original DataFrame all at once. verify_integrity parameter is not supported yet.

Examples

>>> import cudf
>>> df = cudf.DataFrame([[1, 2], [3, 4]], columns=list('AB'))
>>> df
   A  B
0  1  2
1  3  4
>>> df2 = cudf.DataFrame([[5, 6], [7, 8]], columns=list('AB'))
>>> df2
   A  B
0  5  6
1  7  8
>>> df.append(df2)
   A  B
0  1  2
1  3  4
0  5  6
1  7  8

With ignore_index set to True:

>>> df.append(df2, ignore_index=True)
   A  B
0  1  2
1  3  4
2  5  6
3  7  8

The following, while not recommended methods for generating DataFrames, show two ways to generate a DataFrame from multiple data sources. Less efficient:

>>> df = cudf.DataFrame(columns=['A'])
>>> for i in range(5):
...     df = df.append({'A': i}, ignore_index=True)
>>> df
   A
0  0
1  1
2  2
3  3
4  4

More efficient than above:

>>> cudf.concat([cudf.DataFrame([i], columns=['A']) for i in range(5)],
...           ignore_index=True)
   A
0  0
1  1
2  2
3  3
4  4
apply_chunks(func, incols, outcols, kwargs={}, pessimistic_nulls=True, chunks=None, blkct=None, tpb=None)

Transform user-specified chunks using the user-provided function.

Parameters
dfDataFrame

The source dataframe.

funcfunction

The transformation function that will be executed on the CUDA GPU.

incols: list or dict

A list of names of input columns that match the function arguments. Or, a dictionary mapping input column names to their corresponding function arguments such as {‘col1’: ‘arg1’}.

outcols: dict

A dictionary of output column names and their dtype.

kwargs: dict

name-value of extra arguments. These values are passed directly into the function.

pessimistic_nullsbool

Whether or not apply_rows output should be null when any corresponding input is null. If False, all outputs will be non-null, but will be the result of applying func against the underlying column data, which may be garbage.

chunksint or Series-like

If it is an int, it is the chunksize. If it is an array, it contains integer offset for the start of each chunk. The span of a chunk for chunk i-th is data[chunks[i] : chunks[i + 1]] for any i + 1 < chunks.size; or, data[chunks[i]:] for the i == len(chunks) - 1.

tpbint; optional

The threads-per-block for the underlying kernel. If not specified (Default), uses Numba .forall(...) built-in to query the CUDA Driver API to determine optimal kernel launch configuration. Specify 1 to emulate serial execution for each chunk. It is a good starting point but inefficient. Its maximum possible value is limited by the available CUDA GPU resources.

blkctint; optional

The number of blocks for the underlying kernel. If not specified (Default) and tpb is not specified (Default), uses Numba .forall(...) built-in to query the CUDA Driver API to determine optimal kernel launch configuration. If not specified (Default) and tpb is specified, uses chunks as the number of blocks.

Examples

For tpb > 1, func is executed by tpb number of threads concurrently. To access the thread id and count, use numba.cuda.threadIdx.x and numba.cuda.blockDim.x, respectively (See numba CUDA kernel documentation).

In the example below, the kernel is invoked concurrently on each specified chunk. The kernel computes the corresponding output for the chunk.

By looping over the range range(cuda.threadIdx.x, in1.size, cuda.blockDim.x), the kernel function can be used with any tpb in an efficient manner.

>>> from numba import cuda
>>> @cuda.jit
... def kernel(in1, in2, in3, out1):
...      for i in range(cuda.threadIdx.x, in1.size, cuda.blockDim.x):
...          x = in1[i]
...          y = in2[i]
...          z = in3[i]
...          out1[i] = x * y + z
apply_rows(func, incols, outcols, kwargs, pessimistic_nulls=True, cache_key=None)

Apply a row-wise user defined function.

Parameters
dfDataFrame

The source dataframe.

funcfunction

The transformation function that will be executed on the CUDA GPU.

incols: list or dict

A list of names of input columns that match the function arguments. Or, a dictionary mapping input column names to their corresponding function arguments such as {‘col1’: ‘arg1’}.

outcols: dict

A dictionary of output column names and their dtype.

kwargs: dict

name-value of extra arguments. These values are passed directly into the function.

pessimistic_nullsbool

Whether or not apply_rows output should be null when any corresponding input is null. If False, all outputs will be non-null, but will be the result of applying func against the underlying column data, which may be garbage.

Examples

The user function should loop over the columns and set the output for each row. Loop execution order is arbitrary, so each iteration of the loop MUST be independent of each other.

When func is invoked, the array args corresponding to the input/output are strided so as to improve GPU parallelism. The loop in the function resembles serial code, but executes concurrently in multiple threads.

>>> import cudf
>>> import numpy as np
>>> df = cudf.DataFrame()
>>> nelem = 3
>>> df['in1'] = np.arange(nelem)
>>> df['in2'] = np.arange(nelem)
>>> df['in3'] = np.arange(nelem)

Define input columns for the kernel

>>> in1 = df['in1']
>>> in2 = df['in2']
>>> in3 = df['in3']
>>> def kernel(in1, in2, in3, out1, out2, kwarg1, kwarg2):
...     for i, (x, y, z) in enumerate(zip(in1, in2, in3)):
...         out1[i] = kwarg2 * x - kwarg1 * y
...         out2[i] = y - kwarg1 * z

Call .apply_rows with the name of the input columns, the name and dtype of the output columns, and, optionally, a dict of extra arguments.

>>> df.apply_rows(kernel,
...               incols=['in1', 'in2', 'in3'],
...               outcols=dict(out1=np.float64, out2=np.float64),
...               kwargs=dict(kwarg1=3, kwarg2=4))
   in1  in2  in3 out1 out2
0    0    0    0  0.0  0.0
1    1    1    1  1.0 -2.0
2    2    2    2  2.0 -4.0
argsort(ascending=True, na_position='last')

Sort by the values.

Parameters
ascendingbool or list of bool, default True

If True, sort values in ascending order, otherwise descending.

na_position{‘first’ or ‘last’}, default ‘last’

Argument ‘first’ puts NaNs at the beginning, ‘last’ puts NaNs at the end.

Returns
out_column_indscuDF Column of indices sorted based on input

Notes

Difference from pandas:

  • Support axis=’index’ only.

  • Not supporting: inplace, kind

  • Ascending can be a list of bools to control per column

as_gpu_matrix(columns=None, order='F')

Convert to a matrix in device memory.

Parameters
columnssequence of str

List of a column names to be extracted. The order is preserved. If None is specified, all columns are used.

order‘F’ or ‘C’

Optional argument to determine whether to return a column major (Fortran) matrix or a row major (C) matrix.

Returns
A (nrow x ncol) numba device ndarray
as_matrix(columns=None)

Convert to a matrix in host memory.

Parameters
columnssequence of str

List of a column names to be extracted. The order is preserved. If None is specified, all columns are used.

Returns
A (nrow x ncol) numpy ndarray in “F” order.
asin()

Get Trigonometric inverse sine, element-wise.

The inverse of sine so that, if y = x.sin(), then x = y.asin()

Returns
DataFrame/Series/Index

Result of the trigonometric operation.

Examples

>>> import cudf
>>> ser = cudf.Series([-1, 0, 1, 0.32434, 0.5])
>>> ser.asin()
0   -1.570796
1    0.000000
2    1.570796
3    0.330314
4    0.523599
dtype: float64

asin operation on DataFrame:

>>> df = cudf.DataFrame({'first': [-1, 0, 0.5],
...                      'second': [0.234, 0.3, 0.1]})
>>> df
   first  second
0   -1.0   0.234
1    0.0   0.300
2    0.5   0.100
>>> df.asin()
      first    second
0 -1.570796  0.236190
1  0.000000  0.304693
2  0.523599  0.100167

asin operation on Index:

>>> index = cudf.Index([-1, 0.4, 1, 0.3])
>>> index
Float64Index([-1.0, 0.4, 1.0, 0.3], dtype='float64')
>>> index.asin()
Float64Index([-1.5707963267948966, 0.41151684606748806,
            1.5707963267948966, 0.3046926540153975],
            dtype='float64')
assign(**kwargs)

Assign columns to DataFrame from keyword arguments.

Examples

>>> import cudf
>>> df = cudf.DataFrame()
>>> df = df.assign(a=[0, 1, 2], b=[3, 4, 5])
>>> print(df)
   a  b
0  0  3
1  1  4
2  2  5
astype(dtype, copy=False, errors='raise', **kwargs)

Cast the DataFrame to the given dtype

Parameters
dtypedata type, or dict of column name -> data type

Use a numpy.dtype or Python type to cast entire DataFrame object to the same type. Alternatively, use {col: dtype, ...}, where col is a column label and dtype is a numpy.dtype or Python type to cast one or more of the DataFrame’s columns to column-specific types.

copybool, default False

Return a deep-copy when copy=True. Note by default copy=False setting is used and hence changes to values then may propagate to other cudf objects.

errors{‘raise’, ‘ignore’, ‘warn’}, default ‘raise’

Control raising of exceptions on invalid data for provided dtype.

  • raise : allow exceptions to be raised

  • ignore : suppress exceptions. On error return original object.

  • warn : prints last exceptions as warnings and return original object.

**kwargsextra arguments to pass on to the constructor
Returns
castedDataFrame
property at

Alias for DataFrame.loc; provided for compatibility with Pandas.

atan()

Get Trigonometric inverse tangent, element-wise.

The inverse of tan so that, if y = x.tan(), then x = y.atan()

Returns
DataFrame/Series/Index

Result of the trigonometric operation.

Examples

>>> import cudf
>>> ser = cudf.Series([-1, 0, 1, 0.32434, 0.5, -10])
>>> ser
0    -1.00000
1     0.00000
2     1.00000
3     0.32434
4     0.50000
5   -10.00000
dtype: float64
>>> ser.atan()
0   -0.785398
1    0.000000
2    0.785398
3    0.313635
4    0.463648
5   -1.471128
dtype: float64

atan operation on DataFrame:

>>> df = cudf.DataFrame({'first': [-1, -10, 0.5],
...                      'second': [0.234, 0.3, 10]})
>>> df
   first  second
0   -1.0   0.234
1  -10.0   0.300
2    0.5  10.000
>>> df.atan()
      first    second
0 -0.785398  0.229864
1 -1.471128  0.291457
2  0.463648  1.471128

atan operation on Index:

>>> index = cudf.Index([-1, 0.4, 1, 0, 0.3])
>>> index
Float64Index([-1.0, 0.4, 1.0, 0.0, 0.3], dtype='float64')
>>> index.atan()
Float64Index([-0.7853981633974483,  0.3805063771123649,
                            0.7853981633974483, 0.0,
                            0.2914567944778671],
            dtype='float64')
clip(lower=None, upper=None, inplace=False, axis=1)

Trim values at input threshold(s).

Assigns values outside boundary to boundary values. Thresholds can be singular values or array like, and in the latter case the clipping is performed element-wise in the specified axis. Currently only axis=1 is supported.

Parameters
lowerscalar or array_like, default None

Minimum threshold value. All values below this threshold will be set to it. If it is None, there will be no clipping based on lower. In case of Series/Index, lower is expected to be a scalar or an array of size 1.

upperscalar or array_like, default None

Maximum threshold value. All values below this threshold will be set to it. If it is None, there will be no clipping based on upper. In case of Series, upper is expected to be a scalar or an array of size 1.

inplacebool, default False
Returns
Clipped DataFrame/Series/Index/MultiIndex

Examples

>>> import cudf
>>> df = cudf.DataFrame({"a":[1, 2, 3, 4], "b":['a', 'b', 'c', 'd']})
>>> df.clip(lower=[2, 'b'], upper=[3, 'c'])
   a  b
0  2  b
1  2  b
2  3  c
3  3  c
>>> df.clip(lower=None, upper=[3, 'c'])
   a  b
0  1  a
1  2  b
2  3  c
3  3  c
>>> df.clip(lower=[2, 'b'], upper=None)
   a  b
0  2  b
1  2  b
2  3  c
3  4  d
>>> df.clip(lower=2, upper=3, inplace=True)
>>> df
   a  b
0  2  2
1  2  3
2  3  3
3  3  3
>>> import cudf
>>> sr = cudf.Series([1, 2, 3, 4])
>>> sr.clip(lower=2, upper=3)
0    2
1    2
2    3
3    3
dtype: int64
>>> sr.clip(lower=None, upper=3)
0    1
1    2
2    3
3    3
dtype: int64
>>> sr.clip(lower=2, upper=None, inplace=True)
>>> sr
0    2
1    2
2    3
3    4
dtype: int64
property columns

Returns a tuple of columns

copy(deep=True)

Returns a copy of this dataframe

Parameters
deep: bool

Make a full copy of Series columns and Index at the GPU level, or create a new allocation with references.

corr()

Compute the correlation matrix of a DataFrame.

cos()

Get Trigonometric cosine, element-wise.

Returns
DataFrame/Series/Index

Result of the trigonometric operation.

Examples

>>> import cudf
>>> ser = cudf.Series([0.0, 0.32434, 0.5, 45, 90, 180, 360])
>>> ser
0      0.00000
1      0.32434
2      0.50000
3     45.00000
4     90.00000
5    180.00000
6    360.00000
dtype: float64
>>> ser.cos()
0    1.000000
1    0.947861
2    0.877583
3    0.525322
4   -0.448074
5   -0.598460
6   -0.283691
dtype: float64

cos operation on DataFrame:

>>> df = cudf.DataFrame({'first': [0.0, 5, 10, 15],
...                      'second': [100.0, 360, 720, 300]})
>>> df
   first  second
0    0.0   100.0
1    5.0   360.0
2   10.0   720.0
3   15.0   300.0
>>> df.cos()
      first    second
0  1.000000  0.862319
1  0.283662 -0.283691
2 -0.839072 -0.839039
3 -0.759688 -0.022097

cos operation on Index:

>>> index = cudf.Index([-0.4, 100, -180, 90])
>>> index
Float64Index([-0.4, 100.0, -180.0, 90.0], dtype='float64')
>>> index.cos()
Float64Index([ 0.9210609940028851,  0.8623188722876839,
            -0.5984600690578581, -0.4480736161291701],
            dtype='float64')
count(axis=0, level=None, numeric_only=False, **kwargs)

Count non-NA cells for each column or row.

The values None, NaN, NaT are considered NA.

Returns
Series

For each column/row the number of non-NA/null entries.

Notes

Parameters currently not supported are axis, level, numeric_only.

Examples

>>> import cudf
>>> import numpy as np
>>> df = cudf.DataFrame({"Person":
...        ["John", "Myla", "Lewis", "John", "Myla"],
...        "Age": [24., np.nan, 21., 33, 26],
...        "Single": [False, True, True, True, False]})
>>> df.count()
Person    5
Age       4
Single    5
dtype: int64
cov(**kwargs)

Compute the covariance matrix of a DataFrame.

Parameters
**kwargs

Keyword arguments to be passed to cupy.cov

Returns
covDataFrame
cummax(axis=None, skipna=True, *args, **kwargs)

Return cumulative maximum of the DataFrame.

Parameters
skipna: bool, default True

Exclude NA/null values. If an entire row/column is NA, the result will be NA.

Returns
DataFrame

Notes

Parameters currently not supported is axis

Examples

>>> import cudf
>>> df = cudf.DataFrame({'a': [1, 2, 3, 4], 'b': [7, 8, 9, 10]})
>>> df.cummax()
   a   b
0  1   7
1  2   8
2  3   9
3  4  10
cummin(axis=None, skipna=True, *args, **kwargs)

Return cumulative minimum of the DataFrame.

Parameters
skipna: bool, default True

Exclude NA/null values. If an entire row/column is NA, the result will be NA.

Returns
DataFrame

Notes

Parameters currently not supported is axis

Examples

>>> import cudf
>>> df = cudf.DataFrame({'a': [1, 2, 3, 4], 'b': [7, 8, 9, 10]})
>>> df.cummin()
   a  b
0  1  7
1  1  7
2  1  7
3  1  7
cumprod(axis=None, skipna=True, *args, **kwargs)

Return cumulative product of the DataFrame.

Parameters
skipna: bool, default True

Exclude NA/null values. If an entire row/column is NA, the result will be NA.

Returns
DataFrame

Notes

Parameters currently not supported is axis

Examples

>>> import cudf
>>> df = cudf.DataFrame({'a': [1, 2, 3, 4], 'b': [7, 8, 9, 10]})
>>> s.cumprod()
    a     b
0   1     7
1   2    56
2   6   504
3  24  5040
cumsum(axis=None, skipna=True, *args, **kwargs)

Return cumulative sum of the DataFrame.

Parameters
skipna: bool, default True

Exclude NA/null values. If an entire row/column is NA, the result will be NA.

Returns
DataFrame

Notes

Parameters currently not supported is axis

Examples

>>> import cudf
>>> df = cudf.DataFrame({'a': [1, 2, 3, 4], 'b': [7, 8, 9, 10]})
>>> s.cumsum()
    a   b
0   1   7
1   3  15
2   6  24
3  10  34
describe(percentiles=None, include=None, exclude=None, datetime_is_numeric=False)

Generate descriptive statistics.

Descriptive statistics include those that summarize the central tendency, dispersion and shape of a dataset’s distribution, excluding NaN values.

Analyzes both numeric and object series, as well as DataFrame column sets of mixed data types. The output will vary depending on what is provided. Refer to the notes below for more detail.

Parameters
percentileslist-like of numbers, optional

The percentiles to include in the output. All should fall between 0 and 1. The default is [.25, .5, .75], which returns the 25th, 50th, and 75th percentiles.

include‘all’, list-like of dtypes or None(default), optional

A list of data types to include in the result. Ignored for Series. Here are the options:

  • ‘all’ : All columns of the input will be included in the output.

  • A list-like of dtypes : Limits the results to the provided data types. To limit the result to numeric types submit numpy.number. To limit it instead to object columns submit the numpy.object data type. Strings can also be used in the style of select_dtypes (e.g. df.describe(include=['O'])). To select pandas categorical columns, use 'category'

  • None (default) : The result will include all numeric columns.

excludelist-like of dtypes or None (default), optional,

A list of data types to omit from the result. Ignored for Series. Here are the options:

  • A list-like of dtypes : Excludes the provided data types from the result. To exclude numeric types submit numpy.number. To exclude object columns submit the data type numpy.object. Strings can also be used in the style of select_dtypes (e.g. df.describe(include=['O'])). To exclude pandas categorical columns, use 'category'

  • None (default) : The result will exclude nothing.

datetime_is_numericbool, default False

For DataFrame input, this also controls whether datetime columns are included by default.

Returns
output_frameSeries or DataFrame

Summary statistics of the Series or Dataframe provided.

Notes

For numeric data, the result’s index will include count, mean, std, min, max as well as lower, 50 and upper percentiles. By default the lower percentile is 25 and the upper percentile is 75. The 50 percentile is the same as the median.

For strings dtype or datetime dtype, the result’s index will include count, unique, top, and freq. The top is the most common value. The freq is the most common value’s frequency. Timestamps also include the first and last items.

If multiple object values have the highest count, then the count and top results will be arbitrarily chosen from among those with the highest count.

For mixed data types provided via a DataFrame, the default is to return only an analysis of numeric columns. If the dataframe consists only of object and categorical data without any numeric columns, the default is to return an analysis of both the object and categorical columns. If include='all' is provided as an option, the result will include a union of attributes of each type.

The include and exclude parameters can be used to limit which columns in a DataFrame are analyzed for the output. The parameters are ignored when analyzing a Series.

Examples

Describing a Series containing numeric values.

>>> import cudf
>>> s = cudf.Series([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
>>> s
0     1
1     2
2     3
3     4
4     5
5     6
6     7
7     8
8     9
9    10
dtype: int64
>>> s.describe()
count    10.00000
mean      5.50000
std       3.02765
min       1.00000
25%       3.25000
50%       5.50000
75%       7.75000
max      10.00000
dtype: float64

Describing a categorical Series.

>>> s = cudf.Series(['a', 'b', 'a', 'b', 'c', 'a'], dtype='category')
>>> s
0    a
1    b
2    a
3    b
4    c
5    a
dtype: category
Categories (3, object): ['a', 'b', 'c']
>>> s.describe()
count     6
unique    3
top       a
freq      3
dtype: object

Describing a timestamp Series.

>>> import numpy as np
>>> s = cudf.Series([
...   np.datetime64("2000-01-01"),
...   np.datetime64("2010-01-01"),
...   np.datetime64("2010-01-01")
... ])
>>> s
0   2000-01-01
1   2010-01-01
2   2010-01-01
dtype: datetime64[s]
>>> s.describe()
count                                3
mean     2006-09-01 08:00:00.000000000
min      2000-01-01 00:00:00.000000000
25%      2004-12-31 12:00:00.000000000
50%      2010-01-01 00:00:00.000000000
75%      2010-01-01 00:00:00.000000000
max      2010-01-01 00:00:00.000000000
dtype: object

Describing a DataFrame. By default only numeric fields are returned.

>>> df = cudf.DataFrame({"categorical": cudf.Series(['d', 'e', 'f'],
...                         dtype='category'),
...                      "numeric": [1, 2, 3],
...                      "object": ['a', 'b', 'c']
... })
>>> df
  categorical  numeric object
0           d        1      a
1           e        2      b
2           f        3      c
>>> df.describe()
       numeric
count      3.0
mean       2.0
std        1.0
min        1.0
25%        1.5
50%        2.0
75%        2.5
max        3.0

Describing all columns of a DataFrame regardless of data type.

>>> df.describe(include='all')
       categorical numeric object
count            3     3.0      3
unique           3    <NA>      3
top              d    <NA>      a
freq             1    <NA>      1
mean          <NA>     2.0   <NA>
std           <NA>     1.0   <NA>
min           <NA>     1.0   <NA>
25%           <NA>     1.5   <NA>
50%           <NA>     2.0   <NA>
75%           <NA>     2.5   <NA>
max           <NA>     3.0   <NA>

Describing a column from a DataFrame by accessing it as an attribute.

>>> df.numeric.describe()
count    3.0
mean     2.0
std      1.0
min      1.0
25%      1.5
50%      2.0
75%      2.5
max      3.0
Name: numeric, dtype: float64

Including only numeric columns in a DataFrame description.

>>> df.describe(include=[np.number])
       numeric
count      3.0
mean       2.0
std        1.0
min        1.0
25%        1.5
50%        2.0
75%        2.5
max        3.0

Including only string columns in a DataFrame description.

>>> df.describe(include=[object])
       object
count       3
unique      3
top         a
freq        1

Including only categorical columns from a DataFrame description.

>>> df.describe(include=['category'])
       categorical
count            3
unique           3
top              d
freq             1

Excluding numeric columns from a DataFrame description.

>>> df.describe(exclude=[np.number])
       categorical object
count            3      3
unique           3      3
top              d      a
freq             1      1

Excluding object columns from a DataFrame description.

>>> df.describe(exclude=[object])
       categorical numeric
count            3     3.0
unique           3    <NA>
top              d    <NA>
freq             1    <NA>
mean          <NA>     2.0
std           <NA>     1.0
min           <NA>     1.0
25%           <NA>     1.5
50%           <NA>     2.0
75%           <NA>     2.5
max           <NA>     3.0
div(other, axis='columns', level=None, fill_value=None)

Get Floating division of dataframe and other, element-wise (binary operator truediv).

Equivalent to dataframe / other, but with support to substitute a fill_value for missing data in one of the inputs. With reverse version, rtruediv.

Among flexible wrappers (add, sub, mul, div, mod, pow) to arithmetic operators: +, -, *, /, //, %, **.

Parameters
otherscalar, sequence, Series, or DataFrame

Any single or multiple element data structure, or list-like object.

fill_valuefloat or None, default None

Fill existing missing (NaN) values, and any new element needed for successful DataFrame alignment, with this value before computation. If data in both corresponding DataFrame locations is missing the result will be missing.

Returns
DataFrame

Result of the arithmetic operation.

Examples

>>> import cudf
>>> df = cudf.DataFrame({'angles': [0, 3, 4],
...                    'degrees': [360, 180, 360]},
...                   index=['circle', 'triangle', 'rectangle'])
>>> df.truediv(10)
            angles  degrees
circle        0.0     36.0
triangle      0.3     18.0
rectangle     0.4     36.0
>>> df.div(10)
            angles  degrees
circle        0.0     36.0
triangle      0.3     18.0
rectangle     0.4     36.0
>>> df / 10
            angles  degrees
circle        0.0     36.0
triangle      0.3     18.0
rectangle     0.4     36.0
drop(labels=None, axis=0, index=None, columns=None, level=None, inplace=False, errors='raise')

Drop specified labels from rows or columns.

Remove rows or columns by specifying label names and corresponding axis, or by specifying directly index or column names. When using a multi-index, labels on different levels can be removed by specifying the level.

Parameters
labelssingle label or list-like

Index or column labels to drop.

axis{0 or ‘index’, 1 or ‘columns’}, default 0

Whether to drop labels from the index (0 or ‘index’) or columns (1 or ‘columns’).

indexsingle label or list-like

Alternative to specifying axis (labels, axis=0 is equivalent to index=labels).

columnssingle label or list-like

Alternative to specifying axis (labels, axis=1 is equivalent to columns=labels).

levelint or level name, optional

For MultiIndex, level from which the labels will be removed.

inplacebool, default False

If False, return a copy. Otherwise, do operation inplace and return None.

errors{‘ignore’, ‘raise’}, default ‘raise’

If ‘ignore’, suppress error and only existing labels are dropped.

Returns
DataFrame

DataFrame without the removed index or column labels.

Raises
KeyError

If any of the labels is not found in the selected axis.

See also

DataFrame.loc

Label-location based indexer for selection by label.

DataFrame.dropna

Return DataFrame with labels on given axis omitted where (all or any) data are missing.

DataFrame.drop_duplicates

Return DataFrame with duplicate rows removed, optionally only considering certain columns.

Examples

>>> import cudf
>>> df = cudf.DataFrame({"A": [1, 2, 3, 4],
...                      "B": [5, 6, 7, 8],
...                      "C": [10, 11, 12, 13],
...                      "D": [20, 30, 40, 50]})
>>> df
   A  B   C   D
0  1  5  10  20
1  2  6  11  30
2  3  7  12  40
3  4  8  13  50

Drop columns

>>> df.drop(['B', 'C'], axis=1)
   A   D
0  1  20
1  2  30
2  3  40
3  4  50
>>> df.drop(columns=['B', 'C'])
   A   D
0  1  20
1  2  30
2  3  40
3  4  50

Drop a row by index

>>> df.drop([0, 1])
   A  B   C   D
2  3  7  12  40
3  4  8  13  50

Drop columns and/or rows of MultiIndex DataFrame

>>> midx = cudf.MultiIndex(levels=[['lama', 'cow', 'falcon'],
...                              ['speed', 'weight', 'length']],
...                      codes=[[0, 0, 0, 1, 1, 1, 2, 2, 2],
...                             [0, 1, 2, 0, 1, 2, 0, 1, 2]])
>>> df = cudf.DataFrame(index=midx, columns=['big', 'small'],
...                   data=[[45, 30], [200, 100], [1.5, 1], [30, 20],
...                         [250, 150], [1.5, 0.8], [320, 250],
...                         [1, 0.8], [0.3, 0.2]])
>>> df
                 big  small
lama   speed    45.0   30.0
       weight  200.0  100.0
       length    1.5    1.0
cow    speed    30.0   20.0
       weight  250.0  150.0
       length    1.5    0.8
falcon speed   320.0  250.0
       weight    1.0    0.8
       length    0.3    0.2
>>> df.drop(index='cow', columns='small')
                 big
lama   speed    45.0
       weight  200.0
       length    1.5
falcon speed   320.0
       weight    1.0
       length    0.3
>>> df.drop(index='length', level=1)
                 big  small
lama   speed    45.0   30.0
       weight  200.0  100.0
cow    speed    30.0   20.0
       weight  250.0  150.0
falcon speed   320.0  250.0
       weight    1.0    0.8
drop_duplicates(subset=None, keep='first', inplace=False, ignore_index=False)

Return DataFrame with duplicate rows removed, optionally only considering certain subset of columns.

dropna(axis=0, how='any', thresh=None, subset=None, inplace=False)

Drops rows (or columns) containing nulls from a Column.

Parameters
axis{0, 1}, optional

Whether to drop rows (axis=0, default) or columns (axis=1) containing nulls.

how{“any”, “all”}, optional

Specifies how to decide whether to drop a row (or column). any (default) drops rows (or columns) containing at least one null value. all drops only rows (or columns) containing all null values.

thresh: int, optional

If specified, then drops every row (or column) containing less than thresh non-null values

subsetlist, optional

List of columns to consider when dropping rows (all columns are considered by default). Alternatively, when dropping columns, subset is a list of rows to consider.

inplacebool, default False

If True, do operation inplace and return None.

Returns
Copy of the DataFrame with rows/columns containing nulls dropped.

See also

cudf.core.dataframe.DataFrame.isna

Indicate null values.

cudf.core.dataframe.DataFrame.notna

Indicate non-null values.

cudf.core.dataframe.DataFrame.fillna

Replace null values.

cudf.core.series.Series.dropna

Drop null values.

cudf.core.index.Index.dropna

Drop null indices.

Examples

>>> import cudf
>>> df = cudf.DataFrame({"name": ['Alfred', 'Batman', 'Catwoman'],
...                    "toy": ['Batmobile', None, 'Bullwhip'],
...                    "born": [np.datetime64("1940-04-25"),
...                             np.datetime64("NaT"),
...                             np.datetime64("NaT")]})
>>> df
       name        toy       born
0    Alfred  Batmobile 1940-04-25
1    Batman       None       null
2  Catwoman   Bullwhip       null

Drop the rows where at least one element is null.

>>> df.dropna()
     name        toy       born
0  Alfred  Batmobile 1940-04-25

Drop the columns where at least one element is null.

>>> df.dropna(axis='columns')
       name
0    Alfred
1    Batman
2  Catwoman

Drop the rows where all elements are null.

>>> df.dropna(how='all')
       name        toy       born
0    Alfred  Batmobile 1940-04-25
1    Batman       None       null
2  Catwoman   Bullwhip       null

Keep only the rows with at least 2 non-null values.

>>> df.dropna(thresh=2)
       name        toy       born
0    Alfred  Batmobile 1940-04-25
2  Catwoman   Bullwhip       null

Define in which columns to look for null values.

>>> df.dropna(subset=['name', 'born'])
     name        toy       born
0  Alfred  Batmobile 1940-04-25

Keep the DataFrame with valid entries in the same variable.

>>> df.dropna(inplace=True)
>>> df
     name        toy       born
0  Alfred  Batmobile 1940-04-25
property dtypes

Return the dtypes in this object.

property empty

Indicator whether DataFrame or Series is empty.

True if DataFrame/Series is entirely empty (no items), meaning any of the axes are of length 0.

Returns
outbool

If DataFrame/Series is empty, return True, if not return False.

Notes

If DataFrame/Series contains only null values, it is still not considered empty. See the example below.

Examples

>>> import cudf
>>> df = cudf.DataFrame({'A' : []})
>>> df
Empty DataFrame
Columns: [A]
Index: []
>>> df.empty
True

If we only have null values in our DataFrame, it is not considered empty! We will need to drop the null’s to make the DataFrame empty:

>>> df = cudf.DataFrame({'A' : [None, None]})
>>> df
      A
0  null
1  null
>>> df.empty
False
>>> df.dropna().empty
True

Non-empty and empty Series example:

>>> s = cudf.Series([1, 2, None])
>>> s
0       1
1       2
2    null
dtype: int64
>>> s.empty
False
>>> s = cudf.Series([])
>>> s
Series([], dtype: float64)
>>> s.empty
True
equals(other)

Test whether two objects contain the same elements. This function allows two Series or DataFrames to be compared against each other to see if they have the same shape and elements. NaNs in the same location are considered equal. The column headers do not need to have the same type.

Parameters
otherSeries or DataFrame

The other Series or DataFrame to be compared with the first.

Returns
bool

True if all elements are the same in both objects, False otherwise.

Examples

>>> import cudf

Comparing Series with equals:

>>> s = cudf.Series([1, 2, 3])
>>> other = cudf.Series([1, 2, 3])
>>> s.equals(other)
True
>>> different = cudf.Series([1.5, 2, 3])
>>> s.equals(different)
False

Comparing DataFrames with equals:

>>> df = cudf.DataFrame({1: [10], 2: [20]})
>>> df
    1   2
0  10  20
>>> exactly_equal = cudf.DataFrame({1: [10], 2: [20]})
>>> exactly_equal
    1   2
0  10  20
>>> df.equals(exactly_equal)
True

For two DataFrames to compare equal, the types of column values must be equal, but the types of column labels need not:

>>> different_column_type = cudf.DataFrame({1.0: [10], 2.0: [20]})
>>> different_column_type
   1.0  2.0
0   10   20
>>> df.equals(different_column_type)
True
exp()

Get the exponential of all elements, element-wise.

Exponential is the inverse of the log function, so that x.exp().log() = x

Returns
DataFrame/Series/Index

Result of the element-wise exponential.

Examples

>>> import cudf
>>> ser = cudf.Series([-1, 0, 1, 0.32434, 0.5, -10, 100])
>>> ser
0     -1.00000
1      0.00000
2      1.00000
3      0.32434
4      0.50000
5    -10.00000
6    100.00000
dtype: float64
>>> ser.exp()
0    3.678794e-01
1    1.000000e+00
2    2.718282e+00
3    1.383117e+00
4    1.648721e+00
5    4.539993e-05
6    2.688117e+43
dtype: float64

exp operation on DataFrame:

>>> df = cudf.DataFrame({'first': [-1, -10, 0.5],
...                      'second': [0.234, 0.3, 10]})
>>> df
   first  second
0   -1.0   0.234
1  -10.0   0.300
2    0.5  10.000
>>> df.exp()
      first        second
0  0.367879      1.263644
1  0.000045      1.349859
2  1.648721  22026.465795

exp operation on Index:

>>> index = cudf.Index([-1, 0.4, 1, 0, 0.3])
>>> index
Float64Index([-1.0, 0.4, 1.0, 0.0, 0.3], dtype='float64')
>>> index.exp()
Float64Index([0.36787944117144233,  1.4918246976412703,
              2.718281828459045, 1.0,  1.3498588075760032],
            dtype='float64')
fillna(value, method=None, axis=None, inplace=False, limit=None)

Fill null values with value.

Parameters
valuescalar, Series-like or dict

Value to use to fill nulls. If Series-like, null values are filled with values in corresponding indices. A dict can be used to provide different values to fill nulls in different columns.

Returns
resultDataFrame

Copy with nulls filled.

Examples

>>> import cudf
>>> df = cudf.DataFrame({'a': [1, 2, None], 'b': [3, None, 5]})
>>> df
      a     b
0     1     3
1     2  null
2  null     5
>>> df.fillna(4)
   a  b
0  1  3
1  2  4
2  4  5
>>> df.fillna({'a': 3, 'b': 4})
   a  b
0  1  3
1  2  4
2  3  5

fillna on a Series object:

>>> ser = cudf.Series(['a', 'b', None, 'c'])
>>> ser
0       a
1       b
2    None
3       c
dtype: object
>>> ser.fillna('z')
0    a
1    b
2    z
3    c
dtype: object

fillna can also supports inplace operation:

>>> ser.fillna('z', inplace=True)
>>> ser
0    a
1    b
2    z
3    c
dtype: object
>>> df.fillna({'a': 3, 'b': 4}, inplace=True)
>>> df
a  b
0  1  3
1  2  4
2  3  5
floordiv(other, axis='columns', level=None, fill_value=None)

Get Integer division of dataframe and other, element-wise (binary operator floordiv).

Equivalent to dataframe // other, but with support to substitute a fill_value for missing data in one of the inputs. With reverse version, rfloordiv.

Among flexible wrappers (add, sub, mul, div, mod, pow) to arithmetic operators: +, -, *, /, //, %, **.

Parameters
otherscalar, sequence, Series, or DataFrame

Any single or multiple element data structure, or list-like object.

fill_valuefloat or None, default None

Fill existing missing (NaN) values, and any new element needed for successful DataFrame alignment, with this value before computation. If data in both corresponding DataFrame locations is missing the result will be missing.

Returns
DataFrame

Result of the arithmetic operation.

Examples

>>> import cudf
>>> df = cudf.DataFrame({'angles': [1, 3, 4],
...                    'degrees': [360, 180, 360]},
...                   index=['circle', 'triangle', 'rectangle'])
>>> df.floordiv(2)
        angles  degrees
circle          0      180
triangle        1       90
rectangle       2      180
>>> df // 2
        angles  degrees
circle          0      180
triangle        1       90
rectangle       2      180
classmethod from_arrow(table)

Convert from PyArrow Table to DataFrame.

Parameters
tablePyArrow Table Object

PyArrow Table Object which has to be converted to cudf DataFrame.

Returns
cudf DataFrame
Raises
TypeError for invalid input type.

Notes

  • Does not support automatically setting index column(s) similar to how to_pandas works for PyArrow Tables.

Examples

>>> import cudf
>>> import pyarrow as pa
>>> data = pa.table({"a":[1, 2, 3], "b":[4, 5, 6]})
>>> cudf.DataFrame.from_arrow(data)
   a  b
0  1  4
1  2  5
2  3  6
classmethod from_gpu_matrix(data, index=None, columns=None, nan_as_null=False)

Convert from a numba gpu ndarray.

Parameters
datanumba gpu ndarray
indexstr, Index

The name of the index column in data or an Index itself. If None, the default index is used.

columnslist of str

List of column names to include.

Returns
DataFrame
classmethod from_pandas(dataframe, nan_as_null=None)

Convert from a Pandas DataFrame.

Parameters
dataframePandas DataFrame object

A Pandads DataFrame object which has to be converted to cuDF DataFrame.

nan_as_nullbool, Default True

If True, converts np.nan values to null values. If False, leaves np.nan values as is.

Raises
TypeError for invalid input type.

Examples

>>> import cudf
>>> import pandas as pd
>>> data = [[0,1], [1,2], [3,4]]
>>> pdf = pd.DataFrame(data, columns=['a', 'b'], dtype=int)
>>> cudf.from_pandas(pdf)
   a  b
0  0  1
1  1  2
2  3  4
classmethod from_records(data, index=None, columns=None, nan_as_null=False)

Convert structured or record ndarray to DataFrame.

Parameters
datanumpy structured dtype or recarray of ndim=2
indexstr, array-like

The name of the index column in data. If None, the default index is used.

columnslist of str

List of column names to include.

Returns
DataFrame
groupby(by=None, axis=0, level=None, as_index=True, sort=True, group_keys=True, squeeze=False, observed=False, dropna=True, method=None)

Group DataFrame using a mapper or by a Series of columns.

A groupby operation involves some combination of splitting the object, applying a function, and combining the results. This can be used to group large amounts of data and compute operations on these groups.

Parameters
bymapping, function, label, or list of labels

Used to determine the groups for the groupby. If by is a function, it’s called on each value of the object’s index. If a dict or Series is passed, the Series or dict VALUES will be used to determine the groups (the Series’ values are first aligned; see .align() method). If a cupy array is passed, the values are used as-is determine the groups. A label or list of labels may be passed to group by the columns in self. Notice that a tuple is interpreted as a (single) key.

levelint, level name, or sequence of such, default None

If the axis is a MultiIndex (hierarchical), group by a particular level or levels.

as_indexbool, default True

For aggregated output, return object with group labels as the index. Only relevant for DataFrame input. as_index=False is effectively “SQL-style” grouped output.

sortbool, default True

Sort group keys. Get better performance by turning this off. Note this does not influence the order of observations within each group. Groupby preserves the order of rows within each group.

dropnabool, optional

If True (default), do not include the “null” group.

Returns
DataFrameGroupBy

Returns a groupby object that contains information about the groups.

Examples

>>> import cudf
>>> import pandas as pd
>>> df = cudf.DataFrame({'Animal': ['Falcon', 'Falcon',
...                               'Parrot', 'Parrot'],
...                    'Max Speed': [380., 370., 24., 26.]})
>>> df
Animal  Max Speed
0  Falcon      380.0
1  Falcon      370.0
2  Parrot       24.0
3  Parrot       26.0
>>> df.groupby(['Animal']).mean()
        Max Speed
Animal
Falcon      375.0
Parrot       25.0
>>> arrays = [['Falcon', 'Falcon', 'Parrot', 'Parrot'],
... ['Captive', 'Wild', 'Captive', 'Wild']]
>>> index = pd.MultiIndex.from_arrays(arrays, names=('Animal', 'Type'))
>>> df = cudf.DataFrame({'Max Speed': [390., 350., 30., 20.]},
        index=index)
>>> df
                Max Speed
Animal Type
Falcon Captive      390.0
    Wild         350.0
Parrot Captive       30.0
    Wild          20.0
>>> df.groupby(level=0).mean()
        Max Speed
Animal
Falcon      370.0
Parrot       25.0
>>> df.groupby(level="Type").mean()
        Max Speed
Type
Captive      210.0
Wild         185.0
hash_columns(columns=None)

Hash the given columns and return a new device array

Parameters
columnssequence of str; optional

Sequence of column names. If columns is None (unspecified), all columns in the frame are used.

head(n=5)

Returns the first n rows as a new DataFrame

Examples

>>> import cudf
>>> df = cudf.DataFrame()
>>> df['key'] = [0, 1, 2, 3, 4]
>>> df['val'] = [float(i + 10) for i in range(5)]  # insert column
>>> print(df.head(2))
   key   val
0    0  10.0
1    1  11.0
property iat

Alias for DataFrame.iloc; provided for compatibility with Pandas.

property iloc

Selecting rows and column by position.

See also

DataFrame.loc

Notes

One notable difference from Pandas is when DataFrame is of mixed types and result is expected to be a Series in case of Pandas. cuDF will return a DataFrame as it doesn’t support mixed types under Series yet.

Mixed dtype single row output as a dataframe (pandas results in Series)

>>> import cudf
>>> df = cudf.DataFrame({"a":[1, 2, 3], "b":["a", "b", "c"]})
>>> df.iloc[0]
   a  b
0  1  a

Examples

>>> df = cudf.DataFrame({'a': range(20),
...                      'b': range(20),
...                      'c': range(20)})

Select a single row using an integer index.

>>> print(df.iloc[1])
a    1
b    1
c    1

Select multiple rows using a list of integers.

>>> print(df.iloc[[0, 2, 9, 18]])
      a    b    c
 0    0    0    0
 2    2    2    2
 9    9    9    9
18   18   18   18

Select rows using a slice.

>>> print(df.iloc[3:10:2])
     a    b    c
3    3    3    3
5    5    5    5
7    7    7    7
9    9    9    9

Select both rows and columns.

>>> print(df.iloc[[1, 3, 5, 7], 2])
1    1
3    3
5    5
7    7
Name: c, dtype: int64

Setting values in a column using iloc.

>>> df.iloc[:4] = 0
>>> print(df)
   a  b  c
0  0  0  0
1  0  0  0
2  0  0  0
3  0  0  0
4  4  4  4
5  5  5  5
6  6  6  6
7  7  7  7
8  8  8  8
9  9  9  9
[10 more rows]
property index

Returns the index of the DataFrame

info(verbose=None, buf=None, max_cols=None, memory_usage=None, null_counts=None)

Print a concise summary of a DataFrame.

This method prints information about a DataFrame including the index dtype and column dtypes, non-null values and memory usage.

Parameters
verbosebool, optional

Whether to print the full summary. By default, the setting in pandas.options.display.max_info_columns is followed.

bufwritable buffer, defaults to sys.stdout

Where to send the output. By default, the output is printed to sys.stdout. Pass a writable buffer if you need to further process the output.

max_colsint, optional

When to switch from the verbose to the truncated output. If the DataFrame has more than max_cols columns, the truncated output is used. By default, the setting in pandas.options.display.max_info_columns is used.

memory_usagebool, str, optional

Specifies whether total memory usage of the DataFrame elements (including the index) should be displayed. By default, this follows the pandas.options.display.memory_usage setting. True always show memory usage. False never shows memory usage. A value of ‘deep’ is equivalent to “True with deep introspection”. Memory usage is shown in human-readable units (base-2 representation). Without deep introspection a memory estimation is made based in column dtype and number of rows assuming values consume the same memory amount for corresponding dtypes. With deep memory introspection, a real memory usage calculation is performed at the cost of computational resources.

null_countsbool, optional

Whether to show the non-null counts. By default, this is shown only if the frame is smaller than pandas.options.display.max_info_rows and pandas.options.display.max_info_columns. A value of True always shows the counts, and False never shows the counts.

Returns
None

This method prints a summary of a DataFrame and returns None.

See also

DataFrame.describe

Generate descriptive statistics of DataFrame columns.

DataFrame.memory_usage

Memory usage of DataFrame columns.

Examples

>>> import cudf
>>> int_values = [1, 2, 3, 4, 5]
>>> text_values = ['alpha', 'beta', 'gamma', 'delta', 'epsilon']
>>> float_values = [0.0, 0.25, 0.5, 0.75, 1.0]
>>> df = cudf.DataFrame({"int_col": int_values,
...                     "text_col": text_values,
...                     "float_col": float_values})
>>> df
   int_col text_col  float_col
0        1    alpha       0.00
1        2     beta       0.25
2        3    gamma       0.50
3        4    delta       0.75
4        5  epsilon       1.00

Prints information of all columns:

>>> df.info(verbose=True)
<class 'cudf.core.dataframe.DataFrame'>
RangeIndex: 5 entries, 0 to 4
Data columns (total 3 columns):
 #   Column     Non-Null Count  Dtype
---  ------     --------------  -----
 0   int_col    5 non-null      int64
 1   text_col   5 non-null      object
 2   float_col  5 non-null      float64
dtypes: float64(1), int64(1), object(1)
memory usage: 130.0+ bytes

Prints a summary of columns count and its dtypes but not per column information:

>>> df.info(verbose=False)
<class 'cudf.core.dataframe.DataFrame'>
RangeIndex: 5 entries, 0 to 4
Columns: 3 entries, int_col to float_col
dtypes: float64(1), int64(1), object(1)
memory usage: 130.0+ bytes

Pipe output of DataFrame.info to buffer instead of sys.stdout, get buffer content and writes to a text file:

>>> import io
>>> buffer = io.StringIO()
>>> df.info(buf=buffer)
>>> s = buffer.getvalue()
>>> with open("df_info.txt", "w",
...           encoding="utf-8") as f:
...     f.write(s)
...
369

The memory_usage parameter allows deep introspection mode, specially useful for big DataFrames and fine-tune memory optimization:

>>> import numpy as np
>>> random_strings_array = np.random.choice(['a', 'b', 'c'], 10 ** 6)
>>> df = cudf.DataFrame({
...     'column_1': np.random.choice(['a', 'b', 'c'], 10 ** 6),
...     'column_2': np.random.choice(['a', 'b', 'c'], 10 ** 6),
...     'column_3': np.random.choice(['a', 'b', 'c'], 10 ** 6)
... })
>>> df.info(memory_usage='deep')
<class 'cudf.core.dataframe.DataFrame'>
RangeIndex: 1000000 entries, 0 to 999999
Data columns (total 3 columns):
 #   Column    Non-Null Count    Dtype
---  ------    --------------    -----
 0   column_1  1000000 non-null  object
 1   column_2  1000000 non-null  object
 2   column_3  1000000 non-null  object
dtypes: object(3)
memory usage: 14.3 MB
insert(loc, name, value)

Add a column to DataFrame at the index specified by loc.

Parameters
locint

location to insert by index, cannot be greater then num columns + 1

namenumber or string

name or label of column to be inserted

valueSeries or array-like
interleave_columns()

Interleave Series columns of a table into a single column.

Converts the column major table cols into a row major column.

Parameters
colsinput Table containing columns to interleave.
Returns
The interleaved columns as a single column

Examples

>>> df = DataFrame([['A1', 'A2', 'A3'], ['B1', 'B2', 'B3']])
>>> df
0    [A1, A2, A3]
1    [B1, B2, B3]
>>> df.interleave_columns()
0    A1
1    B1
2    A2
3    B2
4    A3
5    B3
isin(values)

Whether each element in the DataFrame is contained in values.

Parameters
valuesiterable, Series, DataFrame or dict

The result will only be true at a location if all the labels match. If values is a Series, that’s the index. If values is a dict, the keys must be the column names, which must match. If values is a DataFrame, then both the index and column labels must match.

Returns
DataFrame:

DataFrame of booleans showing whether each element in the DataFrame is contained in values.

isna()

Identify missing values. Alias for isnull

isnull()

Identify missing values.

iteritems()

Iterate over column names and series pairs

join(other, on=None, how='left', lsuffix='', rsuffix='', sort=False, type='', method='hash')

Join columns with other DataFrame on index or on a key column.

Parameters
otherDataFrame
howstr

Only accepts “left”, “right”, “inner”, “outer”

lsuffix, rsuffixstr

The suffices to add to the left (lsuffix) and right (rsuffix) column names when avoiding conflicts.

sortbool

Set to True to ensure sorted ordering.

Returns
joinedDataFrame

Notes

Difference from pandas:

  • other must be a single DataFrame for now.

  • on is not supported yet due to lack of multi-index support.

keys()

Get the columns. This is index for Series, columns for DataFrame.

Returns
Index

Columns of DataFrame.

Examples

>>> import cudf
>>> df = cudf.DataFrame({'one' : [1, 2, 3], 'five' : ['a', 'b', 'c']})
>>> df
   one five
0    1    a
1    2    b
2    3    c
>>> df.keys()
Index(['one', 'five'], dtype='object')
>>> df = cudf.DataFrame(columns=[0, 1, 2, 3])
>>> df
Empty DataFrame
Columns: [0, 1, 2, 3]
Index: []
>>> df.keys()
Int64Index([0, 1, 2, 3], dtype='int64')
kurt(axis=None, skipna=None, level=None, numeric_only=None, **kwargs)

Return Fisher’s unbiased kurtosis of a sample.

Kurtosis obtained using Fisher’s definition of kurtosis (kurtosis of normal == 0.0). Normalized by N-1.

Parameters
skipna: bool, default True

Exclude NA/null values when computing the result.

Returns
Series

Notes

Parameters currently not supported are axis, level and numeric_only

Examples

>>> import cudf
>>> df = cudf.DataFrame({'a': [1, 2, 3, 4], 'b': [7, 8, 9, 10]})
>>> df.kurt()
a   -1.2
b   -1.2
dtype: float64
kurtosis(axis=None, skipna=None, level=None, numeric_only=None, **kwargs)

Return Fisher’s unbiased kurtosis of a sample.

Kurtosis obtained using Fisher’s definition of kurtosis (kurtosis of normal == 0.0). Normalized by N-1.

Parameters
skipna: bool, default True

Exclude NA/null values when computing the result.

Returns
Series

Notes

Parameters currently not supported are axis, level and numeric_only

Examples

>>> import cudf
>>> df = cudf.DataFrame({'a': [1, 2, 3, 4], 'b': [7, 8, 9, 10]})
>>> df.kurt()
a   -1.2
b   -1.2
dtype: float64
label_encoding(column, prefix, cats, prefix_sep='_', dtype=None, na_sentinel=- 1)

Encode labels in a column with label encoding.

Parameters
columnstr

the source column with binary encoding for the data.

prefixstr

the new column name prefix.

catssequence of ints

the sequence of categories as integers.

prefix_sepstr

the separator between the prefix and the category.

dtype :

the dtype for the outputs; see Series.label_encoding

na_sentinelnumber

Value to indicate missing category.

Returns
a new dataframe with a new column append for the coded values.
property loc

Selecting rows and columns by label or boolean mask.

See also

DataFrame.iloc

Notes

One notable difference from Pandas is when DataFrame is of mixed types and result is expected to be a Series in case of Pandas. cuDF will return a DataFrame as it doesn’t support mixed types under Series yet.

Mixed dtype single row output as a dataframe (pandas results in Series)

>>> import cudf
>>> df = cudf.DataFrame({"a":[1, 2, 3], "b":["a", "b", "c"]})
>>> df.loc[0]
   a  b
0  1  a

Examples

DataFrame with string index.

>>> print(df)
   a  b
a  0  5
b  1  6
c  2  7
d  3  8
e  4  9

Select a single row by label.

>>> print(df.loc['a'])
a    0
b    5
Name: a, dtype: int64

Select multiple rows and a single column.

>>> print(df.loc[['a', 'c', 'e'], 'b'])
a    5
c    7
e    9
Name: b, dtype: int64

Selection by boolean mask.

>>> print(df.loc[df.a > 2])
   a  b
d  3  8
e  4  9

Setting values using loc.

>>> df.loc[['a', 'c', 'e'], 'a'] = 0
>>> print(df)
   a  b
a  0  5
b  1  6
c  0  7
d  3  8
e  0  9
log()

Get the natural logarithm of all elements, element-wise.

Natural logarithm is the inverse of the exp function, so that x.log().exp() = x

Returns
DataFrame/Series/Index

Result of the element-wise natural logarithm.

Examples

>>> import cudf
>>> ser = cudf.Series([-1, 0, 1, 0.32434, 0.5, -10, 100])
>>> ser
0     -1.00000
1      0.00000
2      1.00000
3      0.32434
4      0.50000
5    -10.00000
6    100.00000
dtype: float64
>>> ser.log()
0         NaN
1        -inf
2    0.000000
3   -1.125963
4   -0.693147
5         NaN
6    4.605170
dtype: float64

log operation on DataFrame:

>>> df = cudf.DataFrame({'first': [-1, -10, 0.5],
...                      'second': [0.234, 0.3, 10]})
>>> df
   first  second
0   -1.0   0.234
1  -10.0   0.300
2    0.5  10.000
>>> df.log()
      first    second
0       NaN -1.452434
1       NaN -1.203973
2 -0.693147  2.302585

log operation on Index:

>>> index = cudf.Index([10, 11, 500.0])
>>> index
Float64Index([10.0, 11.0, 500.0], dtype='float64')
>>> index.log()
Float64Index([2.302585092994046, 2.3978952727983707,
            6.214608098422191], dtype='float64')
mask(cond, other=None, inplace=False)

Replace values where the condition is True.

Parameters
condbool Series/DataFrame, array-like

Where cond is False, keep the original value. Where True, replace with corresponding value from other. Callables are not supported.

other: scalar, list of scalars, Series/DataFrame

Entries where cond is True are replaced with corresponding value from other. Callables are not supported. Default is None.

DataFrame expects only Scalar or array like with scalars or dataframe with same dimension as self.

Series expects only scalar or series like with same length

inplacebool, default False

Whether to perform the operation in place on the data.

Returns
Same type as caller

Examples

>>> import cudf
>>> df = cudf.DataFrame({"A":[1, 4, 5], "B":[3, 5, 8]})
>>> df.mask(df % 2 == 0, [-1, -1])
   A  B
0  1  3
1 -1  5
2  5 -1
>>> ser = cudf.Series([4, 3, 2, 1, 0])
>>> ser.mask(ser > 2, 10)
0    10
1    10
2     2
3     1
4     0
dtype: int64
>>> ser.mask(ser > 2)
0    null
1    null
2       2
3       1
4       0
dtype: int64
max(axis=None, skipna=None, level=None, numeric_only=None, **kwargs)

Return the maximum of the values in the DataFrame.

Parameters
axis: {index (0), columns(1)}

Axis for the function to be applied on.

skipna: bool, default True

Exclude NA/null values when computing the result.

level: int or level name, default None

If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a Series.

numeric_only: bool, default None

Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data.

Returns
Series

Notes

Parameters currently not supported are level, numeric_only.

Examples

>>> import cudf
>>> df = cudf.DataFrame({'a': [1, 2, 3, 4], 'b': [7, 8, 9, 10]})
>>> df.max()
a     4
b    10
dtype: int64
mean(axis=None, skipna=None, level=None, numeric_only=None, **kwargs)

Return the mean of the values for the requested axis.

Parameters
axis{0 or ‘index’, 1 or ‘columns’}

Axis for the function to be applied on.

skipnabool, default True

Exclude NA/null values when computing the result.

levelint or level name, default None

If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a Series.

numeric_onlybool, default None

Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data. Not implemented for Series.

**kwargs

Additional keyword arguments to be passed to the function.

Returns
meanSeries or DataFrame (if level specified)

Examples

>>> import cudf
>>> df = cudf.DataFrame({'a': [1, 2, 3, 4], 'b': [7, 8, 9, 10]})
>>> df.mean()
a    2.5
b    8.5
dtype: float64
melt(**kwargs)

Unpivots a DataFrame from wide format to long format, optionally leaving identifier variables set.

Parameters
frameDataFrame
id_varstuple, list, or ndarray, optional

Column(s) to use as identifier variables. default: None

value_varstuple, list, or ndarray, optional

Column(s) to unpivot. default: all columns that are not set as id_vars.

var_namescalar

Name to use for the variable column. default: frame.columns.name or ‘variable’

value_namestr

Name to use for the value column. default: ‘value’

Returns
outDataFrame

Melted result

memory_usage(index=True, deep=False)

Return the memory usage of each column in bytes. The memory usage can optionally include the contribution of the index and elements of object dtype.

Parameters
indexbool, default True

Specifies whether to include the memory usage of the DataFrame’s index in returned Series. If index=True, the memory usage of the index is the first item in the output.

deepbool, default False

If True, introspect the data deeply by interrogating object dtypes for system-level memory consumption, and include it in the returned values.

Returns
Series

A Series whose index is the original column names and whose values is the memory usage of each column in bytes.

Examples

>>> dtypes = ['int64', 'float64', 'object', 'bool']
>>> data = dict([(t, np.ones(shape=5000).astype(t))
...              for t in dtypes])
>>> df = cudf.DataFrame(data)
>>> df.head()
    int64  float64  object  bool
0      1      1.0     1.0  True
1      1      1.0     1.0  True
2      1      1.0     1.0  True
3      1      1.0     1.0  True
4      1      1.0     1.0  True
>>> df.memory_usage(index=False)
int64      40000
float64    40000
object     40000
bool        5000
dtype: int64
Use a Categorical for efficient storage of an object-dtype column with
many repeated values.
>>> df['object'].astype('category').memory_usage(deep=True)
5048
merge(right, on=None, left_on=None, right_on=None, left_index=False, right_index=False, how='inner', sort=False, lsuffix=None, rsuffix=None, type='', method='hash', indicator=False, suffixes='_x', '_y')

Merge GPU DataFrame objects by performing a database-style join operation by columns or indexes.

Parameters
rightDataFrame
onlabel or list; defaults to None

Column or index level names to join on. These must be found in both DataFrames.

If on is None and not merging on indexes then this defaults to the intersection of the columns in both DataFrames.

how{‘left’, ‘outer’, ‘inner’}, default ‘inner’

Type of merge to be performed.

  • left : use only keys from left frame, similar to a SQL left outer join.

  • right : not supported.

  • outer : use union of keys from both frames, similar to a SQL full outer join.

  • inner: use intersection of keys from both frames, similar to a SQL inner join.

left_onlabel or list, or array-like

Column or index level names to join on in the left DataFrame. Can also be an array or list of arrays of the length of the left DataFrame. These arrays are treated as if they are columns.

right_onlabel or list, or array-like

Column or index level names to join on in the right DataFrame. Can also be an array or list of arrays of the length of the right DataFrame. These arrays are treated as if they are columns.

left_indexbool, default False

Use the index from the left DataFrame as the join key(s).

right_indexbool, default False

Use the index from the right DataFrame as the join key.

sortbool, default False

Sort the resulting dataframe by the columns that were merged on, starting from the left.

suffixes: Tuple[str, str], defaults to (‘_x’, ‘_y’)

Suffixes applied to overlapping column names on the left and right sides

method{‘hash’, ‘sort’}, default ‘hash’

The implementation method to be used for the operation.

Returns
mergedDataFrame

Notes

DataFrames merges in cuDF result in non-deterministic row ordering.

Examples

>>> import cudf
>>> df_a = cudf.DataFrame()
>>> df_a['key'] = [0, 1, 2, 3, 4]
>>> df_a['vals_a'] = [float(i + 10) for i in range(5)]
>>> df_b = cudf.DataFrame()
>>> df_b['key'] = [1, 2, 4]
>>> df_b['vals_b'] = [float(i+10) for i in range(3)]
>>> df_merged = df_a.merge(df_b, on=['key'], how='left')
>>> df_merged.sort_values('key')  
   key  vals_a  vals_b
3    0    10.0
0    1    11.0    10.0
1    2    12.0    11.0
4    3    13.0
2    4    14.0    12.0
min(axis=None, skipna=None, level=None, numeric_only=None, **kwargs)

Return the minimum of the values in the DataFrame.

Parameters
axis: {index (0), columns(1)}

Axis for the function to be applied on.

skipna: bool, default True

Exclude NA/null values when computing the result.

level: int or level name, default None

If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a Series.

numeric_only: bool, default None

Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data.

Returns
Series

Notes

Parameters currently not supported are level, numeric_only.

Examples

>>> import cudf
>>> df = cudf.DataFrame({'a': [1, 2, 3, 4], 'b': [7, 8, 9, 10]})
>>> df.min()
a    1
b    7
dtype: int64
mod(other, axis='columns', level=None, fill_value=None)

Get Modulo division of dataframe and other, element-wise (binary operator mod).

Equivalent to dataframe % other, but with support to substitute a fill_value for missing data in one of the inputs. With reverse version, rmod.

Among flexible wrappers (add, sub, mul, div, mod, pow) to arithmetic operators: +, -, *, /, //, %, **.

Parameters
otherscalar, sequence, Series, or DataFrame

Any single or multiple element data structure, or list-like object.

fill_valuefloat or None, default None

Fill existing missing (NaN) values, and any new element needed for successful DataFrame alignment, with this value before computation. If data in both corresponding DataFrame locations is missing the result will be missing.

Returns
DataFrame

Result of the arithmetic operation.

Examples

>>> import cudf
>>> df = cudf.DataFrame({'angles': [0, 3, 4],
...                    'degrees': [360, 180, 360]},
...                   index=['circle', 'triangle', 'rectangle'])
>>> df % 100
        angles  degrees
circle          0       60
triangle        3       80
rectangle       4       60
>>> df.mod(100)
        angles  degrees
circle          0       60
triangle        3       80
rectangle       4       60
mode(axis=0, numeric_only=False, dropna=True)

Get the mode(s) of each element along the selected axis.

The mode of a set of values is the value that appears most often. It can be multiple values.

Parameters
axis{0 or ‘index’, 1 or ‘columns’}, default 0

The axis to iterate over while searching for the mode:

  • 0 or ‘index’ : get mode of each column

  • 1 or ‘columns’ : get mode of each row.

numeric_onlybool, default False

If True, only apply to numeric columns.

dropnabool, default True

Don’t consider counts of NA/NaN/NaT.

Returns
DataFrame

The modes of each column or row.

See also

cudf.core.series.Series.mode

Return the highest frequency value in a Series.

cudf.core.series.Series.value_counts

Return the counts of values in a Series.

Notes

axis parameter is currently not supported.

Examples

>>> import cudf
>>> df = cudf.DataFrame({
...     "species": ["bird", "mammal", "arthropod", "bird"],
...     "legs": [2, 4, 8, 2],
...     "wings": [2.0, None, 0.0, None]
... })
>>> df
     species  legs wings
0       bird     2   2.0
1     mammal     4  <NA>
2  arthropod     8   0.0
3       bird     2  <NA>

By default, missing values are not considered, and the mode of wings are both 0 and 2. The second row of species and legs contains NA, because they have only one mode, but the DataFrame has two rows.

>>> df.mode()
  species  legs  wings
0    bird     2    0.0
1    <NA>  <NA>    2.0

Setting dropna=False, NA values are considered and they can be the mode (like for wings).

>>> df.mode(dropna=False)
  species  legs wings
0    bird     2  <NA>

Setting numeric_only=True, only the mode of numeric columns is computed, and columns of other types are ignored.

>>> df.mode(numeric_only=True)
   legs  wings
0     2    0.0
1  <NA>    2.0
mul(other, axis='columns', level=None, fill_value=None)

Get Multiplication of dataframe and other, element-wise (binary operator mul).

Equivalent to dataframe * other, but with support to substitute a fill_value for missing data in one of the inputs. With reverse version, rmul.

Among flexible wrappers (add, sub, mul, div, mod, pow) to arithmetic operators: +, -, *, /, //, %, **.

Parameters
otherscalar, sequence, Series, or DataFrame

Any single or multiple element data structure, or list-like object.

fill_valuefloat or None, default None

Fill existing missing (NaN) values, and any new element needed for successful DataFrame alignment, with this value before computation. If data in both corresponding DataFrame locations is missing the result will be missing.

Returns
DataFrame

Result of the arithmetic operation.

Examples

>>> import cudf
>>> df = cudf.DataFrame({'angles': [0, 3, 4],
...                    'degrees': [360, 180, 360]},
...                   index=['circle', 'triangle', 'rectangle'])
>>> other = pd.DataFrame({'angles': [0, 3, 4]},
...                      index=['circle', 'triangle', 'rectangle'])
>>> df * other
        angles degrees
circle          0    null
triangle        9    null
rectangle      16    null
>>> df.mul(other, fill_value=0)
        angles  degrees
circle          0        0
triangle        9        0
rectangle      16        0
nans_to_nulls()

Convert nans (if any) to nulls.

property ndim

Dimension of the data. DataFrame ndim is always 2.

nlargest(n, columns, keep='first')

Get the rows of the DataFrame sorted by the n largest value of columns

Notes

Difference from pandas:
  • Only a single column is supported in columns

notna()

Identify non-missing values. Alias for notnull.

notnull()

Identify non-missing values.

nsmallest(n, columns, keep='first')

Get the rows of the DataFrame sorted by the n smallest value of columns

Notes

Difference from pandas:
  • Only a single column is supported in columns

one_hot_encoding(column, prefix, cats, prefix_sep='_', dtype='float64')

Expand a column with one-hot-encoding.

Parameters
columnstr

the source column with binary encoding for the data.

prefixstr

the new column name prefix.

catssequence of ints

the sequence of categories as integers.

prefix_sepstr

the separator between the prefix and the category.

dtype :

the dtype for the outputs; defaults to float64.

Returns
a new dataframe with new columns append for each category.

Examples

>>> import pandas as pd
>>> import cudf
>>> pet_owner = [1, 2, 3, 4, 5]
>>> pet_type = ['fish', 'dog', 'fish', 'bird', 'fish']
>>> df = pd.DataFrame({'pet_owner': pet_owner, 'pet_type': pet_type})
>>> df.pet_type = df.pet_type.astype('category')

Create a column with numerically encoded category values

>>> df['pet_codes'] = df.pet_type.cat.codes
>>> gdf = cudf.from_pandas(df)

Create the list of category codes to use in the encoding

>>> codes = gdf.pet_codes.unique()
>>> gdf.one_hot_encoding('pet_codes', 'pet_dummy', codes).head()
  pet_owner  pet_type  pet_codes  pet_dummy_0  pet_dummy_1  pet_dummy_2
0         1      fish          2          0.0          0.0          1.0
1         2       dog          1          0.0          1.0          0.0
2         3      fish          2          0.0          0.0          1.0
3         4      bird          0          1.0          0.0          0.0
4         5      fish          2          0.0          0.0          1.0
partition_by_hash(columns, nparts, keep_index=True)

Partition the dataframe by the hashed value of data in columns.

Parameters
columnssequence of str

The names of the columns to be hashed. Must have at least one name.

npartsint

Number of output partitions

keep_indexboolean

Whether to keep the index or drop it

Returns
partitioned: list of DataFrame
pivot(index, columns, values=None)

Return reshaped DataFrame organized by the given index and column values.

Reshape data (produce a “pivot” table) based on column values. Uses unique values from specified index / columns to form axes of the resulting DataFrame.

Parameters
indexcolumn name, optional

Column used to construct the index of the result.

columnscolumn name, optional

Column used to construct the columns of the result.

valuescolumn name or list of column names, optional

Column(s) whose values are rearranged to produce the result. If not specified, all remaining columns of the DataFrame are used.

Returns
DataFrame

Examples

>>> a = cudf.DataFrame()
>>> a['a'] = [1, 1, 2, 2],
>>> a['b'] = ['a', 'b', 'a', 'b']
>>> a['c'] = [1, 2, 3, 4]
>>> a.pivot(index='a', columns='b')
   c
b  a  b
a
1  1  2
2  3  4

Pivot with missing values in result:

>>> a = cudf.DataFrame()
>>> a['a'] = [1, 1, 2]
>>> a['b'] = [1, 2, 3]
>>> a['c'] = ['one', 'two', 'three']
>>> a.pivot(index='a', columns='b')
          c
    b     1     2      3
    a
    1   one   two   <NA>
    2  <NA>  <NA>  three
pop(item)

Return a column and drop it from the DataFrame.

pow(other, axis='columns', level=None, fill_value=None)

Get Exponential power of dataframe and other, element-wise (binary operator pow).

Equivalent to dataframe ** other, but with support to substitute a fill_value for missing data in one of the inputs. With reverse version, rpow.

Among flexible wrappers (add, sub, mul, div, mod, pow) to arithmetic operators: +, -, *, /, //, %, **.

Parameters
otherscalar, sequence, Series, or DataFrame

Any single or multiple element data structure, or list-like object.

fill_valuefloat or None, default None

Fill existing missing (NaN) values, and any new element needed for successful DataFrame alignment, with this value before computation. If data in both corresponding DataFrame locations is missing the result will be missing.

Returns
DataFrame

Result of the arithmetic operation.

Examples

>>> import cudf
>>> df = cudf.DataFrame({'angles': [1, 3, 4],
...                    'degrees': [360, 180, 360]},
...                   index=['circle', 'triangle', 'rectangle'])
>>> df ** 2
        angles  degrees
circle          0   129600
triangle        9    32400
rectangle      16   129600
>>> df.pow(2)
        angles  degrees
circle          0   129600
triangle        9    32400
rectangle      16   129600
prod(axis=None, skipna=None, dtype=None, level=None, numeric_only=None, min_count=0, **kwargs)

Return product of the values in the DataFrame.

Parameters
axis: {index (0), columns(1)}

Axis for the function to be applied on.

skipna: bool, default True

Exclude NA/null values when computing the result.

dtype: data type

Data type to cast the result to.

min_count: int, default 0

The required number of valid values to perform the operation. If fewer than min_count non-NA values are present the result will be NA.

The default being 0. This means the sum of an all-NA or empty Series is 0, and the product of an all-NA or empty Series is 1.

Returns
scalar

Notes

Parameters currently not supported are level, numeric_only.

Examples

>>> import cudf
>>> df = cudf.DataFrame({'a': [1, 2, 3, 4], 'b': [7, 8, 9, 10]})
>>> df.prod()
a      24
b    5040
dtype: int64
product(axis=None, skipna=None, dtype=None, level=None, numeric_only=None, min_count=0, **kwargs)

Return product of the values in the DataFrame.

Parameters
axis: {index (0), columns(1)}

Axis for the function to be applied on.

skipna: bool, default True

Exclude NA/null values when computing the result.

dtype: data type

Data type to cast the result to.

min_count: int, default 0

The required number of valid values to perform the operation. If fewer than min_count non-NA values are present the result will be NA.

The default being 0. This means the sum of an all-NA or empty Series is 0, and the product of an all-NA or empty Series is 1.

Returns
Series

Notes

Parameters currently not supported are level`, numeric_only.

Examples

>>> import cudf
>>> df = cudf.DataFrame({'a': [1, 2, 3, 4], 'b': [7, 8, 9, 10]})
>>> df.product()
a      24
b    5040
dtype: int64
quantile(q=0.5, axis=0, numeric_only=True, interpolation='linear', columns=None, exact=True)

Return values at the given quantile.

Parameters
qfloat or array-like

0 <= q <= 1, the quantile(s) to compute

axisint

axis is a NON-FUNCTIONAL parameter

numeric_onlyboolean

numeric_only is a NON-FUNCTIONAL parameter

interpolation{linear, lower, higher, midpoint, nearest}

This parameter specifies the interpolation method to use, when the desired quantile lies between two data points i and j. Default linear.

columnslist of str

List of column names to include.

exactboolean

Whether to use approximate or exact quantile algorithm.

Returns
DataFrame
quantiles(q=0.5, interpolation='nearest')

Return values at the given quantile.

Parameters
qfloat or array-like

0 <= q <= 1, the quantile(s) to compute

interpolation{lower, higher, nearest}

This parameter specifies the interpolation method to use, when the desired quantile lies between two data points i and j. Default ‘nearest’.

Returns
DataFrame
query(expr, local_dict={})

Query with a boolean expression using Numba to compile a GPU kernel.

See pandas.DataFrame.query.

Parameters
exprstr

A boolean expression. Names in expression refer to columns. index can be used instead of index name, but this is not supported for MultiIndex.

Names starting with @ refer to Python variables.

An output value will be null if any of the input values are null regardless of expression.

local_dictdict

Containing the local variable to be used in query.

Returns
filteredDataFrame

Examples

>>> import cudf
>>> a = ('a', [1, 2, 2])
>>> b = ('b', [3, 4, 5])
>>> df = cudf.DataFrame([a, b])
>>> expr = "(a == 2 and b == 4) or (b == 3)"
>>> print(df.query(expr))
   a  b
0  1  3
1  2  4

DateTime conditionals:

>>> import numpy as np
>>> import datetime
>>> df = cudf.DataFrame()
>>> data = np.array(['2018-10-07', '2018-10-08'], dtype='datetime64')
>>> df['datetimes'] = data
>>> search_date = datetime.datetime.strptime('2018-10-08', '%Y-%m-%d')
>>> print(df.query('datetimes==@search_date'))
                datetimes
1 2018-10-08T00:00:00.000

Using local_dict:

>>> import numpy as np
>>> import datetime
>>> df = cudf.DataFrame()
>>> data = np.array(['2018-10-07', '2018-10-08'], dtype='datetime64')
>>> df['datetimes'] = data
>>> search_date2 = datetime.datetime.strptime('2018-10-08', '%Y-%m-%d')
>>> print(df.query('datetimes==@search_date',
>>>         local_dict={'search_date':search_date2}))
                datetimes
1 2018-10-08T00:00:00.000
radd(other, axis=1, level=None, fill_value=None)

Get Addition of dataframe and other, element-wise (binary operator radd).

Equivalent to other + dataframe, but with support to substitute a fill_value for missing data in one of the inputs. With reverse version, add.

Among flexible wrappers (add, sub, mul, div, mod, pow) to arithmetic operators: +, -, *, /, //, %, **.

Parameters
otherscalar, sequence, Series, or DataFrame

Any single or multiple element data structure, or list-like object.

fill_valuefloat or None, default None

Fill existing missing (NaN) values, and any new element needed for successful DataFrame alignment, with this value before computation. If data in both corresponding DataFrame locations is missing the result will be missing.

Returns
DataFrame

Result of the arithmetic operation.

Examples

>>> import cudf
>>> df = cudf.DataFrame({'angles': [0, 3, 4],
...                    'degrees': [360, 180, 360]},
...                   index=['circle', 'triangle', 'rectangle'])
>>> df + 1
        angles  degrees
circle          1      361
triangle        4      181
rectangle       5      361
>>> df.radd(1)
        angles  degrees
circle          1      361
triangle        4      181
rectangle       5      361
rank(axis=0, method='average', numeric_only=None, na_option='keep', ascending=True, pct=False)

Compute numerical data ranks (1 through n) along axis. By default, equal values are assigned a rank that is the average of the ranks of those values.

Parameters
axis{0 or ‘index’, 1 or ‘columns’}, default 0

Index to direct ranking.

method{‘average’, ‘min’, ‘max’, ‘first’, ‘dense’}, default ‘average’

How to rank the group of records that have the same value (i.e. ties): * average: average rank of the group * min: lowest rank in the group * max: highest rank in the group * first: ranks assigned in order they appear in the array * dense: like ‘min’, but rank always increases by 1 between groups.

numeric_onlybool, optional

For DataFrame objects, rank only numeric columns if set to True.

na_option{‘keep’, ‘top’, ‘bottom’}, default ‘keep’

How to rank NaN values: * keep: assign NaN rank to NaN values * top: assign smallest rank to NaN values if ascending * bottom: assign highest rank to NaN values if ascending.

ascendingbool, default True

Whether or not the elements should be ranked in ascending order.

pctbool, default False

Whether or not to display the returned rankings in percentile form.

Returns
same type as caller

Return a Series or DataFrame with data ranks as values.

rdiv(other, axis='columns', level=None, fill_value=None)

Get Floating division of dataframe and other, element-wise (binary operator rtruediv).

Equivalent to other / dataframe, but with support to substitute a fill_value for missing data in one of the inputs. With reverse version, truediv.

Among flexible wrappers (add, sub, mul, div, mod, pow) to arithmetic operators: +, -, *, /, //, %, **.

Parameters
otherscalar, sequence, Series, or DataFrame

Any single or multiple element data structure, or list-like object.

fill_valuefloat or None, default None

Fill existing missing (NaN) values, and any new element needed for successful DataFrame alignment, with this value before computation. If data in both corresponding DataFrame locations is missing the result will be missing.

Returns
DataFrame

Result of the arithmetic operation.

Examples

>>> import cudf
>>> df = cudf.DataFrame({'angles': [0, 3, 4],
...                    'degrees': [360, 180, 360]},
...                   index=['circle', 'triangle', 'rectangle'])
>>> df
           angles  degrees
circle          0      360
triangle        3      180
rectangle       4      360
>>> df.rtruediv(10)
             angles   degrees
circle          inf  0.027778
triangle   3.333333  0.055556
rectangle  2.500000  0.027778
>>> df.rdiv(10)
             angles   degrees
circle          inf  0.027778
triangle   3.333333  0.055556
rectangle  2.500000  0.027778
>>> 10 / df
             angles   degrees
circle          inf  0.027778
triangle   3.333333  0.055556
rectangle  2.500000  0.027778
reindex(labels=None, axis=0, index=None, columns=None, copy=True)

Return a new DataFrame whose axes conform to a new index

DataFrame.reindex supports two calling conventions:
  • (index=index_labels, columns=column_names)

  • (labels, axis={0 or 'index', 1 or 'columns'})

Parameters
labelsIndex, Series-convertible, optional, default None
axis{0 or ‘index’, 1 or ‘columns’}, optional, default 0
indexIndex, Series-convertible, optional, default None

Shorthand for df.reindex(labels=index_labels, axis=0)

columnsarray-like, optional, default None

Shorthand for df.reindex(labels=column_names, axis=1)

copyboolean, optional, default True
Returns
A DataFrame whose axes conform to the new index(es)

Examples

>>> import cudf
>>> df = cudf.DataFrame()
>>> df['key'] = [0, 1, 2, 3, 4]
>>> df['val'] = [float(i + 10) for i in range(5)]
>>> df_new = df.reindex(index=[0, 3, 4, 5],
...                     columns=['key', 'val', 'sum'])
>>> print(df)
   key   val
0    0  10.0
1    1  11.0
2    2  12.0
3    3  13.0
4    4  14.0
>>> print(df_new)
   key   val  sum
0    0  10.0  NaN
3    3  13.0  NaN
4    4  14.0  NaN
5   -1   NaN  NaN
rename(mapper=None, index=None, columns=None, axis=0, copy=True, inplace=False, level=None, errors='ignore')

Alter column and index labels.

Function / dict values must be unique (1-to-1). Labels not contained in a dict / Series will be left as-is. Extra labels listed don’t throw an error.

DataFrame.rename supports two calling conventions:
  • (index=index_mapper, columns=columns_mapper, ...)

  • (mapper, axis={0/'index' or 1/'column'}, ...)

We highly recommend using keyword arguments to clarify your intent.

Parameters
mapperdict-like or function, default None

optional dict-like or functions transformations to apply to the index/column values depending on selected axis.

indexdict-like, default None

Optional dict-like transformations to apply to the index axis’ values. Does not support functions for axis 0 yet.

columnsdict-like or function, default None

optional dict-like or functions transformations to apply to the columns axis’ values.

axisint, default 0

Axis to rename with mapper. 0 or ‘index’ for index 1 or ‘columns’ for columns

copyboolean, default True

Also copy underlying data

inplaceboolean, default False

Return new DataFrame. If True, assign columns without copy

levelint or level name, default None

In case of a MultiIndex, only rename labels in the specified level.

errors{‘raise’, ‘ignore’, ‘warn’}, default ‘ignore’

Only ‘ignore’ supported Control raising of exceptions on invalid data for provided dtype.

  • raise : allow exceptions to be raised

  • ignore : suppress exceptions. On error return original object.

  • warn : prints last exceptions as warnings and return original object.

Returns
DataFrame

Notes

Difference from pandas:
  • Not supporting: level

Rename will not overwite column names. If a list with duplicates is passed, column names will be postfixed with a number.

repeat(repeats, axis=None)

Repeats elements consecutively.

Returns a new object of caller type(DataFrame/Series/Index) where each element of the current object is repeated consecutively a given number of times.

Parameters
repeatsint, or array of ints

The number of repetitions for each element. This should be a non-negative integer. Repeating 0 times will return an empty object.

Returns
Series/DataFrame/Index

A newly created object of same type as caller with repeated elements.

Examples

>>> import cudf
>>> df = cudf.DataFrame({'a': [1, 2, 3], 'b': [10, 20, 30]})
>>> df
   a   b
0  1  10
1  2  20
2  3  30
>>> df.repeat(3)
   a   b
0  1  10
0  1  10
0  1  10
1  2  20
1  2  20
1  2  20
2  3  30
2  3  30
2  3  30

Repeat on Series

>>> s = cudf.Series([0, 2])
>>> s
0    0
1    2
dtype: int64
>>> s.repeat([3, 4])
0    0
0    0
0    0
1    2
1    2
1    2
1    2
dtype: int64
>>> s.repeat(2)
0    0
0    0
1    2
1    2
dtype: int64

Repeat on Index

>>> index = cudf.Index([10, 22, 33, 55])
>>> index
Int64Index([10, 22, 33, 55], dtype='int64')
>>> index.repeat(5)
Int64Index([10, 10, 10, 10, 10, 22, 22, 22, 22, 22, 33,
            33, 33, 33, 33, 55, 55, 55, 55, 55],
        dtype='int64')
replace(to_replace=None, value=None, inplace=False, limit=None, regex=False, method=None)

Replace values given in to_replace with replacement.

Parameters
to_replacenumeric, str, list-like or dict

Value(s) to replace.

  • numeric or str:

    • values equal to to_replace will be replaced with replacement

  • list of numeric or str:

    • If replacement is also list-like, to_replace and replacement must be of same length.

  • dict:

    • Dicts can be used to replace different values in different columns. For example, {‘a’: 1, ‘z’: 2} specifies that the value 1 in column a and the value 2 in column z should be replaced with replacement*.

valuenumeric, str, list-like, or dict

Value(s) to replace to_replace with. If a dict is provided, then its keys must match the keys in to_replace, and corresponding values must be compatible (e.g., if they are lists, then they must match in length).

inplacebool, default False

If True, in place.

Returns
resultDataFrame

DataFrame after replacement.

Notes

Parameters that are currently not supported are: limit, regex, method

Examples

>>> import cudf
>>> gdf = cudf.DataFrame()
>>> gdf['id']= [0, 1, 2, -1, 4, -1, 6]
>>> gdf['id']= gdf['id'].replace(-1, None)
>>> gdf
     id
0     0
1     1
2     2
3  null
4     4
5  null
6     6
reset_index(level=None, drop=False, inplace=False, col_level=0, col_fill='')

Reset the index.

Reset the index of the DataFrame, and use the default one instead.

Parameters
dropbool, default False

Do not try to insert index into dataframe columns. This resets the index to the default integer index.

inplacebool, default False

Modify the DataFrame in place (do not create a new object).

Returns
DataFrame or None

DataFrame with the new index or None if inplace=True.

Examples

>>> df = cudf.DataFrame([('bird', 389.0),
...                    ('bird', 24.0),
...                    ('mammal', 80.5),
...                    ('mammal', np.nan)],
...                   index=['falcon', 'parrot', 'lion', 'monkey'],
...                   columns=('class', 'max_speed'))
>>> df
        class max_speed
falcon    bird     389.0
parrot    bird      24.0
lion    mammal      80.5
monkey  mammal      null
>>> df.reset_index()
    index   class max_speed
0  falcon    bird     389.0
1  parrot    bird      24.0
2    lion  mammal      80.5
3  monkey  mammal      null
>>> df.reset_index(drop=True)
    class max_speed
0    bird     389.0
1    bird      24.0
2  mammal      80.5
3  mammal      null
rfloordiv(other, axis='columns', level=None, fill_value=None)

Get Integer division of dataframe and other, element-wise (binary operator rfloordiv).

Equivalent to other // dataframe, but with support to substitute a fill_value for missing data in one of the inputs. With reverse version, floordiv.

Among flexible wrappers (add, sub, mul, div, mod, pow) to arithmetic operators: +, -, *, /, //, %, **.

Parameters
otherscalar, sequence, Series, or DataFrame

Any single or multiple element data structure, or list-like object.

fill_valuefloat or None, default None

Fill existing missing (NaN) values, and any new element needed for successful DataFrame alignment, with this value before computation. If data in both corresponding DataFrame locations is missing the result will be missing.

Returns
DataFrame

Result of the arithmetic operation.

Examples

>>> import cudf
>>> df = cudf.DataFrame({'col1': [10, 11, 23],
... 'col2': [101, 122, 321]})
>>> df
   col1  col2
0    10   101
1    11   122
2    23   321
>>> df.rfloordiv(df)
   col1  col2
0     1     1
1     1     1
2     1     1
>>> df.rfloordiv(200)
   col1  col2
0    20     1
1    18     1
2     8     0
>>> df.rfloordiv(100)
   col1  col2
0    10     0
1     9     0
2     4     0
rmod(other, axis='columns', level=None, fill_value=None)

Get Modulo division of dataframe and other, element-wise (binary operator rmod).

Equivalent to other % dataframe, but with support to substitute a fill_value for missing data in one of the inputs. With reverse version, mod.

Among flexible wrappers (add, sub, mul, div, mod, pow) to arithmetic operators: +, -, *, /, //, %, **.

Parameters
otherscalar, sequence, Series, or DataFrame

Any single or multiple element data structure, or list-like object.

fill_valuefloat or None, default None

Fill existing missing (NaN) values, and any new element needed for successful DataFrame alignment, with this value before computation. If data in both corresponding DataFrame locations is missing the result will be missing.

Returns
DataFrame

Result of the arithmetic operation.

Examples

>>> import cudf
>>> df = cudf.DataFrame({'angles': [1, 3, 4],
...                    'degrees': [360, 180, 360]},
...                   index=['circle', 'triangle', 'rectangle'])
>>> 100 % df
        angles  degrees
circle          0      100
triangle        1      100
rectangle       0      100
>>> df.rmod(100)
        angles  degrees
circle          0      100
triangle        1      100
rectangle       0      100
rmul(other, axis='columns', level=None, fill_value=None)

Get Multiplication of dataframe and other, element-wise (binary operator rmul).

Equivalent to other * dataframe, but with support to substitute a fill_value for missing data in one of the inputs. With reverse version, mul.

Among flexible wrappers (add, sub, mul, div, mod, pow) to arithmetic operators: +, -, *, /, //, %, **.

Parameters
otherscalar, sequence, Series, or DataFrame

Any single or multiple element data structure, or list-like object.

fill_valuefloat or None, default None

Fill existing missing (NaN) values, and any new element needed for successful DataFrame alignment, with this value before computation. If data in both corresponding DataFrame locations is missing the result will be missing.

Returns
DataFrame

Result of the arithmetic operation.

Examples

>>> import cudf
>>> df = cudf.DataFrame({'angles': [0, 3, 4],
...                    'degrees': [360, 180, 360]},
...                   index=['circle', 'triangle', 'rectangle'])
>>> other = pd.DataFrame({'angles': [0, 3, 4]},
...                      index=['circle', 'triangle', 'rectangle'])
>>> other * df
        angles degrees
circle          0    null
triangle        9    null
rectangle      16    null
>>> df.rmul(other, fill_value=0)
        angles  degrees
circle          0        0
triangle        9        0
rectangle      16        0
rolling(window, min_periods=None, center=False, axis=0, win_type=None)

Rolling window calculations.

Parameters
windowint or offset

Size of the window, i.e., the number of observations used to calculate the statistic. For datetime indexes, an offset can be provided instead of an int. The offset must be convertible to a timedelta. As opposed to a fixed window size, each window will be sized to accommodate observations within the time period specified by the offset.

min_periodsint, optional

The minimum number of observations in the window that are required to be non-null, so that the result is non-null. If not provided or None, min_periods is equal to the window size.

centerbool, optional

If True, the result is set at the center of the window. If False (default), the result is set at the right edge of the window.

Returns
Rolling object.

Examples

>>> import cudf
>>> a = cudf.Series([1, 2, 3, None, 4])

Rolling sum with window size 2.

>>> print(a.rolling(2).sum())
0
1    3
2    5
3
4
dtype: int64

Rolling sum with window size 2 and min_periods 1.

>>> print(a.rolling(2, min_periods=1).sum())
0    1
1    3
2    5
3    3
4    4
dtype: int64

Rolling count with window size 3.

>>> print(a.rolling(3).count())
0    1
1    2
2    3
3    2
4    2
dtype: int64

Rolling count with window size 3, but with the result set at the center of the window.

>>> print(a.rolling(3, center=True).count())
0    2
1    3
2    2
3    2
4    1 dtype: int64

Rolling max with variable window size specified by an offset; only valid for datetime index.

>>> a = cudf.Series(
...     [1, 9, 5, 4, np.nan, 1],
...     index=[
...         pd.Timestamp('20190101 09:00:00'),
...         pd.Timestamp('20190101 09:00:01'),
...         pd.Timestamp('20190101 09:00:02'),
...         pd.Timestamp('20190101 09:00:04'),
...         pd.Timestamp('20190101 09:00:07'),
...         pd.Timestamp('20190101 09:00:08')
...     ]
... )
>>> print(a.rolling('2s').max())
2019-01-01T09:00:00.000    1
2019-01-01T09:00:01.000    9
2019-01-01T09:00:02.000    9
2019-01-01T09:00:04.000    4
2019-01-01T09:00:07.000
2019-01-01T09:00:08.000    1
dtype: int64

Apply custom function on the window with the apply method

>>> import numpy as np
>>> import math
>>> b = cudf.Series([16, 25, 36, 49, 64, 81], dtype=np.float64)
>>> def some_func(A):
...     b = 0
...     for a in A:
...         b = b + math.sqrt(a)
...     return b
...
>>> print(b.rolling(3, min_periods=1).apply(some_func))
0     4.0
1     9.0
2    15.0
3    18.0
4    21.0
5    24.0
dtype: float64

And this also works for window rolling set by an offset

>>> import pandas as pd
>>> c = cudf.Series(
...     [16, 25, 36, 49, 64, 81],
...     index=[
...          pd.Timestamp('20190101 09:00:00'),
...          pd.Timestamp('20190101 09:00:01'),
...          pd.Timestamp('20190101 09:00:02'),
...          pd.Timestamp('20190101 09:00:04'),
...          pd.Timestamp('20190101 09:00:07'),
...          pd.Timestamp('20190101 09:00:08')
...      ],
...     dtype=np.float64
... )
>>> print(c.rolling('2s').apply(some_func))
2019-01-01T09:00:00.000     4.0
2019-01-01T09:00:01.000     9.0
2019-01-01T09:00:02.000    11.0
2019-01-01T09:00:04.000     7.0
2019-01-01T09:00:07.000     8.0
2019-01-01T09:00:08.000    17.0
dtype: float64
rpow(other, axis='columns', level=None, fill_value=None)

Get Exponential power of dataframe and other, element-wise (binary operator pow).

Equivalent to other ** dataframe, but with support to substitute a fill_value for missing data in one of the inputs. With reverse version, pow.

Among flexible wrappers (add, sub, mul, div, mod, pow) to arithmetic operators: +, -, *, /, //, %, **.

Parameters
otherscalar, sequence, Series, or DataFrame

Any single or multiple element data structure, or list-like object.

fill_valuefloat or None, default None

Fill existing missing (NaN) values, and any new element needed for successful DataFrame alignment, with this value before computation. If data in both corresponding DataFrame locations is missing the result will be missing.

Returns
DataFrame

Result of the arithmetic operation.

Examples

>>> import cudf
>>> df = cudf.DataFrame({'angles': [1, 3, 4],
...                    'degrees': [360, 180, 360]},
...                   index=['circle', 'triangle', 'rectangle'])
>>> 1 ** df
        angles  degrees
circle          1        1
triangle        1        1
rectangle       1        1
>>> df.rpow(1)
        angles  degrees
circle          1        1
triangle        1        1
rectangle       1        1
rsub(other, axis='columns', level=None, fill_value=None)

Get Subtraction of dataframe and other, element-wise (binary operator rsub).

Equivalent to other - dataframe, but with support to substitute a fill_value for missing data in one of the inputs. With reverse version, sub.

Among flexible wrappers (add, sub, mul, div, mod, pow) to arithmetic operators: +, -, *, /, //, %, **.

Parameters
otherscalar, sequence, Series, or DataFrame

Any single or multiple element data structure, or list-like object.

fill_valuefloat or None, default None

Fill existing missing (NaN) values, and any new element needed for successful DataFrame alignment, with this value before computation. If data in both corresponding DataFrame locations is missing the result will be missing.

Returns
DataFrame

Result of the arithmetic operation.

Examples

>>> import cudf
>>> df = cudf.DataFrame({'angles': [0, 3, 4],
...                    'degrees': [360, 180, 360]},
...                   index=['circle', 'triangle', 'rectangle'])
>>> df
           angles  degrees
circle          0      360
triangle        3      180
rectangle       4      360
>>> df.rsub(1)
           angles  degrees
circle          1     -359
triangle       -2     -179
rectangle      -3     -359
>>> df.rsub([1, 2])
           angles  degrees
circle          1     -358
triangle       -2     -178
rectangle      -3     -358
rtruediv(other, axis='columns', level=None, fill_value=None)

Get Floating division of dataframe and other, element-wise (binary operator rtruediv).

Equivalent to other / dataframe, but with support to substitute a fill_value for missing data in one of the inputs. With reverse version, truediv.

Among flexible wrappers (add, sub, mul, div, mod, pow) to arithmetic operators: +, -, *, /, //, %, **.

Parameters
otherscalar, sequence, Series, or DataFrame

Any single or multiple element data structure, or list-like object.

fill_valuefloat or None, default None

Fill existing missing (NaN) values, and any new element needed for successful DataFrame alignment, with this value before computation. If data in both corresponding DataFrame locations is missing the result will be missing.

Returns
DataFrame

Result of the arithmetic operation.

Examples

>>> import cudf
>>> df = cudf.DataFrame({'angles': [0, 3, 4],
...                    'degrees': [360, 180, 360]},
...                   index=['circle', 'triangle', 'rectangle'])
>>> df
           angles  degrees
circle          0      360
triangle        3      180
rectangle       4      360
>>> df.rtruediv(10)
             angles   degrees
circle          inf  0.027778
triangle   3.333333  0.055556
rectangle  2.500000  0.027778
>>> df.rdiv(10)
             angles   degrees
circle          inf  0.027778
triangle   3.333333  0.055556
rectangle  2.500000  0.027778
>>> 10 / df
             angles   degrees
circle          inf  0.027778
triangle   3.333333  0.055556
rectangle  2.500000  0.027778
sample(n=None, frac=None, replace=False, weights=None, random_state=None, axis=None, keep_index=True)

Return a random sample of items from an axis of object.

You can use random_state for reproducibility.

Parameters
nint, optional

Number of items from axis to return. Cannot be used with frac. Default = 1 if frac = None.

fracfloat, optional

Fraction of axis items to return. Cannot be used with n.

replacebool, default False

Allow or disallow sampling of the same row more than once. replace == True is not yet supported for axis = 1/”columns”

weightsstr or ndarray-like, optional

Only supported for axis=1/”columns”

random_stateint, numpy RandomState or None, default None

Seed for the random number generator (if int), or None. If None, a random seed will be chosen. if RandomState, seed will be extracted from current state.

axis{0 or ‘index’, 1 or ‘columns’, None}, default None

Axis to sample. Accepts axis number or name. Default is stat axis for given data type (0 for Series and DataFrames). Series and Index doesn’t support axis=1.

Returns
Series or DataFrame or Index

A new object of same type as caller containing n items randomly sampled from the caller object.

Examples

>>> import cudf as cudf
>>> df = cudf.DataFrame({"a":{1, 2, 3, 4, 5}})
>>> df.sample(3)
   a
1  2
3  4
0  1
>>> sr = cudf.Series([1, 2, 3, 4, 5])
>>> sr.sample(10, replace=True)
1    4
3    1
2    4
0    5
0    1
4    5
4    1
0    2
0    3
3    2
dtype: int64
>>> df = cudf.DataFrame(
... {"a":[1, 2], "b":[2, 3], "c":[3, 4], "d":[4, 5]})
>>> df.sample(2, axis=1)
   a  c
0  1  3
1  2  4
scatter_by_map(map_index, map_size=None, keep_index=True, **kwargs)

Scatter to a list of dataframes.

Uses map_index to determine the destination of each row of the original DataFrame.

Parameters
map_indexSeries, str or list-like

Scatter assignment for each row

map_sizeint

Length of output list. Must be >= uniques in map_index

keep_indexbool

Conserve original index values for each row

Returns
A list of cudf.DataFrame objects.
searchsorted(values, side='left', ascending=True, na_position='last')

Find indices where elements should be inserted to maintain order

Parameters
valueFrame (Shape must be consistent with self)

Values to be hypothetically inserted into Self

sidestr {‘left’, ‘right’} optional, default ‘left‘

If ‘left’, the index of the first suitable location found is given If ‘right’, return the last such index

ascendingbool optional, default True

Sorted Frame is in ascending order (otherwise descending)

na_positionstr {‘last’, ‘first’} optional, default ‘last‘

Position of null values in sorted order

Returns
1-D cupy array of insertion points

Examples

>>> s = cudf.Series([1, 2, 3])
>>> s.searchsorted(4)
3
>>> s.searchsorted([0, 4])
array([0, 3], dtype=int32)
>>> s.searchsorted([1, 3], side='left')
array([0, 2], dtype=int32)
>>> s.searchsorted([1, 3], side='right')
array([1, 3], dtype=int32)

If the values are not monotonically sorted, wrong locations may be returned:

>>> s = cudf.Series([2, 1, 3])
>>> s.searchsorted(1)
0   # wrong result, correct would be 1
>>> df = cudf.DataFrame({'a': [1, 3, 5, 7], 'b': [10, 12, 14, 16]})
>>> df
   a   b
0  1  10
1  3  12
2  5  14
3  7  16
>>> values_df = cudf.DataFrame({'a': [0, 2, 5, 6],
... 'b': [10, 11, 13, 15]})
>>> values_df
   a   b
0  0  10
1  2  17
2  5  13
3  6  15
>>> df.searchsorted(values_df, ascending=False)
array([4, 4, 4, 0], dtype=int32)
select_dtypes(include=None, exclude=None)

Return a subset of the DataFrame’s columns based on the column dtypes.

Parameters
includestr or list

which columns to include based on dtypes

excludestr or list

which columns to exclude based on dtypes

Returns
DataFrame

The subset of the frame including the dtypes in include and excluding the dtypes in exclude.

Raises
ValueError
  • If both of include and exclude are empty

  • If include and exclude have overlapping elements

Examples

>>> import cudf
>>> df = cudf.DataFrame({'a': [1, 2] * 3,
...                    'b': [True, False] * 3,
...                    'c': [1.0, 2.0] * 3})
>>> df
   a      b    c
0  1   True  1.0
1  2  False  2.0
2  1   True  1.0
3  2  False  2.0
4  1   True  1.0
5  2  False  2.0
>>> df.select_dtypes(include='bool')
       b
0   True
1  False
2   True
3  False
4   True
5  False
>>> df.select_dtypes(include=['float64'])
     c
0  1.0
1  2.0
2  1.0
3  2.0
4  1.0
5  2.0
>>> df.select_dtypes(exclude=['int'])
       b    c
0   True  1.0
1  False  2.0
2   True  1.0
3  False  2.0
4   True  1.0
5  False  2.0
set_index(index, drop=True, append=False, inplace=False, verify_integrity=False)

Return a new DataFrame with a new index

Parameters
indexIndex, Series-convertible, label-like, or list

Index : the new index. Series-convertible : values for the new index. Label-like : Label of column to be used as index. List : List of items from above.

dropboolean, default True

Whether to drop corresponding column for str index argument

appendboolean, default True

Whether to append columns to the existing index, resulting in a MultiIndex.

inplaceboolean, default False

Modify the DataFrame in place (do not create a new object).

verify_integrityboolean, default False

Check for duplicates in the new index.

Examples

>>> df = cudf.DataFrame({"a": [1, 2, 3, 4, 5],
... "b": ["a", "b", "c", "d","e"],
... "c": [1.0, 2.0, 3.0, 4.0, 5.0]})
>>> df
   a  b    c
0  1  a  1.0
1  2  b  2.0
2  3  c  3.0
3  4  d  4.0
4  5  e  5.0

Set the index to become the ‘b’ column:

>>> df.set_index('b')
   a    c
b
a  1  1.0
b  2  2.0
c  3  3.0
d  4  4.0
e  5  5.0

Create a MultiIndex using columns ‘a’ and ‘b’:

>>> df.set_index(["a", "b"])
       c
a b
1 a  1.0
2 b  2.0
3 c  3.0
4 d  4.0
5 e  5.0

Set new Index instance as index:

>>> df.set_index(cudf.RangeIndex(10, 15))
    a  b    c
10  1  a  1.0
11  2  b  2.0
12  3  c  3.0
13  4  d  4.0
14  5  e  5.0

Setting append=True will combine current index with column a:

>>> df.set_index("a", append=True)
     b    c
  a
0 1  a  1.0
1 2  b  2.0
2 3  c  3.0
3 4  d  4.0
4 5  e  5.0

set_index supports inplace parameter too:

>>> df.set_index("a", inplace=True)
>>> df
   b    c
a
1  a  1.0
2  b  2.0
3  c  3.0
4  d  4.0
5  e  5.0
property shape

Returns a tuple representing the dimensionality of the DataFrame.

shift(periods=1, freq=None, axis=0, fill_value=None)

Shift values by periods positions.

sin()

Get Trigonometric sine, element-wise.

Returns
DataFrame/Series/Index

Result of the trigonometric operation.

Examples

>>> import cudf
>>> ser = cudf.Series([0.0, 0.32434, 0.5, 45, 90, 180, 360])
>>> ser
0      0.00000
1      0.32434
2      0.50000
3     45.00000
4     90.00000
5    180.00000
6    360.00000
dtype: float64
>>> ser.sin()
0    0.000000
1    0.318683
2    0.479426
3    0.850904
4    0.893997
5   -0.801153
6    0.958916
dtype: float64

sin operation on DataFrame:

>>> df = cudf.DataFrame({'first': [0.0, 5, 10, 15],
...                      'second': [100.0, 360, 720, 300]})
>>> df
   first  second
0    0.0   100.0
1    5.0   360.0
2   10.0   720.0
3   15.0   300.0
>>> df.sin()
      first    second
0  0.000000 -0.506366
1 -0.958924  0.958916
2 -0.544021 -0.544072
3  0.650288 -0.999756

sin operation on Index:

>>> index = cudf.Index([-0.4, 100, -180, 90])
>>> index
Float64Index([-0.4, 100.0, -180.0, 90.0], dtype='float64')
>>> index.sin()
Float64Index([-0.3894183423086505, -0.5063656411097588,
            0.8011526357338306, 0.8939966636005579],
            dtype='float64')
property size

Return the number of elements in the underlying data.

Returns
sizeSize of the DataFrame / Index / Series / MultiIndex

Examples

Size of an empty dataframe is 0.

>>> import cudf
>>> df = cudf.DataFrame()
>>> df
Empty DataFrame
Columns: []
Index: []
>>> df.size
0
>>> df = cudf.DataFrame(index=[1, 2, 3])
>>> df
Empty DataFrame
Columns: []
Index: [1, 2, 3]
>>> df.size
0

DataFrame with values

>>> df = cudf.DataFrame({'a': [10, 11, 12],
...         'b': ['hello', 'rapids', 'ai']})
>>> df
    a       b
0  10   hello
1  11  rapids
2  12      ai
>>> df.size
6
>>> df.index
RangeIndex(start=0, stop=3)
>>> df.index.size
3

Size of an Index

>>> index = cudf.Index([])
>>> index
Float64Index([], dtype='float64')
>>> index.size
0
>>> index = cudf.Index([1, 2, 3, 10])
>>> index
Int64Index([1, 2, 3, 10], dtype='int64')
>>> index.size
4

Size of a MultiIndex

>>> midx = cudf.MultiIndex(
...                 levels=[["a", "b", "c", None], ["1", None, "5"]],
...                 codes=[[0, 0, 1, 2, 3], [0, 2, 1, 1, 0]],
...                 names=["x", "y"],
...             )
>>> midx
MultiIndex(levels=[0       a
1       b
2       c
3    None
dtype: object, 0       1
1    None
2       5
dtype: object],
codes=   x  y
0  0  0
1  0  2
2  1  1
3  2  1
4  3  0)
>>> midx.size
5
skew(axis=None, skipna=None, level=None, numeric_only=None, **kwargs)

Return unbiased Fisher-Pearson skew of a sample.

Parameters
skipna: bool, default True

Exclude NA/null values when computing the result.

Returns
Series

Notes

Parameters currently not supported are axis, level and numeric_only

Examples

>>> import cudf
>>> df = cudf.DataFrame({'a': [3, 2, 3, 4], 'b': [7, 8, 10, 10]})
>>> df.skew()
a    0.00000
b   -0.37037
dtype: float64
sort_index(axis=0, level=None, ascending=True, inplace=False, kind=None, na_position='last', sort_remaining=True, ignore_index=False)

Sort object by labels (along an axis).

Parameters
axis{0 or ‘index’, 1 or ‘columns’}, default 0

The axis along which to sort. The value 0 identifies the rows, and 1 identifies the columns.

levelint or level name or list of ints or list of level names

If not None, sort on values in specified index level(s). This is only useful in the case of MultiIndex.

ascendingbool, default True

Sort ascending vs. descending.

inplacebool, default False

If True, perform operation in-place.

kindsorting method such as quick sort and others.

Not yet supported.

na_position{‘first’, ‘last’}, default ‘last’

Puts NaNs at the beginning if first; last puts NaNs at the end.

sort_remainingbool, default True

Not yet supported

ignore_indexbool, default False

if True, index will be replaced with RangeIndex.

Returns
DataFrame or None

Examples

>>> df = cudf.DataFrame(
... {"b":[3, 2, 1], "a":[2, 1, 3]}, index=[1, 3, 2])
>>> df.sort_index(axis=0)
   b  a
1  3  2
2  1  3
3  2  1
>>> df.sort_index(axis=1)
   a  b
1  2  3
3  1  2
2  3  1
sort_values(by, axis=0, ascending=True, inplace=False, kind='quicksort', na_position='last', ignore_index=False)

Sort by the values row-wise.

Parameters
bystr or list of str

Name or list of names to sort by.

ascendingbool or list of bool, default True

Sort ascending vs. descending. Specify list for multiple sort orders. If this is a list of bools, must match the length of the by.

na_position{‘first’, ‘last’}, default ‘last’

‘first’ puts nulls at the beginning, ‘last’ puts nulls at the end

ignore_indexbool, default False

If True, index will not be sorted.

Returns
sorted_objcuDF DataFrame

Notes

Difference from pandas:
  • Support axis=’index’ only.

  • Not supporting: inplace, kind

Examples

>>> import cudf
>>> a = ('a', [0, 1, 2])
>>> b = ('b', [-3, 2, 0])
>>> df = cudf.DataFrame([a, b])
>>> print(df.sort_values('b'))
   a  b
0  0 -3
2  2  0
1  1  2
sqrt()

Get the non-negative square-root of all elements, element-wise.

Returns
DataFrame/Series/Index

Result of the non-negative square-root of each element.

Examples

>>> import cudf
>>> import cudf
>>> ser = cudf.Series([10, 25, 81, 1.0, 100])
>>> ser
0     10.0
1     25.0
2     81.0
3      1.0
4    100.0
dtype: float64
>>> ser.sqrt()
0     3.162278
1     5.000000
2     9.000000
3     1.000000
4    10.000000
dtype: float64

sqrt operation on DataFrame:

>>> df = cudf.DataFrame({'first': [-10.0, 100, 625],
...                      'second': [1, 2, 0.4]})
>>> df
   first  second
0  -10.0     1.0
1  100.0     2.0
2  625.0     0.4
>>> df.sqrt()
   first    second
0    NaN  1.000000
1   10.0  1.414214
2   25.0  0.632456

sqrt operation on Index:

>>> index = cudf.Index([-10.0, 100, 625])
>>> index
Float64Index([-10.0, 100.0, 625.0], dtype='float64')
>>> index.sqrt()
Float64Index([nan, 10.0, 25.0], dtype='float64')
stack(level=- 1, dropna=True)

Stack the prescribed level(s) from columns to index

Return a reshaped Series

Parameters
dropnabool, default True

Whether to drop rows in the resulting Series with missing values.

Returns
The stacked cudf.Series

Examples

>>> import cudf
>>> df = cudf.DataFrame({'a':[0,1,3], 'b':[1,2,4]})
>>> df.stack()
0  a    0
   b    1
1  a    1
   b    2
2  a    3
   b    4
dtype: int64
std(axis=None, skipna=None, level=None, ddof=1, numeric_only=None, **kwargs)

Return sample standard deviation of the DataFrame.

Normalized by N-1 by default. This can be changed using the ddof argument

Parameters
axis: {index (0), columns(1)}

Axis for the function to be applied on.

skipna: bool, default True

Exclude NA/null values. If an entire row/column is NA, the result will be NA.

ddof: int, default 1

Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements.

Returns
Series

Notes

Parameters currently not supported are level and numeric_only

Examples

>>> import cudf
>>> df = cudf.DataFrame({'a': [1, 2, 3, 4], 'b': [7, 8, 9, 10]})
>>> df.std()
a    1.290994
b    1.290994
dtype: float64
sub(other, axis='columns', level=None, fill_value=None)

Get Subtraction of dataframe and other, element-wise (binary operator sub).

Equivalent to dataframe - other, but with support to substitute a fill_value for missing data in one of the inputs. With reverse version, rsub.

Among flexible wrappers (add, sub, mul, div, mod, pow) to arithmetic operators: +, -, *, /, //, %, **.

Parameters
otherscalar, sequence, Series, or DataFrame

Any single or multiple element data structure, or list-like object.

fill_valuefloat or None, default None

Fill existing missing (NaN) values, and any new element needed for successful DataFrame alignment, with this value before computation. If data in both corresponding DataFrame locations is missing the result will be missing.

Returns
DataFrame

Result of the arithmetic operation.

Examples

>>> import cudf
>>> df = cudf.DataFrame({'angles': [0, 3, 4],
...                    'degrees': [360, 180, 360]},
...                   index=['circle', 'triangle', 'rectangle'])
>>> df.sub(1)
        angles  degrees
circle         -1      359
triangle        2      179
rectangle       3      359
>>> df.sub([1, 2])
        angles  degrees
circle         -1      358
triangle        2      178
rectangle       3      358
sum(axis=None, skipna=None, dtype=None, level=None, numeric_only=None, min_count=0, **kwargs)

Return sum of the values in the DataFrame.

Parameters
axis: {index (0), columns(1)}

Axis for the function to be applied on.

skipna: bool, default True

Exclude NA/null values when computing the result.

dtype: data type

Data type to cast the result to.

min_count: int, default 0

The required number of valid values to perform the operation. If fewer than min_count non-NA values are present the result will be NA.

The default being 0. This means the sum of an all-NA or empty Series is 0, and the product of an all-NA or empty Series is 1.

Returns
Series

Notes

Parameters currently not supported are level, numeric_only.

Examples

>>> import cudf
>>> df = cudf.DataFrame({'a': [1, 2, 3, 4], 'b': [7, 8, 9, 10]})
>>> df.sum()
a    10
b    34
dtype: int64
tail(n=5)

Returns the last n rows as a new DataFrame

Examples

>>> import cudf
>>> df = cudf.DataFrame()
>>> df['key'] = [0, 1, 2, 3, 4]
>>> df['val'] = [float(i + 10) for i in range(5)]  # insert column
>>> print(df.tail(2))
   key   val
3    3  13.0
4    4  14.0
take(positions, keep_index=True)

Return a new DataFrame containing the rows specified by positions

Parameters
positionsarray-like

Integer or boolean array-like specifying the rows of the output. If integer, each element represents the integer index of a row. If boolean, positions must be of the same length as self, and represents a boolean mask.

Returns
outDataFrame

New DataFrame

Examples

>>> a = cudf.DataFrame({'a': [1.0, 2.0, 3.0],
...                    'b': cudf.Series(['a', 'b', 'c'])})
>>> a.take([0, 2, 2])
     a  b
0  1.0  a
2  3.0  c
2  3.0  c
>>> a.take([True, False, True])
     a  b
0  1.0  a
2  3.0  c
tan()

Get Trigonometric tangent, element-wise.

Returns
DataFrame/Series/Index

Result of the trigonometric operation.

Examples

>>> import cudf
>>> ser = cudf.Series([0.0, 0.32434, 0.5, 45, 90, 180, 360])
>>> ser
0      0.00000
1      0.32434
2      0.50000
3     45.00000
4     90.00000
5    180.00000
6    360.00000
dtype: float64
>>> ser.tan()
0    0.000000
1    0.336213
2    0.546302
3    1.619775
4   -1.995200
5    1.338690
6   -3.380140
dtype: float64

tan operation on DataFrame:

>>> df = cudf.DataFrame({'first': [0.0, 5, 10, 15],
...                      'second': [100.0, 360, 720, 300]})
>>> df
   first  second
0    0.0   100.0
1    5.0   360.0
2   10.0   720.0
3   15.0   300.0
>>> df.tan()
      first     second
0  0.000000  -0.587214
1 -3.380515  -3.380140
2  0.648361   0.648446
3 -0.855993  45.244742

tan operation on Index:

>>> index = cudf.Index([-0.4, 100, -180, 90])
>>> index
Float64Index([-0.4, 100.0, -180.0, 90.0], dtype='float64')
>>> index.tan()
Float64Index([-0.4227932187381618,  -0.587213915156929,
            -1.3386902103511544, -1.995200412208242],
            dtype='float64')
tile(count)

Repeats the rows from self DataFrame count times to form a new DataFrame.

Parameters
selfinput Table containing columns to interleave.
countNumber of times to tile “rows”. Must be non-negative.
Returns
The table containing the tiled “rows”.

Examples

>>> df  = Dataframe([[8, 4, 7], [5, 2, 3]])
>>> count = 2
>>> df.tile(df, count)
   0  1  2
0  8  4  7
1  5  2  3
0  8  4  7
1  5  2  3
to_arrow(preserve_index=True)

Convert to a PyArrow Table.

Parameters
preserve_indexbool, default True

whether index column and its meta data needs to be saved or not

Returns
PyArrow Table

Examples

>>> import cudf
>>> df = cudf.DataFrame(
...     {"a":[1, 2, 3], "b":[4, 5, 6]}, index=[1, 2, 3])
>>> df.to_arrow()
pyarrow.Table
a: int64
b: int64
index: int64
>>> df.to_arrow(preserve_index=False)
pyarrow.Table
a: int64
b: int64
to_csv(path=None, sep=',', na_rep='', columns=None, header=True, index=True, line_terminator='\n', chunksize=None)

Write a dataframe to csv file format.

Parameters
dfDataFrame

DataFrame object to be written to csv

pathstr, default None

Path of file where DataFrame will be written

sepchar, default ‘,’

Delimiter to be used.

na_repstr, default ‘’

String to use for null entries

columnslist of str, optional

Columns to write

headerbool, default True

Write out the column names

indexbool, default True

Write out the index as a column

line_terminatorchar, default ‘n’
chunksizeint or None, default None

Rows to write at a time

Notes

  • Follows the standard of Pandas csv.QUOTE_NONNUMERIC for all output.

  • If to_csv leads to memory errors consider setting the chunksize argument.

Examples

Write a dataframe to csv.

>>> import cudf
>>> filename = 'foo.csv'
>>> df = cudf.DataFrame({'x': [0, 1, 2, 3],
                         'y': [1.0, 3.3, 2.2, 4.4],
                         'z': ['a', 'b', 'c', 'd']})
>>> df = df.set_index([3, 2, 1, 0])
>>> df.to_csv(filename)
to_dlpack()

Converts a cuDF object into a DLPack tensor.

DLPack is an open-source memory tensor structure: dmlc/dlpack.

This function takes a cuDF object and converts it to a PyCapsule object which contains a pointer to a DLPack tensor. This function deep copies the data into the DLPack tensor from the cuDF object.

Parameters
cudf_objDataFrame, Series, Index, or Column
Returns
pycapsule_objPyCapsule

Output DLPack tensor pointer which is encapsulated in a PyCapsule object.

to_feather(path, *args, **kwargs)

Write a DataFrame to the feather format.

Parameters
pathstr

File path

to_gpu_matrix()

Convert to a numba gpu ndarray

Returns
numba gpu ndarray
to_hdf(path_or_buf, key, *args, **kwargs)

Write the contained data to an HDF5 file using HDFStore.

Hierarchical Data Format (HDF) is self-describing, allowing an application to interpret the structure and contents of a file with no outside information. One HDF file can hold a mix of related objects which can be accessed as a group or as individual objects.

In order to add another DataFrame or Series to an existing HDF file please use append mode and a different a key.

For more information see the user guide.

Parameters
path_or_bufstr or pandas.HDFStore

File path or HDFStore object.

keystr

Identifier for the group in the store.

mode{‘a’, ‘w’, ‘r+’}, default ‘a’

Mode to open file:

  • ‘w’: write, a new file is created (an existing file with the same name would be deleted).

  • ‘a’: append, an existing file is opened for reading and writing, and if the file does not exist it is created.

  • ‘r+’: similar to ‘a’, but the file must already exist.

format{‘fixed’, ‘table’}, default ‘fixed’

Possible values:

  • ‘fixed’: Fixed format. Fast writing/reading. Not-appendable, nor searchable.

  • ‘table’: Table format. Write as a PyTables Table structure which may perform worse but allow more flexible operations like searching / selecting subsets of the data.

appendbool, default False

For Table formats, append the input data to the existing.

data_columnslist of columns or True, optional

List of columns to create as indexed data columns for on-disk queries, or True to use all columns. By default only the axes of the object are indexed. See Query via Data Columns. Applicable only to format=’table’.

complevel{0-9}, optional

Specifies a compression level for data. A value of 0 disables compression.

complib{‘zlib’, ‘lzo’, ‘bzip2’, ‘blosc’}, default ‘zlib’

Specifies the compression library to be used. As of v0.20.2 these additional compressors for Blosc are supported (default if no compressor specified: ‘blosc:blosclz’): {‘blosc:blosclz’, ‘blosc:lz4’, ‘blosc:lz4hc’, ‘blosc:snappy’, ‘blosc:zlib’, ‘blosc:zstd’}. Specifying a compression library which is not available issues a ValueError.

fletcher32bool, default False

If applying compression use the fletcher32 checksum.

dropnabool, default False

If true, ALL nan rows will not be written to store.

errorsstr, default ‘strict’

Specifies how encoding and decoding errors are to be handled. See the errors argument for open() for a full list of options.

See also

cudf.io.hdf.read_hdf

Read from HDF file.

cudf.io.parquet.to_parquet

Write a DataFrame to the binary parquet format.

cudf.io.feather.to_feather

Write out feather-format for DataFrames.

to_json(path_or_buf=None, *args, **kwargs)

Convert the cuDF object to a JSON string. Note nulls and NaNs will be converted to null and datetime objects will be converted to UNIX timestamps.

Parameters
path_or_bufstring or file handle, optional

File path or object. If not specified, the result is returned as a string.

orientstring

Indication of expected JSON string format.

  • Series
    • default is ‘index’

    • allowed values are: {‘split’,’records’,’index’,’table’}

  • DataFrame
    • default is ‘columns’

    • allowed values are: {‘split’,’records’,’index’,’columns’,’values’,’table’}

  • The format of the JSON string
    • ‘split’ : dict like {‘index’ -> [index], ‘columns’ -> [columns], ‘data’ -> [values]}

    • ‘records’ : list like [{column -> value}, … , {column -> value}]

    • ‘index’ : dict like {index -> {column -> value}}

    • ‘columns’ : dict like {column -> {index -> value}}

    • ‘values’ : just the values array

    • ‘table’ : dict like {‘schema’: {schema}, ‘data’: {data}} describing the data, and the data component is like orient='records'.

date_format{None, ‘epoch’, ‘iso’}

Type of date conversion. ‘epoch’ = epoch milliseconds, ‘iso’ = ISO8601. The default depends on the orient. For orient='table', the default is ‘iso’. For all other orients, the default is ‘epoch’.

double_precisionint, default 10

The number of decimal places to use when encoding floating point values.

force_asciibool, default True

Force encoded string to be ASCII.

date_unitstring, default ‘ms’ (milliseconds)

The time unit to encode to, governs timestamp and ISO8601 precision. One of ‘s’, ‘ms’, ‘us’, ‘ns’ for second, millisecond, microsecond, and nanosecond respectively.

default_handlercallable, default None

Handler to call if object cannot otherwise be converted to a suitable format for JSON. Should receive a single argument which is the object to convert and return a serializable object.

linesbool, default False

If ‘orient’ is ‘records’ write out line delimited json format. Will throw ValueError if incorrect ‘orient’ since others are not list like.

compression{‘infer’, ‘gzip’, ‘bz2’, ‘zip’, ‘xz’, None}

A string representing the compression to use in the output file, only used when the first argument is a filename. By default, the compression is inferred from the filename.

indexbool, default True

Whether to include the index values in the JSON string. Not including the index (index=False) is only supported when orient is ‘split’ or ‘table’.

to_orc(fname, compression=None, *args, **kwargs)

Write a DataFrame to the ORC format.

Parameters
fnamestr

File path or object where the ORC dataset will be stored.

compression{{ ‘snappy’, None }}, default None

Name of the compression to use. Use None for no compression.

enable_statistics: boolean, default True

Enable writing column statistics.

to_pandas(**kwargs)

Convert to a Pandas DataFrame.

Examples

>>> import cudf
>>> df = cudf.DataFrame({'a': [0, 1, 2], 'b': [-3, 2, 0]})
>>> pdf = df.to_pandas()
>>> pdf
   a  b
0  0 -3
1  1  2
2  2  0
>>> type(pdf)
<class 'pandas.core.frame.DataFrame'>
to_parquet(path, *args, **kwargs)

Write a DataFrame to the parquet format.

Parameters
pathstr

File path or Root Directory path. Will be used as Root Directory path while writing a partitioned dataset.

compression{‘snappy’, ‘gzip’, ‘brotli’, None}, default ‘snappy’

Name of the compression to use. Use None for no compression.

indexbool, default None

If True, include the dataframe’s index(es) in the file output. If False, they will not be written to the file. If None, the engine’s default behavior will be used.

partition_colslist, optional, default None

Column names by which to partition the dataset Columns are partitioned in the order they are given

partition_file_namestr, optional, default None

File name to use for partitioned datasets. Different partitions will be written to different directories, but all files will have this name. If nothing is specified, a random uuid4 hex string will be used for each file.

to_records(index=True)

Convert to a numpy recarray

Parameters
indexbool

Whether to include the index in the output.

Returns
numpy recarray
to_string()

Convert to string

cuDF uses Pandas internals for efficient string formatting. Set formatting options using pandas string formatting options and cuDF objects will print identically to Pandas objects.

cuDF supports null/None as a value in any column type, which is transparently supported during this output process.

Examples

>>> import cudf
>>> df = cudf.DataFrame()
>>> df['key'] = [0, 1, 2]
>>> df['val'] = [float(i + 10) for i in range(3)]
>>> df.to_string()
'   key   val\n0    0  10.0\n1    1  11.0\n2    2  12.0'
transpose()

Transpose index and columns.

Returns
a new (ncol x nrow) dataframe. self is (nrow x ncol)

Notes

Difference from pandas: Not supporting copy because default and only behavior is copy=True

truediv(other, axis='columns', level=None, fill_value=None)

Get Floating division of dataframe and other, element-wise (binary operator truediv).

Equivalent to dataframe / other, but with support to substitute a fill_value for missing data in one of the inputs. With reverse version, rtruediv.

Among flexible wrappers (add, sub, mul, div, mod, pow) to arithmetic operators: +, -, *, /, //, %, **.

Parameters
otherscalar, sequence, Series, or DataFrame

Any single or multiple element data structure, or list-like object.

fill_valuefloat or None, default None

Fill existing missing (NaN) values, and any new element needed for successful DataFrame alignment, with this value before computation. If data in both corresponding DataFrame locations is missing the result will be missing.

Returns
DataFrame

Result of the arithmetic operation.

Examples

>>> import cudf
>>> df = cudf.DataFrame({'angles': [0, 3, 4],
...                    'degrees': [360, 180, 360]},
...                   index=['circle', 'triangle', 'rectangle'])
>>> df.truediv(10)
            angles  degrees
circle        0.0     36.0
triangle      0.3     18.0
rectangle     0.4     36.0
>>> df.div(10)
            angles  degrees
circle        0.0     36.0
triangle      0.3     18.0
rectangle     0.4     36.0
>>> df / 10
            angles  degrees
circle        0.0     36.0
triangle      0.3     18.0
rectangle     0.4     36.0
unstack(level=- 1, fill_value=None)

Pivot one or more levels of the (necessarily hierarchical) index labels.

Pivots the specified levels of the index labels of df to the innermost levels of the columns labels of the result.

Parameters
dfDataFrame
levellevel name or index, list-like

Integer, name or list of such, specifying one or more levels of the index to pivot

fill_value

Non-functional argument provided for compatibility with Pandas.

Returns
DataFrame with specified index levels pivoted to column levels

Examples

>>> df['a'] = [1, 1, 1, 2, 2]
>>> df['b'] = [1, 2, 3, 1, 2]
>>> df['c'] = [5, 6, 7, 8, 9]
>>> df['d'] = ['a', 'b', 'a', 'd', 'e']
>>> df = df.set_index(['a', 'b', 'd'])
>>> df
       c
a b d
1 1 a  5
  2 b  6
  3 a  7
2 1 d  8
  2 e  9

Unstacking level ‘a’:

>>> df.unstack('a')
        c
a       1     2
b d
1 a     5  <NA>
  d  <NA>     8
2 b     6  <NA>
  e  <NA>     9
3 a     7  <NA>

Unstacking level ‘d’ :

>>> df.unstack('d')
        c
d       a     b     d     e
a b
1 1     5  <NA>  <NA>  <NA>
  2  <NA>     6  <NA>  <NA>
  3     7  <NA>  <NA>  <NA>
2 1  <NA>  <NA>     8  <NA>
  2  <NA>  <NA>  <NA>     9

Unstacking multiple levels:

>>> df.unstack(['b', 'd'])
      c
b     1           2           3
d     a     d     b     e     a
a
1     5  <NA>     6  <NA>     7
2  <NA>     8  <NA>     9  <NA>
property values

Return a CuPy representation of the DataFrame.

Only the values in the DataFrame will be returned, the axes labels will be removed.

Returns
out: cupy.ndarray

The values of the DataFrame.

var(axis=None, skipna=None, level=None, ddof=1, numeric_only=None, **kwargs)

Return unbiased variance of the DataFrame.

Normalized by N-1 by default. This can be changed using the ddof argument

Parameters
axis: {index (0), columns(1)}

Axis for the function to be applied on.

skipna: bool, default True

Exclude NA/null values. If an entire row/column is NA, the result will be NA.

ddof: int, default 1

Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements.

Returns
scalar

Notes

Parameters currently not supported are level and numeric_only

Examples

>>> import cudf
>>> df = cudf.DataFrame({'a': [1, 2, 3, 4], 'b': [7, 8, 9, 10]})
>>> df.var()
a    1.666667
b    1.666667
dtype: float64
where(cond, other=None, inplace=False)

Replace values where the condition is False.

Parameters
condbool Series/DataFrame, array-like

Where cond is True, keep the original value. Where False, replace with corresponding value from other. Callables are not supported.

other: scalar, list of scalars, Series/DataFrame

Entries where cond is False are replaced with corresponding value from other. Callables are not supported. Default is None.

DataFrame expects only Scalar or array like with scalars or dataframe with same dimension as self.

Series expects only scalar or series like with same length

inplacebool, default False

Whether to perform the operation in place on the data.

Returns
Same type as caller

Examples

>>> import cudf
>>> df = cudf.DataFrame({"A":[1, 4, 5], "B":[3, 5, 8]})
>>> df.where(df % 2 == 0, [-1, -1])
   A  B
0 -1 -1
1  4 -1
2 -1  8
>>> ser = cudf.Series([4, 3, 2, 1, 0])
>>> ser.where(ser > 2, 10)
0     4
1     3
2    10
3    10
4    10
dtype: int64
>>> ser.where(ser > 2)
0       4
1       3
2    null
3    null
4    null
dtype: int64

Series

class cudf.core.series.Series(data=None, index=None, dtype=None, name=None, nan_as_null=True)

One-dimensional GPU array (including time series).

Labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index. Statistical methods from ndarray have been overridden to automatically exclude missing data (currently represented as null/NaN).

Operations between Series (+, -, /, *, **) align values based on their associated index values-– they need not be the same length. The result index will be the sorted union of the two indexes.

Series objects are used as columns of DataFrame.

Parameters
dataarray-like, Iterable, dict, or scalar value

Contains data stored in Series.

indexarray-like or Index (1d)

Values must be hashable and have the same length as data. Non-unique index values are allowed. Will default to RangeIndex (0, 1, 2, …, n) if not provided. If both a dict and index sequence are used, the index will override the keys found in the dict.

dtypestr, numpy.dtype, or ExtensionDtype, optional

Data type for the output Series. If not specified, this will be inferred from data.

namestr, optional

The name to give to the Series.

nan_as_nullbool, Default True

If None/True, converts np.nan values to null values. If False, leaves np.nan values as is.

Attributes
cat

Accessor object for categorical properties of the Series values.

data

The gpu buffer for the data

dt

Accessor object for datetimelike properties of the Series values.

dtype

dtype of the Series

empty

Indicator whether DataFrame or Series is empty.

has_nulls

Indicator whether Series contains null values.

iloc

Select values by position.

index

The index object

is_monotonic

Return boolean if values in the object are monotonic_increasing.

is_monotonic_decreasing

Return boolean if values in the object are monotonic_decreasing.

is_monotonic_increasing

Return boolean if values in the object are monotonic_increasing.

is_unique

Return boolean if values in the object are unique.

list
loc

Select values by label.

name

Returns name of the Series.

ndim

Dimension of the data.

null_count

Number of null values

nullable

A boolean indicating whether a null-mask is needed

nullmask

The gpu buffer for the null-mask

shape

Returns a tuple representing the dimensionality of the Series.

size

Return the number of elements in the underlying data.

str

Vectorized string functions for Series and Index.

valid_count

Number of non-null values

values

Return a CuPy representation of the Series.

values_host

Return a numpy representation of the Series.

Methods

abs()

Absolute value of each element of the series.

acos()

Get Trigonometric inverse cosine, element-wise.

add(other[, fill_value, axis])

Addition of series and other, element-wise (binary operator add).

all([axis, bool_only, skipna, level])

Return whether all elements are True in Series.

any([axis, bool_only, skipna, level])

Return whether any elements is True in Series.

append(to_append[, ignore_index, …])

Append values from another Series or array-like object.

applymap(udf[, out_dtype])

Apply an elementwise function to transform the values in the Column.

argsort([ascending, na_position])

Returns a Series of int64 index that will sort the series.

as_index()

Returns a new Series with a RangeIndex.

as_mask()

Convert booleans to bitmask

asin()

Get Trigonometric inverse sine, element-wise.

astype(dtype[, copy, errors])

Cast the Series to the given dtype

atan()

Get Trigonometric inverse tangent, element-wise.

ceil()

Rounds each value upward to the smallest integral value not less than the original.

clip([lower, upper, inplace, axis])

Trim values at input threshold(s).

copy([deep])

Make a copy of this object’s indices and data.

corr(other[, method, min_periods])

Calculates the sample correlation between two Series, excluding missing values.

cos()

Get Trigonometric cosine, element-wise.

count([level])

Return number of non-NA/null observations in the Series

cov(other[, min_periods])

Compute covariance with Series, excluding missing values.

cummax([axis, skipna])

Return cumulative maximum of the Series.

cummin([axis, skipna])

Return cumulative minimum of the Series.

cumprod([axis, skipna])

Return cumulative product of the Series.

cumsum([axis, skipna])

Return cumulative sum of the Series.

describe([percentiles, include, exclude, …])

Generate descriptive statistics.

diff([periods])

Calculate the difference between values at positions i and i - N in an array and store the output in a new array.

digitize(bins[, right])

Return the indices of the bins to which each value in series belongs.

drop_duplicates([keep, inplace, ignore_index])

Return Series with duplicate values removed

dropna([axis, inplace, how])

Return a Series with null values removed.

eq(other[, fill_value, axis])

Equal to of series and other, element-wise (binary operator eq).

equals(other, **kwargs)

Test whether two objects contain the same elements.

exp()

Get the exponential of all elements, element-wise.

factorize([na_sentinel])

Encode the input values as integer labels

fillna(value[, method, axis, inplace, limit])

Fill null values with value.

floor()

Rounds each value downward to the largest integral value not greater than the original.

floordiv(other[, fill_value, axis])

Integer division of series and other, element-wise (binary operator floordiv).

from_arrow(array)

Convert from PyArrow Array/ChunkedArray to Series.

from_categorical(categorical[, codes])

Creates from a pandas.Categorical

from_masked_array(data, mask[, null_count])

Create a Series with null-mask.

from_pandas(s[, nan_as_null])

Convert from a Pandas Series.

ge(other[, fill_value, axis])

Greater than or equal to of series and other, element-wise (binary operator ge).

groupby([by, group_series, level, sort, …])

Group Series using a mapper or by a Series of columns.

gt(other[, fill_value, axis])

Greater than of series and other, element-wise (binary operator gt).

hash_encode(stop[, use_name])

Encode column values as ints in [0, stop) using hash function.

hash_values()

Compute the hash of values in this column.

head([n])

Return the first n rows.

interleave_columns()

Interleave Series columns of a table into a single column.

isin(values)

Check whether values are contained in Series.

isna()

Identify missing values.

isnull()

Identify missing values.

keys()

Return alias for index.

kurt([axis, skipna, level, numeric_only])

Return Fisher’s unbiased kurtosis of a sample.

kurtosis([axis, skipna, level, numeric_only])

Return Fisher’s unbiased kurtosis of a sample.

label_encoding(cats[, dtype, na_sentinel])

Perform label encoding

le(other[, fill_value, axis])

Less than or equal to of series and other, element-wise (binary operator le).

log()

Get the natural logarithm of all elements, element-wise.

lt(other[, fill_value, axis])

Less than of series and other, element-wise (binary operator lt).

mask(cond[, other, inplace])

Replace values where the condition is True.

max([axis, skipna, dtype, level, numeric_only])

Return the maximum of the values in the Series.

mean([axis, skipna, level, numeric_only])

Return the mean of the values in the series.

median([axis, skipna, level, numeric_only])

Return the median of the values for the requested axis.

memory_usage([index, deep])

Return the memory usage of the Series.

min([axis, skipna, dtype, level, numeric_only])

Return the minimum of the values in the Series.

mod(other[, fill_value, axis])

Modulo of series and other, element-wise (binary operator mod).

mode([dropna])

Return the mode(s) of the dataset.

mul(other[, fill_value, axis])

Multiplication of series and other, element-wise (binary operator mul).

nans_to_nulls()

Convert nans (if any) to nulls

ne(other[, fill_value, axis])

Not equal to of series and other, element-wise (binary operator ne).

nlargest([n, keep])

Returns a new Series of the n largest element.

notna()

Identify non-missing values.

notnull()

Identify non-missing values.

nsmallest([n, keep])

Returns a new Series of the n smallest element.

nunique([method, dropna])

Returns the number of unique values of the Series: approximate version, and exact version to be moved to libgdf

one_hot_encoding(cats[, dtype])

Perform one-hot-encoding

pow(other[, fill_value, axis])

Exponential power of series and other, element-wise (binary operator pow).

prod([axis, skipna, dtype, level, …])

Return product of the values in the series

product([axis, skipna, dtype, level, …])

Return product of the values in the Series.

quantile([q, interpolation, exact, quant_index])

Return values at the given quantile.

radd(other[, fill_value, axis])

Addition of series and other, element-wise (binary operator radd).

rank([axis, method, numeric_only, …])

Compute numerical data ranks (1 through n) along axis.

reindex([index, copy])

Return a Series that conforms to a new index

rename([index, copy])

Alter Series name

repeat(repeats[, axis])

Repeats elements consecutively.

replace([to_replace, value, inplace, limit, …])

Replace values given in to_replace with value.

reset_index([drop, inplace])

Reset index to RangeIndex

reverse()

Reverse the Series

rfloordiv(other[, fill_value, axis])

Integer division of series and other, element-wise (binary operator rfloordiv).

rmod(other[, fill_value, axis])

Modulo of series and other, element-wise (binary operator rmod).

rmul(other[, fill_value, axis])

Multiplication of series and other, element-wise (binary operator rmul).

rolling(window[, min_periods, center, axis, …])

Rolling window calculations.

round([decimals])

Round a Series to a configurable number of decimal places.

rpow(other[, fill_value, axis])

Exponential power of series and other, element-wise (binary operator rpow).

rsub(other[, fill_value, axis])

Subtraction of series and other, element-wise (binary operator rsub).

rtruediv(other[, fill_value, axis])

Floating division of series and other, element-wise (binary operator rtruediv).

sample([n, frac, replace, weights, …])

Return a random sample of items from an axis of object.

scale()

Scale values to [0, 1] in float64

scatter_by_map(map_index[, map_size, keep_index])

Scatter to a list of dataframes.

searchsorted(values[, side, ascending, …])

Find indices where elements should be inserted to maintain order

set_index(index)

Returns a new Series with a different index.

set_mask(mask[, null_count])

Create new Series by setting a mask array.

shift([periods, freq, axis, fill_value])

Shift values by periods positions.

sin()

Get Trigonometric sine, element-wise.

skew([axis, skipna, level, numeric_only])

Return unbiased Fisher-Pearson skew of a sample.

sort_index([ascending])

Sort by the index.

sort_values([axis, ascending, inplace, …])

Sort by the values.

sqrt()

Get the non-negative square-root of all elements, element-wise.

std([axis, skipna, level, ddof, numeric_only])

Return sample standard deviation of the Series.

sub(other[, fill_value, axis])

Subtraction of series and other, element-wise (binary operator sub).

sum([axis, skipna, dtype, level, …])

Return sum of the values in the Series.

tail([n])

Returns the last n rows as a new Series

take(indices[, keep_index])

Return Series by taking values from the corresponding indices.

tan()

Get Trigonometric tangent, element-wise.

tile(count)

Repeats the rows from self DataFrame count times to form a new DataFrame.

to_array([fillna])

Get a dense numpy array for the data.

to_arrow()

Convert Series to a PyArrow Array.

to_dlpack()

Converts a cuDF object into a DLPack tensor.

to_frame([name])

Convert Series into a DataFrame

to_gpu_array([fillna])

Get a dense numba device array for the data.

to_hdf(path_or_buf, key, *args, **kwargs)

Write the contained data to an HDF5 file using HDFStore.

to_json([path_or_buf])

Convert the cuDF object to a JSON string.

to_pandas([index])

Convert to a Pandas Series.

to_string()

Convert to string

truediv(other[, fill_value, axis])

Floating division of series and other, element-wise (binary operator truediv).

unique()

Returns unique values of this Series.

value_counts([normalize, sort, ascending, …])

Return a Series containing counts of unique values.

values_to_string([nrows])

Returns a list of string for each element.

var([axis, skipna, level, ddof, numeric_only])

Return unbiased variance of the Series.

where(cond[, other, inplace])

Replace values where the condition is False.

abs()

Absolute value of each element of the series.

Returns a new Series.

acos()

Get Trigonometric inverse cosine, element-wise.

The inverse of cos so that, if y = x.cos(), then x = y.acos()

Returns
DataFrame/Series/Index

Result of the trigonometric operation.

Examples

>>> import cudf
>>> ser = cudf.Series([-1, 0, 1, 0.32434, 0.5])
>>> ser.acos()
0    3.141593
1    1.570796
2    0.000000
3    1.240482
4    1.047198
dtype: float64

acos operation on DataFrame:

>>> df = cudf.DataFrame({'first': [-1, 0, 0.5],
...                      'second': [0.234, 0.3, 0.1]})
>>> df
   first  second
0   -1.0   0.234
1    0.0   0.300
2    0.5   0.100
>>> df.acos()
      first    second
0  3.141593  1.334606
1  1.570796  1.266104
2  1.047198  1.470629

acos operation on Index:

>>> index = cudf.Index([-1, 0.4, 1, 0, 0.3])
>>> index
Float64Index([-1.0, 0.4, 1.0, 0.0, 0.3], dtype='float64')
>>> index.acos()
Float64Index([ 3.141592653589793, 1.1592794807274085, 0.0,
            1.5707963267948966,  1.266103672779499],
            dtype='float64')
add(other, fill_value=None, axis=0)

Addition of series and other, element-wise (binary operator add).

Parameters
otherSeries or scalar value
fill_valueNone or value

Value to fill nulls with before computation. If data in both corresponding Series locations is null the result will be null

all(axis=0, bool_only=None, skipna=True, level=None, **kwargs)

Return whether all elements are True in Series.

Parameters
skipnabool, default True

Exclude NA/null values. If the entire row/column is NA and skipna is True, then the result will be True, as for an empty row/column. If skipna is False, then NA are treated as True, because these are not equal to zero.

Returns
scalar

Notes

Parameters currently not supported are axis, bool_only, level.

Examples

>>> import cudf
>>> ser = cudf.Series([1, 5, 2, 4, 3])
>>> ser.all()
True
any(axis=0, bool_only=None, skipna=True, level=None, **kwargs)

Return whether any elements is True in Series.

Parameters
skipnabool, default True

Exclude NA/null values. If the entire row/column is NA and skipna is True, then the result will be False, as for an empty row/column. If skipna is False, then NA are treated as True, because these are not equal to zero.

Returns
scalar

Notes

Parameters currently not supported are axis, bool_only, level.

Examples

>>> import cudf
>>> ser = cudf.Series([1, 5, 2, 4, 3])
>>> ser.any()
True
append(to_append, ignore_index=False, verify_integrity=False)

Append values from another Series or array-like object. If ignore_index=True, the index is reset.

Parameters
to_appendSeries or list/tuple of Series

Series to append with self.

ignore_indexboolean, default False.

If True, do not use the index.

verify_integritybool, default False

This Parameter is currently not supported.

Returns
Series

A new concatenated series

See also

cudf.concat

General function to concatenate DataFrame or Series objects.

Examples

>>> import cudf
>>> s1 = cudf.Series([1, 2, 3])
>>> s2 = cudf.Series([4, 5, 6])
>>> s1
0    1
1    2
2    3
dtype: int64
>>> s2
0    4
1    5
2    6
dtype: int64
>>> s1.append(s2)
0    1
1    2
2    3
0    4
1    5
2    6
dtype: int64
>>> s3 = cudf.Series([4, 5, 6], index=[3, 4, 5])
>>> s3
3    4
4    5
5    6
dtype: int64
>>> s1.append(s3)
0    1
1    2
2    3
3    4
4    5
5    6
dtype: int64

With ignore_index set to True:

>>> s1.append(s2, ignore_index=True)
0    1
1    2
2    3
3    4
4    5
5    6
dtype: int64
applymap(udf, out_dtype=None)

Apply an elementwise function to transform the values in the Column.

The user function is expected to take one argument and return the result, which will be stored to the output Series. The function cannot reference globals except for other simple scalar objects.

Parameters
udffunction

Either a callable python function or a python function already decorated by numba.cuda.jit for call on the GPU as a device

out_dtypenumpy.dtype; optional

The dtype for use in the output. Only used for numba.cuda.jit decorated udf. By default, the result will have the same dtype as the source.

Returns
resultSeries

The mask and index are preserved.

Notes

The supported Python features are listed in

with these exceptions:

  • Math functions in cmath are not supported since libcudf does not have complex number support and output of cmath functions are most likely complex numbers.

  • These five functions in math are not supported since numba generates multiple PTX functions from them

    • math.sin()

    • math.cos()

    • math.tan()

    • math.gamma()

    • math.lgamma()

  • Series with string dtypes are not supported in applymap method.

  • Global variables need to be re-defined explicitly inside the udf, as numba considers them to be compile-time constants and there is no known way to obtain value of the global variable.

Examples

Returning a Series of booleans using only a literal pattern.

>>> import cudf
>>> s = cudf.Series([1, 10, -10, 200, 100])
>>> s.applymap(lambda x: x)
0      1
1     10
2    -10
3    200
4    100
dtype: int64
>>> s.applymap(lambda x: x in [1, 100, 59])
0     True
1    False
2    False
3    False
4     True
dtype: bool
>>> s.applymap(lambda x: x ** 2)
0        1
1      100
2      100
3    40000
4    10000
dtype: int64
>>> s.applymap(lambda x: (x ** 2) + (x / 2))
0        1.5
1      105.0
2       95.0
3    40100.0
4    10050.0
dtype: float64
>>> def cube_function(a):
...     return a ** 3
...
>>> s.applymap(cube_function)
0          1
1       1000
2      -1000
3    8000000
4    1000000
dtype: int64
>>> def custom_udf(x):
...     if x > 0:
...         return x + 5
...     else:
...         return x - 5
...
>>> s.applymap(custom_udf)
0      6
1     15
2    -15
3    205
4    105
dtype: int64
argsort(ascending=True, na_position='last')

Returns a Series of int64 index that will sort the series.

Uses Thrust sort.

Returns
result: Series
as_index()

Returns a new Series with a RangeIndex.

Examples

>>> s = cudf.Series([1,2,3], index=['a','b','c'])
>>> s
a    1
b    2
c    3
dtype: int64
>>> s.as_index()
0    1
1    2
2    3
dtype: int64
as_mask()

Convert booleans to bitmask

Returns
device array
asin()

Get Trigonometric inverse sine, element-wise.

The inverse of sine so that, if y = x.sin(), then x = y.asin()

Returns
DataFrame/Series/Index

Result of the trigonometric operation.

Examples

>>> import cudf
>>> ser = cudf.Series([-1, 0, 1, 0.32434, 0.5])
>>> ser.asin()
0   -1.570796
1    0.000000
2    1.570796
3    0.330314
4    0.523599
dtype: float64

asin operation on DataFrame:

>>> df = cudf.DataFrame({'first': [-1, 0, 0.5],
...                      'second': [0.234, 0.3, 0.1]})
>>> df
   first  second
0   -1.0   0.234
1    0.0   0.300
2    0.5   0.100
>>> df.asin()
      first    second
0 -1.570796  0.236190
1  0.000000  0.304693
2  0.523599  0.100167

asin operation on Index:

>>> index = cudf.Index([-1, 0.4, 1, 0.3])
>>> index
Float64Index([-1.0, 0.4, 1.0, 0.3], dtype='float64')
>>> index.asin()
Float64Index([-1.5707963267948966, 0.41151684606748806,
            1.5707963267948966, 0.3046926540153975],
            dtype='float64')
astype(dtype, copy=False, errors='raise')

Cast the Series to the given dtype

Parameters
dtypedata type, or dict of column name -> data type

Use a numpy.dtype or Python type to cast Series object to the same type. Alternatively, use {col: dtype, …}, where col is a series name and dtype is a numpy.dtype or Python type to cast to.

copybool, default False

Return a deep-copy when copy=True. Note by default copy=False setting is used and hence changes to values then may propagate to other cudf objects.

errors{‘raise’, ‘ignore’, ‘warn’}, default ‘raise’

Control raising of exceptions on invalid data for provided dtype. - raise : allow exceptions to be raised - ignore : suppress exceptions. On error return original object. - warn : prints last exceptions as warnings and return original object.

Returns
outSeries

Returns self.copy(deep=copy) if dtype is the same as self.dtype.

atan()

Get Trigonometric inverse tangent, element-wise.

The inverse of tan so that, if y = x.tan(), then x = y.atan()

Returns
DataFrame/Series/Index

Result of the trigonometric operation.

Examples

>>> import cudf
>>> ser = cudf.Series([-1, 0, 1, 0.32434, 0.5, -10])
>>> ser
0    -1.00000
1     0.00000
2     1.00000
3     0.32434
4     0.50000
5   -10.00000
dtype: float64
>>> ser.atan()
0   -0.785398
1    0.000000
2    0.785398
3    0.313635
4    0.463648
5   -1.471128
dtype: float64

atan operation on DataFrame:

>>> df = cudf.DataFrame({'first': [-1, -10, 0.5],
...                      'second': [0.234, 0.3, 10]})
>>> df
   first  second
0   -1.0   0.234
1  -10.0   0.300
2    0.5  10.000
>>> df.atan()
      first    second
0 -0.785398  0.229864
1 -1.471128  0.291457
2  0.463648  1.471128

atan operation on Index:

>>> index = cudf.Index([-1, 0.4, 1, 0, 0.3])
>>> index
Float64Index([-1.0, 0.4, 1.0, 0.0, 0.3], dtype='float64')
>>> index.atan()
Float64Index([-0.7853981633974483,  0.3805063771123649,
                            0.7853981633974483, 0.0,
                            0.2914567944778671],
            dtype='float64')
property cat

Accessor object for categorical properties of the Series values. Be aware that assigning to categories is a inplace operation, while all methods return new categorical data per default.

Parameters
dataSeries or CategoricalIndex

Examples

>>> s = cudf.Series([1,2,3], dtype='category')
>>> s
>>> s
0    1
1    2
2    3
dtype: category
Categories (3, int64): [1, 2, 3]
>>> s.cat.categories
Int64Index([1, 2, 3], dtype='int64')
>>> s.cat.reorder_categories([3,2,1])
0    1
1    2
2    3
dtype: category
Categories (3, int64): [3, 2, 1]
>>> s.cat.remove_categories([1])
0   null
1      2
2      3
dtype: category
Categories (2, int64): [2, 3]
>>> s.cat.set_categories(list('abcde'))
0   null
1   null
2   null
dtype: category
Categories (5, object): [a, b, c, d, e]
>>> s.cat.as_ordered()
0    1
1    2
2    3
dtype: category
Categories (3, int64): [1 < 2 < 3]
>>> s.cat.as_unordered()
0    1
1    2
2    3
dtype: category
Categories (3, int64): [1, 2, 3]
ceil()

Rounds each value upward to the smallest integral value not less than the original.

Returns a new Series.

clip(lower=None, upper=None, inplace=False, axis=1)

Trim values at input threshold(s).

Assigns values outside boundary to boundary values. Thresholds can be singular values or array like, and in the latter case the clipping is performed element-wise in the specified axis. Currently only axis=1 is supported.

Parameters
lowerscalar or array_like, default None

Minimum threshold value. All values below this threshold will be set to it. If it is None, there will be no clipping based on lower. In case of Series/Index, lower is expected to be a scalar or an array of size 1.

upperscalar or array_like, default None

Maximum threshold value. All values below this threshold will be set to it. If it is None, there will be no clipping based on upper. In case of Series, upper is expected to be a scalar or an array of size 1.

inplacebool, default False
Returns
Clipped DataFrame/Series/Index/MultiIndex

Examples

>>> import cudf
>>> df = cudf.DataFrame({"a":[1, 2, 3, 4], "b":['a', 'b', 'c', 'd']})
>>> df.clip(lower=[2, 'b'], upper=[3, 'c'])
   a  b
0  2  b
1  2  b
2  3  c
3  3  c
>>> df.clip(lower=None, upper=[3, 'c'])
   a  b
0  1  a
1  2  b
2  3  c
3  3  c
>>> df.clip(lower=[2, 'b'], upper=None)
   a  b
0  2  b
1  2  b
2  3  c
3  4  d
>>> df.clip(lower=2, upper=3, inplace=True)
>>> df
   a  b
0  2  2
1  2  3
2  3  3
3  3  3
>>> import cudf
>>> sr = cudf.Series([1, 2, 3, 4])
>>> sr.clip(lower=2, upper=3)
0    2
1    2
2    3
3    3
dtype: int64
>>> sr.clip(lower=None, upper=3)
0    1
1    2
2    3
3    3
dtype: int64
>>> sr.clip(lower=2, upper=None, inplace=True)
>>> sr
0    2
1    2
2    3
3    4
dtype: int64
copy(deep=True)

Make a copy of this object’s indices and data.

When deep=True (default), a new object will be created with a copy of the calling object’s data and indices. Modifications to the data or indices of the copy will not be reflected in the original object (see notes below). When deep=False, a new object will be created without copying the calling object’s data or index (only references to the data and index are copied). Any changes to the data of the original will be reflected in the shallow copy (and vice versa).

Parameters
deepbool, default True

Make a deep copy, including a copy of the data and the indices. With deep=False neither the indices nor the data are copied.

Returns
copySeries or DataFrame

Object type matches caller.

Examples

>>> s = cudf.Series([1, 2], index=["a", "b"])
>>> s
a    1
b    2
dtype: int64
>>> s_copy = s.copy()
>>> s_copy
a    1
b    2
dtype: int64

Shallow copy versus default (deep) copy:

>>> s = cudf.Series([1, 2], index=["a", "b"])
>>> deep = s.copy()
>>> shallow = s.copy(deep=False)

Shallow copy shares data and index with original.

>>> s is shallow
False
>>> s._column is shallow._column and s.index is shallow.index
True

Deep copy has own copy of data and index.

>>> s is deep
False
>>> s.values is deep.values or s.index is deep.index
False

Updates to the data shared by shallow copy and original is reflected in both; deep copy remains unchanged.

>>> s['a'] = 3
>>> shallow['b'] = 4
>>> s
a    3
b    4
dtype: int64
>>> shallow
a    3
b    4
dtype: int64
>>> deep
a    1
b    2
dtype: int64
corr(other, method='pearson', min_periods=None)

Calculates the sample correlation between two Series, excluding missing values.

Examples

>>> import cudf
>>> ser1 = cudf.Series([0.9, 0.13, 0.62])
>>> ser2 = cudf.Series([0.12, 0.26, 0.51])
>>> ser1.corr(ser2)
-0.20454263717316112
cos()

Get Trigonometric cosine, element-wise.

Returns
DataFrame/Series/Index

Result of the trigonometric operation.

Examples

>>> import cudf
>>> ser = cudf.Series([0.0, 0.32434, 0.5, 45, 90, 180, 360])
>>> ser
0      0.00000
1      0.32434
2      0.50000
3     45.00000
4     90.00000
5    180.00000
6    360.00000
dtype: float64
>>> ser.cos()
0    1.000000
1    0.947861
2    0.877583
3    0.525322
4   -0.448074
5   -0.598460
6   -0.283691
dtype: float64

cos operation on DataFrame:

>>> df = cudf.DataFrame({'first': [0.0, 5, 10, 15],
...                      'second': [100.0, 360, 720, 300]})
>>> df
   first  second
0    0.0   100.0
1    5.0   360.0
2   10.0   720.0
3   15.0   300.0
>>> df.cos()
      first    second
0  1.000000  0.862319
1  0.283662 -0.283691
2 -0.839072 -0.839039
3 -0.759688 -0.022097

cos operation on Index:

>>> index = cudf.Index([-0.4, 100, -180, 90])
>>> index
Float64Index([-0.4, 100.0, -180.0, 90.0], dtype='float64')
>>> index.cos()
Float64Index([ 0.9210609940028851,  0.8623188722876839,
            -0.5984600690578581, -0.4480736161291701],
            dtype='float64')
count(level=None, **kwargs)

Return number of non-NA/null observations in the Series

Returns
int

Number of non-null values in the Series.

Notes

Parameters currently not supported is level.

Examples

>>> import cudf
>>> ser = cudf.Series([1, 5, 2, 4, 3])
>>> ser.count()
5
cov(other, min_periods=None)

Compute covariance with Series, excluding missing values.

Parameters
otherSeries

Series with which to compute the covariance.

Returns
float

Covariance between Series and other normalized by N-1 (unbiased estimator).

Notes

min_periods parameter is not yet supported.

Examples

>>> import cudf
>>> ser1 = cudf.Series([0.9, 0.13, 0.62])
>>> ser2 = cudf.Series([0.12, 0.26, 0.51])
>>> ser1.cov(ser2)
-0.015750000000000004
cummax(axis=0, skipna=True, *args, **kwargs)

Return cumulative maximum of the Series.

Parameters
skipnabool, default True

Exclude NA/null values. If an entire row/column is NA, the result will be NA.

Returns
Series

Notes

Parameters currently not supported is axis

Examples

>>> import cudf
>>> ser = cudf.Series([1, 5, 2, 4, 3])
>>> ser.cummax()
0    1
1    5
2    5
3    5
4    5
cummin(axis=None, skipna=True, *args, **kwargs)

Return cumulative minimum of the Series.

Parameters
skipnabool, default True

Exclude NA/null values. If an entire row/column is NA, the result will be NA.

Returns
Series

Notes

Parameters currently not supported is axis

Examples

>>> import cudf
>>> ser = cudf.Series([1, 5, 2, 4, 3])
>>> ser.cummin()
0    1
1    1
2    1
3    1
4    1
cumprod(axis=0, skipna=True, *args, **kwargs)

Return cumulative product of the Series.

Parameters
skipnabool, default True

Exclude NA/null values. If an entire row/column is NA, the result will be NA.

Returns
Series

Notes

Parameters currently not supported is axis

Examples

>>> import cudf
>>> ser = cudf.Series([1, 5, 2, 4, 3])
>>> ser.cumprod()
0    1
1    5
2    10
3    40
4    120
cumsum(axis=0, skipna=True, *args, **kwargs)

Return cumulative sum of the Series.

Parameters
skipnabool, default True

Exclude NA/null values. If an entire row/column is NA, the result will be NA.

Returns
Series

Notes

Parameters currently not supported is axis

Examples

>>> import cudf
>>> ser = cudf.Series([1, 5, 2, 4, 3])
>>> ser.cumsum()
0    1
1    6
2    8
3    12
4    15
property data

The gpu buffer for the data

describe(percentiles=None, include=None, exclude=None, datetime_is_numeric=False)

Generate descriptive statistics.

Descriptive statistics include those that summarize the central tendency, dispersion and shape of a dataset’s distribution, excluding NaN values.

Analyzes both numeric and object series, as well as DataFrame column sets of mixed data types. The output will vary depending on what is provided. Refer to the notes below for more detail.

Parameters
percentileslist-like of numbers, optional

The percentiles to include in the output. All should fall between 0 and 1. The default is [.25, .5, .75], which returns the 25th, 50th, and 75th percentiles.

include‘all’, list-like of dtypes or None(default), optional

A list of data types to include in the result. Ignored for Series. Here are the options:

  • ‘all’ : All columns of the input will be included in the output.

  • A list-like of dtypes : Limits the results to the provided data types. To limit the result to numeric types submit numpy.number. To limit it instead to object columns submit the numpy.object data type. Strings can also be used in the style of select_dtypes (e.g. df.describe(include=['O'])). To select pandas categorical columns, use 'category'

  • None (default) : The result will include all numeric columns.

excludelist-like of dtypes or None (default), optional,

A list of data types to omit from the result. Ignored for Series. Here are the options:

  • A list-like of dtypes : Excludes the provided data types from the result. To exclude numeric types submit numpy.number. To exclude object columns submit the data type numpy.object. Strings can also be used in the style of select_dtypes (e.g. df.describe(include=['O'])). To exclude pandas categorical columns, use 'category'

  • None (default) : The result will exclude nothing.

datetime_is_numericbool, default False

For DataFrame input, this also controls whether datetime columns are included by default.

Returns
output_frameSeries or DataFrame

Summary statistics of the Series or Dataframe provided.

Notes

For numeric data, the result’s index will include count, mean, std, min, max as well as lower, 50 and upper percentiles. By default the lower percentile is 25 and the upper percentile is 75. The 50 percentile is the same as the median.

For strings dtype or datetime dtype, the result’s index will include count, unique, top, and freq. The top is the most common value. The freq is the most common value’s frequency. Timestamps also include the first and last items.

If multiple object values have the highest count, then the count and top results will be arbitrarily chosen from among those with the highest count.

For mixed data types provided via a DataFrame, the default is to return only an analysis of numeric columns. If the dataframe consists only of object and categorical data without any numeric columns, the default is to return an analysis of both the object and categorical columns. If include='all' is provided as an option, the result will include a union of attributes of each type.

The include and exclude parameters can be used to limit which columns in a DataFrame are analyzed for the output. The parameters are ignored when analyzing a Series.

Examples

Describing a Series containing numeric values.

>>> import cudf
>>> s = cudf.Series([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
>>> s
0     1
1     2
2     3
3     4
4     5
5     6
6     7
7     8
8     9
9    10
dtype: int64
>>> s.describe()
count    10.00000
mean      5.50000
std       3.02765
min       1.00000
25%       3.25000
50%       5.50000
75%       7.75000
max      10.00000
dtype: float64

Describing a categorical Series.

>>> s = cudf.Series(['a', 'b', 'a', 'b', 'c', 'a'], dtype='category')
>>> s
0    a
1    b
2    a
3    b
4    c
5    a
dtype: category
Categories (3, object): ['a', 'b', 'c']
>>> s.describe()
count     6
unique    3
top       a
freq      3
dtype: object

Describing a timestamp Series.

>>> import numpy as np
>>> s = cudf.Series([
...   np.datetime64("2000-01-01"),
...   np.datetime64("2010-01-01"),
...   np.datetime64("2010-01-01")
... ])
>>> s
0   2000-01-01
1   2010-01-01
2   2010-01-01
dtype: datetime64[s]
>>> s.describe()
count                                3
mean     2006-09-01 08:00:00.000000000
min      2000-01-01 00:00:00.000000000
25%      2004-12-31 12:00:00.000000000
50%      2010-01-01 00:00:00.000000000
75%      2010-01-01 00:00:00.000000000
max      2010-01-01 00:00:00.000000000
dtype: object

Describing a DataFrame. By default only numeric fields are returned.

>>> df = cudf.DataFrame({"categorical": cudf.Series(['d', 'e', 'f'],
...                         dtype='category'),
...                      "numeric": [1, 2, 3],
...                      "object": ['a', 'b', 'c']
... })
>>> df
  categorical  numeric object
0           d        1      a
1           e        2      b
2           f        3      c
>>> df.describe()
       numeric
count      3.0
mean       2.0
std        1.0
min        1.0
25%        1.5
50%        2.0
75%        2.5
max        3.0

Describing all columns of a DataFrame regardless of data type.

>>> df.describe(include='all')
       categorical numeric object
count            3     3.0      3
unique           3    <NA>      3
top              d    <NA>      a
freq             1    <NA>      1
mean          <NA>     2.0   <NA>
std           <NA>     1.0   <NA>
min           <NA>     1.0   <NA>
25%           <NA>     1.5   <NA>
50%           <NA>     2.0   <NA>
75%           <NA>     2.5   <NA>
max           <NA>     3.0   <NA>

Describing a column from a DataFrame by accessing it as an attribute.

>>> df.numeric.describe()
count    3.0
mean     2.0
std      1.0
min      1.0
25%      1.5
50%      2.0
75%      2.5
max      3.0
Name: numeric, dtype: float64

Including only numeric columns in a DataFrame description.

>>> df.describe(include=[np.number])
       numeric
count      3.0
mean       2.0
std        1.0
min        1.0
25%        1.5
50%        2.0
75%        2.5
max        3.0

Including only string columns in a DataFrame description.

>>> df.describe(include=[object])
       object
count       3
unique      3
top         a
freq        1

Including only categorical columns from a DataFrame description.

>>> df.describe(include=['category'])
       categorical
count            3
unique           3
top              d
freq             1

Excluding numeric columns from a DataFrame description.

>>> df.describe(exclude=[np.number])
       categorical object
count            3      3
unique           3      3
top              d      a
freq             1      1

Excluding object columns from a DataFrame description.

>>> df.describe(exclude=[object])
       categorical numeric
count            3     3.0
unique           3    <NA>
top              d    <NA>
freq             1    <NA>
mean          <NA>     2.0
std           <NA>     1.0
min           <NA>     1.0
25%           <NA>     1.5
50%           <NA>     2.0
75%           <NA>     2.5
max           <NA>     3.0
diff(periods=1)

Calculate the difference between values at positions i and i - N in an array and store the output in a new array.

Notes

Diff currently only supports float and integer dtype columns with no null values.

digitize(bins, right=False)

Return the indices of the bins to which each value in series belongs.

Parameters
binsnp.array

1-D monotonically, increasing array with same type as this series.

rightbool

Indicates whether interval contains the right or left bin edge.

Returns
A new Series containing the indices.

Notes

Monotonicity of bins is assumed and not checked.

drop_duplicates(keep='first', inplace=False, ignore_index=False)

Return Series with duplicate values removed

dropna(axis=0, inplace=False, how=None)

Return a Series with null values removed.

Parameters
axis{0 or ‘index’}, default 0

There is only one axis to drop values from.

inplacebool, default False

If True, do operation inplace and return None.

howstr, optional

Not in use. Kept for compatibility.

Returns
Series

Series with null entries dropped from it.

See also

Series.isna

Indicate null values.

Series.notna

Indicate non-null values.

Series.fillna

Replace null values.

cudf.core.dataframe.DataFrame.dropna

Drop rows or columns which contain null values.

cudf.core.index.Index.dropna

Drop null indices.

Examples

>>> import cudf
>>> ser = cudf.Series([1, 2, None])
>>> ser
0       1
1       2
2    null
dtype: int64

Drop null values from a Series.

>>> ser.dropna()
0    1
1    2
dtype: int64

Keep the Series with valid entries in the same variable.

>>> ser.dropna(inplace=True)
>>> ser
0    1
1    2
dtype: int64

Empty strings are not considered null values. None is considered a null value.

>>> ser = cudf.Series(['', None, 'abc'])
>>> ser
0
1    None
2     abc
dtype: object
>>> ser.dropna()
0
2    abc
dtype: object
property dt

Accessor object for datetimelike properties of the Series values.

Returns
A Series indexed like the original Series.
Raises
TypeError if the Series does not contain datetimelike values.

Examples

>>> s.dt.hour
>>> s.dt.second
>>> s.dt.day
property dtype

dtype of the Series

property empty

Indicator whether DataFrame or Series is empty.

True if DataFrame/Series is entirely empty (no items), meaning any of the axes are of length 0.

Returns
outbool

If DataFrame/Series is empty, return True, if not return False.

Notes

If DataFrame/Series contains only null values, it is still not considered empty. See the example below.

Examples

>>> import cudf
>>> df = cudf.DataFrame({'A' : []})
>>> df
Empty DataFrame
Columns: [A]
Index: []
>>> df.empty
True

If we only have null values in our DataFrame, it is not considered empty! We will need to drop the null’s to make the DataFrame empty:

>>> df = cudf.DataFrame({'A' : [None, None]})
>>> df
      A
0  null
1  null
>>> df.empty
False
>>> df.dropna().empty
True

Non-empty and empty Series example:

>>> s = cudf.Series([1, 2, None])
>>> s
0       1
1       2
2    null
dtype: int64
>>> s.empty
False
>>> s = cudf.Series([])
>>> s
Series([], dtype: float64)
>>> s.empty
True
eq(other, fill_value=None, axis=0)

Equal to of series and other, element-wise (binary operator eq).

Parameters
otherSeries or scalar value
fill_valueNone or value

Value to fill nulls with before computation. If data in both corresponding Series locations is null the result will be null

equals(other, **kwargs)

Test whether two objects contain the same elements. This function allows two Series or DataFrames to be compared against each other to see if they have the same shape and elements. NaNs in the same location are considered equal. The column headers do not need to have the same type.

Parameters
otherSeries or DataFrame

The other Series or DataFrame to be compared with the first.

Returns
bool

True if all elements are the same in both objects, False otherwise.

Examples

>>> import cudf

Comparing Series with equals:

>>> s = cudf.Series([1, 2, 3])
>>> other = cudf.Series([1, 2, 3])
>>> s.equals(other)
True
>>> different = cudf.Series([1.5, 2, 3])
>>> s.equals(different)
False

Comparing DataFrames with equals:

>>> df = cudf.DataFrame({1: [10], 2: [20]})
>>> df
    1   2
0  10  20
>>> exactly_equal = cudf.DataFrame({1: [10], 2: [20]})
>>> exactly_equal
    1   2
0  10  20
>>> df.equals(exactly_equal)
True

For two DataFrames to compare equal, the types of column values must be equal, but the types of column labels need not:

>>> different_column_type = cudf.DataFrame({1.0: [10], 2.0: [20]})
>>> different_column_type
   1.0  2.0
0   10   20
>>> df.equals(different_column_type)
True
exp()

Get the exponential of all elements, element-wise.

Exponential is the inverse of the log function, so that x.exp().log() = x

Returns
DataFrame/Series/Index

Result of the element-wise exponential.

Examples

>>> import cudf
>>> ser = cudf.Series([-1, 0, 1, 0.32434, 0.5, -10, 100])
>>> ser
0     -1.00000
1      0.00000
2      1.00000
3      0.32434
4      0.50000
5    -10.00000
6    100.00000
dtype: float64
>>> ser.exp()
0    3.678794e-01
1    1.000000e+00
2    2.718282e+00
3    1.383117e+00
4    1.648721e+00
5    4.539993e-05
6    2.688117e+43
dtype: float64

exp operation on DataFrame:

>>> df = cudf.DataFrame({'first': [-1, -10, 0.5],
...                      'second': [0.234, 0.3, 10]})
>>> df
   first  second
0   -1.0   0.234
1  -10.0   0.300
2    0.5  10.000
>>> df.exp()
      first        second
0  0.367879      1.263644
1  0.000045      1.349859
2  1.648721  22026.465795

exp operation on Index:

>>> index = cudf.Index([-1, 0.4, 1, 0, 0.3])
>>> index
Float64Index([-1.0, 0.4, 1.0, 0.0, 0.3], dtype='float64')
>>> index.exp()
Float64Index([0.36787944117144233,  1.4918246976412703,
              2.718281828459045, 1.0,  1.3498588075760032],
            dtype='float64')
factorize(na_sentinel=- 1)

Encode the input values as integer labels

Parameters
na_sentinelnumber

Value to indicate missing category.

Returns
(labels, cats)(Series, Series)
  • labels contains the encoded values

  • cats contains the categories in order that the N-th item corresponds to the (N-1) code.

Examples

>>> import cudf
>>> s = cudf.Series(['a', 'a', 'c'])
>>> codes, uniques = s.factorize()
>>> codes
0    0
1    0
2    1
dtype: int8
>>> uniques
0    a
1    c
dtype: object
fillna(value, method=None, axis=None, inplace=False, limit=None)

Fill null values with value.

Parameters
valuescalar, Series-like or dict

Value to use to fill nulls. If Series-like, null values are filled with values in corresponding indices. A dict can be used to provide different values to fill nulls in different columns.

Returns
resultDataFrame

Copy with nulls filled.

Examples

>>> import cudf
>>> df = cudf.DataFrame({'a': [1, 2, None], 'b': [3, None, 5]})
>>> df
      a     b
0     1     3
1     2  null
2  null     5
>>> df.fillna(4)
   a  b
0  1  3
1  2  4
2  4  5
>>> df.fillna({'a': 3, 'b': 4})
   a  b
0  1  3
1  2  4
2  3  5

fillna on a Series object:

>>> ser = cudf.Series(['a', 'b', None, 'c'])
>>> ser
0       a
1       b
2    None
3       c
dtype: object
>>> ser.fillna('z')
0    a
1    b
2    z
3    c
dtype: object

fillna can also supports inplace operation:

>>> ser.fillna('z', inplace=True)
>>> ser
0    a
1    b
2    z
3    c
dtype: object
>>> df.fillna({'a': 3, 'b': 4}, inplace=True)
>>> df
a  b
0  1  3
1  2  4
2  3  5
floor()

Rounds each value downward to the largest integral value not greater than the original.

Returns a new Series.

floordiv(other, fill_value=None, axis=0)

Integer division of series and other, element-wise (binary operator floordiv).

Parameters
otherSeries or scalar value
fill_valueNone or value

Value to fill nulls with before computation. If data in both corresponding Series locations is null the result will be null

classmethod from_arrow(array)

Convert from PyArrow Array/ChunkedArray to Series.

Parameters
arrayPyArrow Array/ChunkedArray

PyArrow Object which has to be converted to cudf Series.

Returns
cudf Series
Raises
TypeError for invalid input type.

Examples

>>> import cudf
>>> import pyarrow as pa
>>> cudf.Series.from_arrow(pa.array(["a", "b", None]))
0       a
1       b
2    <NA>
dtype: object
classmethod from_categorical(categorical, codes=None)

Creates from a pandas.Categorical

If codes is defined, use it instead of categorical.codes

classmethod from_masked_array(data, mask, null_count=None)

Create a Series with null-mask. This is equivalent to:

Series(data).set_mask(mask, null_count=null_count)

Parameters
data1D array-like

The values. Null values must not be skipped. They can appear as garbage values.

mask1D array-like

The null-mask. Valid values are marked as 1; otherwise 0. The mask bit given the data index idx is computed as:

(mask[idx // 8] >> (idx % 8)) & 1
null_countint, optional

The number of null values. If None, it is calculated automatically.

classmethod from_pandas(s, nan_as_null=None)

Convert from a Pandas Series.

Parameters
sPandas Series object

A Pandas Series object which has to be converted to cuDF Series.

nan_as_nullbool, Default None

If None/True, converts np.nan values to null values. If False, leaves np.nan values as is.

Raises
TypeError for invalid input type.

Examples

>>> import cudf
>>> import pandas as pd
>>> import numpy as np
>>> data = [10, 20, 30, np.nan]
>>> pds = pd.Series(data)
>>> cudf.Series.from_pandas(pds)
0    10.0
1    20.0
2    30.0
3    null
dtype: float64
>>> cudf.Series.from_pandas(pds, nan_as_null=False)
0    10.0
1    20.0
2    30.0
3     NaN
dtype: float64
ge(other, fill_value=None, axis=0)

Greater than or equal to of series and other, element-wise (binary operator ge).

Parameters
otherSeries or scalar value
fill_valueNone or value

Value to fill nulls with before computation. If data in both corresponding Series locations is null the result will be null

groupby(by=None, group_series=None, level=None, sort=True, group_keys=True, as_index=None, dropna=True, method=None)

Group Series using a mapper or by a Series of columns.

A groupby operation involves some combination of splitting the object, applying a function, and combining the results. This can be used to group large amounts of data and compute operations on these groups.

Parameters
bymapping, function, label, or list of labels

Used to determine the groups for the groupby. If by is a function, it’s called on each value of the object’s index. If a dict or Series is passed, the Series or dict VALUES will be used to determine the groups (the Series’ values are first aligned; see .align() method). If an cupy array is passed, the values are used as-is determine the groups. A label or list of labels may be passed to group by the columns in self. Notice that a tuple is interpreted as a (single) key.

levelint, level name, or sequence of such, default None

If the axis is a MultiIndex (hierarchical), group by a particular level or levels.

as_indexbool, default True

For aggregated output, return object with group labels as the index. Only relevant for DataFrame input. as_index=False is effectively “SQL-style” grouped output.

sortbool, default True

Sort group keys. Get better performance by turning this off. Note this does not influence the order of observations within each group. Groupby preserves the order of rows within each group.

Returns
SeriesGroupBy

Returns a groupby object that contains information about the groups.

Examples

>>> ser = cudf.Series([390., 350., 30., 20.],
...                 index=['Falcon', 'Falcon', 'Parrot', 'Parrot'],
...                 name="Max Speed")
>>> ser
Falcon    390.0
Falcon    350.0
Parrot     30.0
Parrot     20.0
Name: Max Speed, dtype: float64
>>> ser.groupby(level=0).mean()
Falcon    370.0
Parrot     25.0
Name: Max Speed, dtype: float64
>>> ser.groupby(ser > 100).mean()
Max Speed
False     25.0
True     370.0
Name: Max Speed, dtype: float64
gt(other, fill_value=None, axis=0)

Greater than of series and other, element-wise (binary operator gt).

Parameters
otherSeries or scalar value
fill_valueNone or value

Value to fill nulls with before computation. If data in both corresponding Series locations is null the result will be null

property has_nulls

Indicator whether Series contains null values.

Returns
outbool

If Series has atleast one null value, return True, if not return False.

hash_encode(stop, use_name=False)

Encode column values as ints in [0, stop) using hash function.

Parameters
stopint

The upper bound on the encoding range.

use_namebool

If True then combine hashed column values with hashed column name. This is useful for when the same values in different columns should be encoded with different hashed values.

Returns
resultSeries

The encoded Series.

hash_values()

Compute the hash of values in this column.

head(n=5)

Return the first n rows. This function returns the first n rows for the object based on position. It is useful for quickly testing if your object has the right type of data in it. For negative values of n, this function returns all rows except the last n rows, equivalent to df[:-n].

Parameters
nint, default 5

Number of rows to select.

Returns
same type as caller

The first n rows of the caller object.

See also

Series.tail

Returns the last n rows.

Examples

>>> ser = cudf.Series(['alligator', 'bee', 'falcon',
... 'lion', 'monkey', 'parrot', 'shark', 'whale', 'zebra'])
>>> ser
0    alligator
1          bee
2       falcon
3         lion
4       monkey
5       parrot
6        shark
7        whale
8        zebra
dtype: object

Viewing the first 5 lines

>>> ser.head()
0    alligator
1          bee
2       falcon
3         lion
4       monkey
dtype: object

Viewing the first n lines (three in this case)

>>> ser.head(3)
0    alligator
1          bee
2       falcon
dtype: object

For negative values of n

>>> ser.head(-3)
0    alligator
1          bee
2       falcon
3         lion
4       monkey
5       parrot
dtype: object
property iloc

Select values by position.

property index

The index object

interleave_columns()

Interleave Series columns of a table into a single column.

Converts the column major table cols into a row major column.

Parameters
colsinput Table containing columns to interleave.
Returns
The interleaved columns as a single column

Examples

>>> df = DataFrame([['A1', 'A2', 'A3'], ['B1', 'B2', 'B3']])
>>> df
0    [A1, A2, A3]
1    [B1, B2, B3]
>>> df.interleave_columns()
0    A1
1    B1
2    A2
3    B2
4    A3
5    B3
property is_monotonic

Return boolean if values in the object are monotonic_increasing.

Returns
outbool
property is_monotonic_decreasing

Return boolean if values in the object are monotonic_decreasing.

Returns
outbool
property is_monotonic_increasing

Return boolean if values in the object are monotonic_increasing.

Returns
outbool
property is_unique

Return boolean if values in the object are unique.

Returns
outbool
isin(values)

Check whether values are contained in Series.

Parameters
valuesset or list-like

The sequence of values to test. Passing in a single string will raise a TypeError. Instead, turn a single string into a list of one element.

Returns
resultSeries

Series of booleans indicating if each element is in values.

Raises
TypeError

If values is a string

isna()

Identify missing values. Alias for isnull

isnull()

Identify missing values.

keys()

Return alias for index.

Returns
Index

Index of the Series.

Examples

>>> import cudf
>>> sr = cudf.Series([10, 11, 12, 13, 14, 15])
>>> sr
0    10
1    11
2    12
3    13
4    14
5    15
dtype: int64
>>> sr.keys()
RangeIndex(start=0, stop=6)
>>> sr = cudf.Series(['a', 'b', 'c'])
>>> sr
0    a
1    b
2    c
dtype: object
>>> sr.keys()
RangeIndex(start=0, stop=3)
>>> sr = cudf.Series([1, 2, 3], index=['a', 'b', 'c'])
>>> sr
a    1
b    2
c    3
dtype: int64
>>> sr.keys()
StringIndex(['a' 'b' 'c'], dtype='object')
kurt(axis=None, skipna=None, level=None, numeric_only=None, **kwargs)

Return Fisher’s unbiased kurtosis of a sample.

Kurtosis obtained using Fisher’s definition of kurtosis (kurtosis of normal == 0.0). Normalized by N-1.

Parameters
skipnabool, default True

Exclude NA/null values when computing the result.

Returns
scalar

Notes

Parameters currently not supported are axis, level and numeric_only

kurtosis(axis=None, skipna=None, level=None, numeric_only=None, **kwargs)

Return Fisher’s unbiased kurtosis of a sample.

Kurtosis obtained using Fisher’s definition of kurtosis (kurtosis of normal == 0.0). Normalized by N-1.

Parameters
skipnabool, default True

Exclude NA/null values when computing the result.

Returns
scalar

Notes

Parameters currently not supported are axis, level and numeric_only

label_encoding(cats, dtype=None, na_sentinel=- 1)

Perform label encoding

Parameters
valuessequence of input values
dtypenumpy.dtype; optional

Specifies the output dtype. If None is given, the smallest possible integer dtype (starting with np.int8) is used.

na_sentinelnumber, default -1

Value to indicate missing category.

Returns
A sequence of encoded labels with value between 0 and n-1 classes(cats)

Examples

>>> import cudf
>>> s = cudf.Series([1, 2, 3, 4, 10])
>>> s.label_encoding([2, 3])
0   -1
1    0
2    1
3   -1
4   -1
dtype: int8

na_sentinel parameter can be used to control the value when there is no encoding.

>>> s.label_encoding([2, 3], na_sentinel=10)
0    10
1     0
2     1
3    10
4    10
dtype: int8

When none of cats values exist in s, entire Series will be na_sentinel.

>>> s.label_encoding(['a', 'b', 'c'])
0   -1
1   -1
2   -1
3   -1
4   -1
dtype: int8
le(other, fill_value=None, axis=0)

Less than or equal to of series and other, element-wise (binary operator le).

Parameters
otherSeries or scalar value
fill_valueNone or value

Value to fill nulls with before computation. If data in both corresponding Series locations is null the result will be null

property loc

Select values by label.

log()

Get the natural logarithm of all elements, element-wise.

Natural logarithm is the inverse of the exp function, so that x.log().exp() = x

Returns
DataFrame/Series/Index

Result of the element-wise natural logarithm.

Examples

>>> import cudf
>>> ser = cudf.Series([-1, 0, 1, 0.32434, 0.5, -10, 100])
>>> ser
0     -1.00000
1      0.00000
2      1.00000
3      0.32434
4      0.50000
5    -10.00000
6    100.00000
dtype: float64
>>> ser.log()
0         NaN
1        -inf
2    0.000000
3   -1.125963
4   -0.693147
5         NaN
6    4.605170
dtype: float64

log operation on DataFrame:

>>> df = cudf.DataFrame({'first': [-1, -10, 0.5],
...                      'second': [0.234, 0.3, 10]})
>>> df
   first  second
0   -1.0   0.234
1  -10.0   0.300
2    0.5  10.000
>>> df.log()
      first    second
0       NaN -1.452434
1       NaN -1.203973
2 -0.693147  2.302585

log operation on Index:

>>> index = cudf.Index([10, 11, 500.0])
>>> index
Float64Index([10.0, 11.0, 500.0], dtype='float64')
>>> index.log()
Float64Index([2.302585092994046, 2.3978952727983707,
            6.214608098422191], dtype='float64')
lt(other, fill_value=None, axis=0)

Less than of series and other, element-wise (binary operator lt).

Parameters
otherSeries or scalar value
fill_valueNone or value

Value to fill nulls with before computation. If data in both corresponding Series locations is null the result will be null

mask(cond, other=None, inplace=False)

Replace values where the condition is True.

Parameters
condbool Series/DataFrame, array-like

Where cond is False, keep the original value. Where True, replace with corresponding value from other. Callables are not supported.

other: scalar, list of scalars, Series/DataFrame

Entries where cond is True are replaced with corresponding value from other. Callables are not supported. Default is None.

DataFrame expects only Scalar or array like with scalars or dataframe with same dimension as self.

Series expects only scalar or series like with same length

inplacebool, default False

Whether to perform the operation in place on the data.

Returns
Same type as caller

Examples

>>> import cudf
>>> df = cudf.DataFrame({"A":[1, 4, 5], "B":[3, 5, 8]})
>>> df.mask(df % 2 == 0, [-1, -1])
   A  B
0  1  3
1 -1  5
2  5 -1
>>> ser = cudf.Series([4, 3, 2, 1, 0])
>>> ser.mask(ser > 2, 10)
0    10
1    10
2     2
3     1
4     0
dtype: int64
>>> ser.mask(ser > 2)
0    null
1    null
2       2
3       1
4       0
dtype: int64
max(axis=None, skipna=None, dtype=None, level=None, numeric_only=None, **kwargs)

Return the maximum of the values in the Series.

Parameters
skipnabool, default True

Exclude NA/null values when computing the result.

dtypedata type

Data type to cast the result to.

Returns
scalar

Notes

Parameters currently not supported are axis, level, numeric_only.

Examples

>>> import cudf
>>> ser = cudf.Series([1, 5, 2, 4, 3])
>>> ser.max()
5
mean(axis=None, skipna=None, level=None, numeric_only=None, **kwargs)

Return the mean of the values in the series.

Parameters
skipnabool, default True

Exclude NA/null values when computing the result.

Returns
scalar

Notes

Parameters currently not supported are axis, level and numeric_only

Examples

>>> import cudf
>>> ser = cudf.Series([10, 25, 3, 25, 24, 6])
>>> ser.mean()
15.5
median(axis=None, skipna=None, level=None, numeric_only=None, **kwargs)

Return the median of the values for the requested axis.

Parameters
skipnabool, default True

Exclude NA/null values when computing the result.

Returns
scalar

Notes

Parameters currently not supported are axis, level and numeric_only

Examples

>>> import cudf
>>> ser = cudf.Series([10, 25, 3, 25, 24, 6])
>>> ser
0    10
1    25
2     3
3    25
4    24
5     6
dtype: int64
>>> ser.median()
17.0
memory_usage(index=True, deep=False)

Return the memory usage of the Series.

The memory usage can optionally include the contribution of the index and of elements of object dtype.

Parameters
indexbool, default True

Specifies whether to include the memory usage of the Series index.

deepbool, default False

If True, introspect the data deeply by interrogating object dtypes for system-level memory consumption, and include it in the returned value.

Returns
int

Bytes of memory consumed.

See also

cudf.core.dataframe.DataFrame.memory_usage

Bytes consumed by a DataFrame.

Examples

>>> s = cudf.Series(range(3), index=['a','b','c'])
>>> s.memory_usage()
48

Not including the index gives the size of the rest of the data, which is necessarily smaller:

>>> s.memory_usage(index=False)
24
min(axis=None, skipna=None, dtype=None, level=None, numeric_only=None, **kwargs)

Return the minimum of the values in the Series.

Parameters
skipnabool, default True

Exclude NA/null values when computing the result.

dtypedata type

Data type to cast the result to.

Returns
scalar

Notes

Parameters currently not supported are axis, level, numeric_only.

Examples

>>> import cudf
>>> ser = cudf.Series([1, 5, 2, 4, 3])
>>> ser.min()
1
mod(other, fill_value=None, axis=0)

Modulo of series and other, element-wise (binary operator mod).

Parameters
otherSeries or scalar value
fill_valueNone or value

Value to fill nulls with before computation. If data in both corresponding Series locations is null the result will be null

mode(dropna=True)

Return the mode(s) of the dataset.

Always returns Series even if only one value is returned.

Parameters
dropnabool, default True

Don’t consider counts of NA/NaN/NaT.

Returns
Series

Modes of the Series in sorted order.

Examples

>>> import cudf
>>> series = cudf.Series([7, 6, 5, 4, 3, 2, 1])
>>> series
0    7
1    6
2    5
3    4
4    3
5    2
6    1
dtype: int64
>>> series.mode()
0    1
1    2
2    3
3    4
4    5
5    6
6    7
dtype: int64

We can include <NA> values in mode by passing dropna=False.

>>> series = cudf.Series([7, 4, 3, 3, 7, None, None])
>>> series
0       7
1       4
2       3
3       3
4       7
5    <NA>
6    <NA>
dtype: int64
>>> series.mode()
0    3
1    7
dtype: int64
>>> series.mode(dropna=False)
0       3
1       7
2    <NA>
dtype: int64
mul(other, fill_value=None, axis=0)

Multiplication of series and other, element-wise (binary operator mul).

Parameters
otherSeries or scalar value
fill_valueNone or value

Value to fill nulls with before computation. If data in both corresponding Series locations is null the result will be null

property name

Returns name of the Series.

nans_to_nulls()

Convert nans (if any) to nulls

property ndim

Dimension of the data. Series ndim is always 1.

ne(other, fill_value=None, axis=0)

Not equal to of series and other, element-wise (binary operator ne).

Parameters
otherSeries or scalar value
fill_valueNone or value

Value to fill nulls with before computation. If data in both corresponding Series locations is null the result will be null

nlargest(n=5, keep='first')

Returns a new Series of the n largest element.

notna()

Identify non-missing values. Alias for notnull.

notnull()

Identify non-missing values.

nsmallest(n=5, keep='first')

Returns a new Series of the n smallest element.

property null_count

Number of null values

property nullable

A boolean indicating whether a null-mask is needed

property nullmask

The gpu buffer for the null-mask

nunique(method='sort', dropna=True)

Returns the number of unique values of the Series: approximate version, and exact version to be moved to libgdf

one_hot_encoding(cats, dtype='float64')

Perform one-hot-encoding

Parameters
catssequence of values

values representing each category.

dtypenumpy.dtype

specifies the output dtype.

Returns
Sequence

A sequence of new series for each category. Its length is determined by the length of cats.

pow(other, fill_value=None, axis=0)

Exponential power of series and other, element-wise (binary operator pow).

Parameters
otherSeries or scalar value
fill_valueNone or value

Value to fill nulls with before computation. If data in both corresponding Series locations is null the result will be null

prod(axis=None, skipna=None, dtype=None, level=None, numeric_only=None, min_count=0, **kwargs)

Return product of the values in the series

Parameters
skipnabool, default True

Exclude NA/null values when computing the result.

dtypedata type

Data type to cast the result to.

min_countint, default 0

The required number of valid values to perform the operation. If fewer than min_count non-NA values are present the result will be NA.

The default being 0. This means the sum of an all-NA or empty Series is 0, and the product of an all-NA or empty Series is 1.

Returns
scalar

Notes

Parameters currently not supported are axis, level, numeric_only.

Examples

>>> import cudf
>>> ser = cudf.Series([1, 5, 2, 4, 3])
>>> ser.prod()
120
product(axis=None, skipna=None, dtype=None, level=None, numeric_only=None, min_count=0, **kwargs)

Return product of the values in the Series.

Parameters
skipnabool, default True

Exclude NA/null values when computing the result.

dtypedata type

Data type to cast the result to.

min_countint, default 0

The required number of valid values to perform the operation. If fewer than min_count non-NA values are present the result will be NA.

The default being 0. This means the sum of an all-NA or empty Series is 0, and the product of an all-NA or empty Series is 1.

Returns
scalar

Notes

Parameters currently not supported are axis, level, numeric_only.

Examples

>>> import cudf
>>> ser = cudf.Series([1, 5, 2, 4, 3])
>>> ser.product()
120
quantile(q=0.5, interpolation='linear', exact=True, quant_index=True)

Return values at the given quantile.

Parameters
qfloat or array-like, default 0.5 (50% quantile)

0 <= q <= 1, the quantile(s) to compute

interpolation{’linear’, ‘lower’, ‘higher’, ‘midpoint’, ‘nearest’}

This optional parameter specifies the interpolation method to use, when the desired quantile lies between two data points i and j:

columnslist of str

List of column names to include.

exactboolean

Whether to use approximate or exact quantile algorithm.

quant_indexboolean

Whether to use the list of quantiles as index.

Returns
float or Series

If q is an array, a Series will be returned where the index is q and the values are the quantiles, otherwise a float will be returned.

radd(other, fill_value=None, axis=0)

Addition of series and other, element-wise (binary operator radd).

Parameters
otherSeries or scalar value
fill_valueNone or value

Value to fill nulls with before computation. If data in both corresponding Series locations is null the result will be null

rank(axis=0, method='average', numeric_only=None, na_option='keep', ascending=True, pct=False)

Compute numerical data ranks (1 through n) along axis. By default, equal values are assigned a rank that is the average of the ranks of those values.

Parameters
axis{0 or ‘index’, 1 or ‘columns’}, default 0

Index to direct ranking.

method{‘average’, ‘min’, ‘max’, ‘first’, ‘dense’}, default ‘average’

How to rank the group of records that have the same value (i.e. ties): * average: average rank of the group * min: lowest rank in the group * max: highest rank in the group * first: ranks assigned in order they appear in the array * dense: like ‘min’, but rank always increases by 1 between groups.

numeric_onlybool, optional

For DataFrame objects, rank only numeric columns if set to True.

na_option{‘keep’, ‘top’, ‘bottom’}, default ‘keep’

How to rank NaN values: * keep: assign NaN rank to NaN values * top: assign smallest rank to NaN values if ascending * bottom: assign highest rank to NaN values if ascending.

ascendingbool, default True

Whether or not the elements should be ranked in ascending order.

pctbool, default False

Whether or not to display the returned rankings in percentile form.

Returns
same type as caller

Return a Series or DataFrame with data ranks as values.

reindex(index=None, copy=True)

Return a Series that conforms to a new index

Parameters
indexIndex, Series-convertible, default None
copyboolean, default True
Returns
A new Series that conforms to the supplied index
rename(index=None, copy=True)

Alter Series name

Change Series.name with a scalar value

Parameters
indexScalar, optional

Scalar to alter the Series.name attribute

copyboolean, default True

Also copy underlying data

Returns
Series

Notes

Difference from pandas:
  • Supports scalar values only for changing name attribute

  • Not supporting : inplace, level

repeat(repeats, axis=None)

Repeats elements consecutively.

Returns a new object of caller type(DataFrame/Series/Index) where each element of the current object is repeated consecutively a given number of times.

Parameters
repeatsint, or array of ints

The number of repetitions for each element. This should be a non-negative integer. Repeating 0 times will return an empty object.

Returns
Series/DataFrame/Index

A newly created object of same type as caller with repeated elements.

Examples

>>> import cudf
>>> df = cudf.DataFrame({'a': [1, 2, 3], 'b': [10, 20, 30]})
>>> df
   a   b
0  1  10
1  2  20
2  3  30
>>> df.repeat(3)
   a   b
0  1  10
0  1  10
0  1  10
1  2  20
1  2  20
1  2  20
2  3  30
2  3  30
2  3  30

Repeat on Series

>>> s = cudf.Series([0, 2])
>>> s
0    0
1    2
dtype: int64
>>> s.repeat([3, 4])
0    0
0    0
0    0
1    2
1    2
1    2
1    2
dtype: int64
>>> s.repeat(2)
0    0
0    0
1    2
1    2
dtype: int64

Repeat on Index

>>> index = cudf.Index([10, 22, 33, 55])
>>> index
Int64Index([10, 22, 33, 55], dtype='int64')
>>> index.repeat(5)
Int64Index([10, 10, 10, 10, 10, 22, 22, 22, 22, 22, 33,
            33, 33, 33, 33, 55, 55, 55, 55, 55],
        dtype='int64')
replace(to_replace=None, value=None, inplace=False, limit=None, regex=False, method=None)

Replace values given in to_replace with value.

Parameters
to_replacenumeric, str or list-like

Value(s) to replace.

  • numeric or str:
    • values equal to to_replace will be replaced with value

  • list of numeric or str:
    • If value is also list-like, to_replace and value must be of same length.

valuenumeric, str, list-like, or dict

Value(s) to replace to_replace with.

inplacebool, default False

If True, in place.

Returns
resultSeries

Series after replacement. The mask and index are preserved.

See also

Series.fillna

Notes

Parameters that are currently not supported are: limit, regex, method

reset_index(drop=False, inplace=False)

Reset index to RangeIndex

reverse()

Reverse the Series

rfloordiv(other, fill_value=None, axis=0)

Integer division of series and other, element-wise (binary operator rfloordiv).

Parameters
otherSeries or scalar value
fill_valueNone or value

Value to fill nulls with before computation. If data in both corresponding Series locations is null the result will be null

Returns
Series

Result of the arithmetic operation.

Examples

>>> import cudf
>>> s = cudf.Series([1, 2, 10, 17])
>>> s
0     1
1     2
2    10
3    17
dtype: int64
>>> s.rfloordiv(100)
0    100
1     50
2     10
3      5
dtype: int64
>>> s = cudf.Series([10, 20, None])
>>> s
0      10
1      20
2    null
dtype: int64
>>> s.rfloordiv(200)
0      20
1      10
2    null
dtype: int64
>>> s.rfloordiv(200, fill_value=2)
0     20
1     10
2    100
dtype: int64
rmod(other, fill_value=None, axis=0)

Modulo of series and other, element-wise (binary operator rmod).

Parameters
otherSeries or scalar value
fill_valueNone or value

Value to fill nulls with before computation. If data in both corresponding Series locations is null the result will be null

rmul(other, fill_value=None, axis=0)

Multiplication of series and other, element-wise (binary operator rmul).

Parameters
otherSeries or scalar value
fill_valueNone or value

Value to fill nulls with before computation. If data in both corresponding Series locations is null the result will be null

rolling(window, min_periods=None, center=False, axis=0, win_type=None)

Rolling window calculations.

Parameters
windowint or offset

Size of the window, i.e., the number of observations used to calculate the statistic. For datetime indexes, an offset can be provided instead of an int. The offset must be convertible to a timedelta. As opposed to a fixed window size, each window will be sized to accommodate observations within the time period specified by the offset.

min_periodsint, optional

The minimum number of observations in the window that are required to be non-null, so that the result is non-null. If not provided or None, min_periods is equal to the window size.

centerbool, optional

If True, the result is set at the center of the window. If False (default), the result is set at the right edge of the window.

Returns
Rolling object.

Examples

>>> import cudf
>>> a = cudf.Series([1, 2, 3, None, 4])

Rolling sum with window size 2.

>>> print(a.rolling(2).sum())
0
1    3
2    5
3
4
dtype: int64

Rolling sum with window size 2 and min_periods 1.

>>> print(a.rolling(2, min_periods=1).sum())
0    1
1    3
2    5
3    3
4    4
dtype: int64

Rolling count with window size 3.

>>> print(a.rolling(3).count())
0    1
1    2
2    3
3    2
4    2
dtype: int64

Rolling count with window size 3, but with the result set at the center of the window.

>>> print(a.rolling(3, center=True).count())
0    2
1    3
2    2
3    2
4    1 dtype: int64

Rolling max with variable window size specified by an offset; only valid for datetime index.

>>> a = cudf.Series(
...     [1, 9, 5, 4, np.nan, 1],
...     index=[
...         pd.Timestamp('20190101 09:00:00'),
...         pd.Timestamp('20190101 09:00:01'),
...         pd.Timestamp('20190101 09:00:02'),
...         pd.Timestamp('20190101 09:00:04'),
...         pd.Timestamp('20190101 09:00:07'),
...         pd.Timestamp('20190101 09:00:08')
...     ]
... )
>>> print(a.rolling('2s').max())
2019-01-01T09:00:00.000    1
2019-01-01T09:00:01.000    9
2019-01-01T09:00:02.000    9
2019-01-01T09:00:04.000    4
2019-01-01T09:00:07.000
2019-01-01T09:00:08.000    1
dtype: int64

Apply custom function on the window with the apply method

>>> import numpy as np
>>> import math
>>> b = cudf.Series([16, 25, 36, 49, 64, 81], dtype=np.float64)
>>> def some_func(A):
...     b = 0
...     for a in A:
...         b = b + math.sqrt(a)
...     return b
...
>>> print(b.rolling(3, min_periods=1).apply(some_func))
0     4.0
1     9.0
2    15.0
3    18.0
4    21.0
5    24.0
dtype: float64

And this also works for window rolling set by an offset

>>> import pandas as pd
>>> c = cudf.Series(
...     [16, 25, 36, 49, 64, 81],
...     index=[
...          pd.Timestamp('20190101 09:00:00'),
...          pd.Timestamp('20190101 09:00:01'),
...          pd.Timestamp('20190101 09:00:02'),
...          pd.Timestamp('20190101 09:00:04'),
...          pd.Timestamp('20190101 09:00:07'),
...          pd.Timestamp('20190101 09:00:08')
...      ],
...     dtype=np.float64
... )
>>> print(c.rolling('2s').apply(some_func))
2019-01-01T09:00:00.000     4.0
2019-01-01T09:00:01.000     9.0
2019-01-01T09:00:02.000    11.0
2019-01-01T09:00:04.000     7.0
2019-01-01T09:00:07.000     8.0
2019-01-01T09:00:08.000    17.0
dtype: float64
round(decimals=0)

Round a Series to a configurable number of decimal places.

rpow(other, fill_value=None, axis=0)

Exponential power of series and other, element-wise (binary operator rpow).

Parameters
otherSeries or scalar value
fill_valueNone or value

Value to fill nulls with before computation. If data in both corresponding Series locations is null the result will be null

rsub(other, fill_value=None, axis=0)

Subtraction of series and other, element-wise (binary operator rsub).

Parameters
otherSeries or scalar value
fill_valueNone or value

Value to fill nulls with before computation. If data in both corresponding Series locations is null the result will be null

rtruediv(other, fill_value=None, axis=0)

Floating division of series and other, element-wise (binary operator rtruediv).

Parameters
otherSeries or scalar value
fill_valueNone or value

Value to fill nulls with before computation. If data in both corresponding Series locations is null the result will be null

sample(n=None, frac=None, replace=False, weights=None, random_state=None, axis=None, keep_index=True)

Return a random sample of items from an axis of object.

You can use random_state for reproducibility.

Parameters
nint, optional

Number of items from axis to return. Cannot be used with frac. Default = 1 if frac = None.

fracfloat, optional

Fraction of axis items to return. Cannot be used with n.

replacebool, default False

Allow or disallow sampling of the same row more than once. replace == True is not yet supported for axis = 1/”columns”

weightsstr or ndarray-like, optional

Only supported for axis=1/”columns”

random_stateint, numpy RandomState or None, default None

Seed for the random number generator (if int), or None. If None, a random seed will be chosen. if RandomState, seed will be extracted from current state.

axis{0 or ‘index’, 1 or ‘columns’, None}, default None

Axis to sample. Accepts axis number or name. Default is stat axis for given data type (0 for Series and DataFrames). Series and Index doesn’t support axis=1.

Returns
Series or DataFrame or Index

A new object of same type as caller containing n items randomly sampled from the caller object.

Examples

>>> import cudf as cudf
>>> df = cudf.DataFrame({"a":{1, 2, 3, 4, 5}})
>>> df.sample(3)
   a
1  2
3  4
0  1
>>> sr = cudf.Series([1, 2, 3, 4, 5])
>>> sr.sample(10, replace=True)
1    4
3    1
2    4
0    5
0    1
4    5
4    1
0    2
0    3
3    2
dtype: int64
>>> df = cudf.DataFrame(
... {"a":[1, 2], "b":[2, 3], "c":[3, 4], "d":[4, 5]})
>>> df.sample(2, axis=1)
   a  c
0  1  3
1  2  4
scale()

Scale values to [0, 1] in float64

scatter_by_map(map_index, map_size=None, keep_index=True, **kwargs)

Scatter to a list of dataframes.

Uses map_index to determine the destination of each row of the original DataFrame.

Parameters
map_indexSeries, str or list-like

Scatter assignment for each row

map_sizeint

Length of output list. Must be >= uniques in map_index

keep_indexbool

Conserve original index values for each row

Returns
A list of cudf.DataFrame objects.
searchsorted(values, side='left', ascending=True, na_position='last')

Find indices where elements should be inserted to maintain order

Parameters
valueFrame (Shape must be consistent with self)

Values to be hypothetically inserted into Self

sidestr {‘left’, ‘right’} optional, default ‘left‘

If ‘left’, the index of the first suitable location found is given If ‘right’, return the last such index

ascendingbool optional, default True

Sorted Frame is in ascending order (otherwise descending)

na_positionstr {‘last’, ‘first’} optional, default ‘last‘

Position of null values in sorted order

Returns
1-D cupy array of insertion points

Examples

>>> s = cudf.Series([1, 2, 3])
>>> s.searchsorted(4)
3
>>> s.searchsorted([0, 4])
array([0, 3], dtype=int32)
>>> s.searchsorted([1, 3], side='left')
array([0, 2], dtype=int32)
>>> s.searchsorted([1, 3], side='right')
array([1, 3], dtype=int32)

If the values are not monotonically sorted, wrong locations may be returned:

>>> s = cudf.Series([2, 1, 3])
>>> s.searchsorted(1)
0   # wrong result, correct would be 1
>>> df = cudf.DataFrame({'a': [1, 3, 5, 7], 'b': [10, 12, 14, 16]})
>>> df
   a   b
0  1  10
1  3  12
2  5  14
3  7  16
>>> values_df = cudf.DataFrame({'a': [0, 2, 5, 6],
... 'b': [10, 11, 13, 15]})
>>> values_df
   a   b
0  0  10
1  2  17
2  5  13
3  6  15
>>> df.searchsorted(values_df, ascending=False)
array([4, 4, 4, 0], dtype=int32)
set_index(index)

Returns a new Series with a different index.

Parameters
indexIndex, Series-convertible

the new index or values for the new index

set_mask(mask, null_count=None)

Create new Series by setting a mask array.

This will override the existing mask. The returned Series will reference the same data buffer as this Series.

Parameters
mask1D array-like

The null-mask. Valid values are marked as 1; otherwise 0. The mask bit given the data index idx is computed as:

(mask[idx // 8] >> (idx % 8)) & 1
null_countint, optional

The number of null values. If None, it is calculated automatically.

property shape

Returns a tuple representing the dimensionality of the Series.

shift(periods=1, freq=None, axis=0, fill_value=None)

Shift values by periods positions.

sin()

Get Trigonometric sine, element-wise.

Returns
DataFrame/Series/Index

Result of the trigonometric operation.

Examples

>>> import cudf
>>> ser = cudf.Series([0.0, 0.32434, 0.5, 45, 90, 180, 360])
>>> ser
0      0.00000
1      0.32434
2      0.50000
3     45.00000
4     90.00000
5    180.00000
6    360.00000
dtype: float64
>>> ser.sin()
0    0.000000
1    0.318683
2    0.479426
3    0.850904
4    0.893997
5   -0.801153
6    0.958916
dtype: float64

sin operation on DataFrame:

>>> df = cudf.DataFrame({'first': [0.0, 5, 10, 15],
...                      'second': [100.0, 360, 720, 300]})
>>> df
   first  second
0    0.0   100.0
1    5.0   360.0
2   10.0   720.0
3   15.0   300.0
>>> df.sin()
      first    second
0  0.000000 -0.506366
1 -0.958924  0.958916
2 -0.544021 -0.544072
3  0.650288 -0.999756

sin operation on Index:

>>> index = cudf.Index([-0.4, 100, -180, 90])
>>> index
Float64Index([-0.4, 100.0, -180.0, 90.0], dtype='float64')
>>> index.sin()
Float64Index([-0.3894183423086505, -0.5063656411097588,
            0.8011526357338306, 0.8939966636005579],
            dtype='float64')
property size

Return the number of elements in the underlying data.

Returns
sizeSize of the DataFrame / Index / Series / MultiIndex

Examples

Size of an empty dataframe is 0.

>>> import cudf
>>> df = cudf.DataFrame()
>>> df
Empty DataFrame
Columns: []
Index: []
>>> df.size
0
>>> df = cudf.DataFrame(index=[1, 2, 3])
>>> df
Empty DataFrame
Columns: []
Index: [1, 2, 3]
>>> df.size
0

DataFrame with values

>>> df = cudf.DataFrame({'a': [10, 11, 12],
...         'b': ['hello', 'rapids', 'ai']})
>>> df
    a       b
0  10   hello
1  11  rapids
2  12      ai
>>> df.size
6
>>> df.index
RangeIndex(start=0, stop=3)
>>> df.index.size
3

Size of an Index

>>> index = cudf.Index([])
>>> index
Float64Index([], dtype='float64')
>>> index.size
0
>>> index = cudf.Index([1, 2, 3, 10])
>>> index
Int64Index([1, 2, 3, 10], dtype='int64')
>>> index.size
4

Size of a MultiIndex

>>> midx = cudf.MultiIndex(
...                 levels=[["a", "b", "c", None], ["1", None, "5"]],
...                 codes=[[0, 0, 1, 2, 3], [0, 2, 1, 1, 0]],
...                 names=["x", "y"],
...             )
>>> midx
MultiIndex(levels=[0       a
1       b
2       c
3    None
dtype: object, 0       1
1    None
2       5
dtype: object],
codes=   x  y
0  0  0
1  0  2
2  1  1
3  2  1
4  3  0)
>>> midx.size
5
skew(axis=None, skipna=None, level=None, numeric_only=None, **kwargs)

Return unbiased Fisher-Pearson skew of a sample.

Parameters
skipnabool, default True

Exclude NA/null values when computing the result.

Returns
scalar

Notes

Parameters currently not supported are axis, level and numeric_only

sort_index(ascending=True)

Sort by the index.

sort_values(axis=0, ascending=True, inplace=False, kind='quicksort', na_position='last', ignore_index=False)

Sort by the values.

Sort a Series in ascending or descending order by some criterion.

Parameters
ascendingbool, default True

If True, sort values in ascending order, otherwise descending.

na_position{‘first’, ‘last’}, default ‘last’

‘first’ puts nulls at the beginning, ‘last’ puts nulls at the end.

ignore_indexbool, default False

If True, index will not be sorted.

Returns
sorted_objcuDF Series

Notes

Difference from pandas:
  • Not supporting: inplace, kind

Examples

>>> import cudf
>>> s = cudf.Series([1, 5, 2, 4, 3])
>>> s.sort_values()
0    1
2    2
4    3
3    4
1    5
sqrt()

Get the non-negative square-root of all elements, element-wise.

Returns
DataFrame/Series/Index

Result of the non-negative square-root of each element.

Examples

>>> import cudf
>>> import cudf
>>> ser = cudf.Series([10, 25, 81, 1.0, 100])
>>> ser
0     10.0
1     25.0
2     81.0
3      1.0
4    100.0
dtype: float64
>>> ser.sqrt()
0     3.162278
1     5.000000
2     9.000000
3     1.000000
4    10.000000
dtype: float64

sqrt operation on DataFrame:

>>> df = cudf.DataFrame({'first': [-10.0, 100, 625],
...                      'second': [1, 2, 0.4]})
>>> df
   first  second
0  -10.0     1.0
1  100.0     2.0
2  625.0     0.4
>>> df.sqrt()
   first    second
0    NaN  1.000000
1   10.0  1.414214
2   25.0  0.632456

sqrt operation on Index:

>>> index = cudf.Index([-10.0, 100, 625])
>>> index
Float64Index([-10.0, 100.0, 625.0], dtype='float64')
>>> index.sqrt()
Float64Index([nan, 10.0, 25.0], dtype='float64')
std(axis=None, skipna=None, level=None, ddof=1, numeric_only=None, **kwargs)

Return sample standard deviation of the Series.

Normalized by N-1 by default. This can be changed using the ddof argument

Parameters
skipnabool, default True

Exclude NA/null values. If an entire row/column is NA, the result will be NA.

ddofint, default 1

Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements.

Returns
scalar

Notes

Parameters currently not supported are axis, level and numeric_only

property str

Vectorized string functions for Series and Index.

This mimics pandas df.str interface. nulls stay null unless handled otherwise by a particular method. Patterned after Python’s string methods, with some inspiration from R’s stringr package.

sub(other, fill_value=None, axis=0)

Subtraction of series and other, element-wise (binary operator sub).

Parameters
otherSeries or scalar value
fill_valueNone or value

Value to fill nulls with before computation. If data in both corresponding Series locations is null the result will be null

sum(axis=None, skipna=None, dtype=None, level=None, numeric_only=None, min_count=0, **kwargs)

Return sum of the values in the Series.

Parameters
skipnabool, default True

Exclude NA/null values when computing the result.

dtypedata type

Data type to cast the result to.

min_countint, default 0

The required number of valid values to perform the operation. If fewer than min_count non-NA values are present the result will be NA.

The default being 0. This means the sum of an all-NA or empty Series is 0, and the product of an all-NA or empty Series is 1.

Returns
scalar

Notes

Parameters currently not supported are axis, level, numeric_only.

Examples

>>> import cudf
>>> ser = cudf.Series([1, 5, 2, 4, 3])
>>> ser.sum()
15
tail(n=5)

Returns the last n rows as a new Series

Examples

>>> import cudf
>>> ser = cudf.Series([4, 3, 2, 1, 0])
>>> print(ser.tail(2))
3    1
4    0
take(indices, keep_index=True)

Return Series by taking values from the corresponding indices.

tan()

Get Trigonometric tangent, element-wise.

Returns
DataFrame/Series/Index

Result of the trigonometric operation.

Examples

>>> import cudf
>>> ser = cudf.Series([0.0, 0.32434, 0.5, 45, 90, 180, 360])
>>> ser
0      0.00000
1      0.32434
2      0.50000
3     45.00000
4     90.00000
5    180.00000
6    360.00000
dtype: float64
>>> ser.tan()
0    0.000000
1    0.336213
2    0.546302
3    1.619775
4   -1.995200
5    1.338690
6   -3.380140
dtype: float64

tan operation on DataFrame:

>>> df = cudf.DataFrame({'first': [0.0, 5, 10, 15],
...                      'second': [100.0, 360, 720, 300]})
>>> df
   first  second
0    0.0   100.0
1    5.0   360.0
2   10.0   720.0
3   15.0   300.0
>>> df.tan()
      first     second
0  0.000000  -0.587214
1 -3.380515  -3.380140
2  0.648361   0.648446
3 -0.855993  45.244742

tan operation on Index:

>>> index = cudf.Index([-0.4, 100, -180, 90])
>>> index
Float64Index([-0.4, 100.0, -180.0, 90.0], dtype='float64')
>>> index.tan()
Float64Index([-0.4227932187381618,  -0.587213915156929,
            -1.3386902103511544, -1.995200412208242],
            dtype='float64')
tile(count)

Repeats the rows from self DataFrame count times to form a new DataFrame.

Parameters
selfinput Table containing columns to interleave.
countNumber of times to tile “rows”. Must be non-negative.
Returns
The table containing the tiled “rows”.

Examples

>>> df  = Dataframe([[8, 4, 7], [5, 2, 3]])
>>> count = 2
>>> df.tile(df, count)
   0  1  2
0  8  4  7
1  5  2  3
0  8  4  7
1  5  2  3
to_array(fillna=None)

Get a dense numpy array for the data.

Parameters
fillnastr or None

Defaults to None, which will skip null values. If it equals “pandas”, null values are filled with NaNs. Non integral dtype is promoted to np.float64.

Notes

If fillna is None, null values are skipped. Therefore, the output size could be smaller.

to_arrow()

Convert Series to a PyArrow Array.

Returns
PyArrow Array

Examples

>>> import cudf
>>> sr = cudf.Series(["a", "b", None])
>>> sr.to_arrow()
<pyarrow.lib.StringArray object at 0x7f796b0e7600>
[
  "a",
  "b",
  null
]
to_dlpack()

Converts a cuDF object into a DLPack tensor.

DLPack is an open-source memory tensor structure: dmlc/dlpack.

This function takes a cuDF object and converts it to a PyCapsule object which contains a pointer to a DLPack tensor. This function deep copies the data into the DLPack tensor from the cuDF object.

Parameters
cudf_objDataFrame, Series, Index, or Column
Returns
pycapsule_objPyCapsule

Output DLPack tensor pointer which is encapsulated in a PyCapsule object.

to_frame(name=None)

Convert Series into a DataFrame

Parameters
namestr, default None

Name to be used for the column

Returns
DataFrame

cudf DataFrame

to_gpu_array(fillna=None)

Get a dense numba device array for the data.

Parameters
fillnastr or None

See fillna in .to_array.

Notes

if fillna is None, null values are skipped. Therefore, the output size could be smaller.

to_hdf(path_or_buf, key, *args, **kwargs)

Write the contained data to an HDF5 file using HDFStore.

Hierarchical Data Format (HDF) is self-describing, allowing an application to interpret the structure and contents of a file with no outside information. One HDF file can hold a mix of related objects which can be accessed as a group or as individual objects.

In order to add another DataFrame or Series to an existing HDF file please use append mode and a different a key.

For more information see the user guide.

Parameters
path_or_bufstr or pandas.HDFStore

File path or HDFStore object.

keystr

Identifier for the group in the store.

mode{‘a’, ‘w’, ‘r+’}, default ‘a’

Mode to open file:

  • ‘w’: write, a new file is created (an existing file with the same name would be deleted).

  • ‘a’: append, an existing file is opened for reading and writing, and if the file does not exist it is created.

  • ‘r+’: similar to ‘a’, but the file must already exist.

format{‘fixed’, ‘table’}, default ‘fixed’

Possible values:

  • ‘fixed’: Fixed format. Fast writing/reading. Not-appendable, nor searchable.

  • ‘table’: Table format. Write as a PyTables Table structure which may perform worse but allow more flexible operations like searching / selecting subsets of the data.

appendbool, default False

For Table formats, append the input data to the existing.

data_columnslist of columns or True, optional

List of columns to create as indexed data columns for on-disk queries, or True to use all columns. By default only the axes of the object are indexed. See Query via Data Columns. Applicable only to format=’table’.

complevel{0-9}, optional

Specifies a compression level for data. A value of 0 disables compression.

complib{‘zlib’, ‘lzo’, ‘bzip2’, ‘blosc’}, default ‘zlib’

Specifies the compression library to be used. As of v0.20.2 these additional compressors for Blosc are supported (default if no compressor specified: ‘blosc:blosclz’): {‘blosc:blosclz’, ‘blosc:lz4’, ‘blosc:lz4hc’, ‘blosc:snappy’, ‘blosc:zlib’, ‘blosc:zstd’}. Specifying a compression library which is not available issues a ValueError.

fletcher32bool, default False

If applying compression use the fletcher32 checksum.

dropnabool, default False

If true, ALL nan rows will not be written to store.

errorsstr, default ‘strict’

Specifies how encoding and decoding errors are to be handled. See the errors argument for open() for a full list of options.

See also

cudf.io.hdf.read_hdf

Read from HDF file.

cudf.io.parquet.to_parquet

Write a DataFrame to the binary parquet format.

cudf.io.feather.to_feather

Write out feather-format for DataFrames.

to_json(path_or_buf=None, *args, **kwargs)

Convert the cuDF object to a JSON string. Note nulls and NaNs will be converted to null and datetime objects will be converted to UNIX timestamps.

Parameters
path_or_bufstring or file handle, optional

File path or object. If not specified, the result is returned as a string.

orientstring

Indication of expected JSON string format.

  • Series
    • default is ‘index’

    • allowed values are: {‘split’,’records’,’index’,’table’}

  • DataFrame
    • default is ‘columns’

    • allowed values are: {‘split’,’records’,’index’,’columns’,’values’,’table’}

  • The format of the JSON string
    • ‘split’ : dict like {‘index’ -> [index], ‘columns’ -> [columns], ‘data’ -> [values]}

    • ‘records’ : list like [{column -> value}, … , {column -> value}]

    • ‘index’ : dict like {index -> {column -> value}}

    • ‘columns’ : dict like {column -> {index -> value}}

    • ‘values’ : just the values array

    • ‘table’ : dict like {‘schema’: {schema}, ‘data’: {data}} describing the data, and the data component is like orient='records'.

date_format{None, ‘epoch’, ‘iso’}

Type of date conversion. ‘epoch’ = epoch milliseconds, ‘iso’ = ISO8601. The default depends on the orient. For orient='table', the default is ‘iso’. For all other orients, the default is ‘epoch’.

double_precisionint, default 10

The number of decimal places to use when encoding floating point values.

force_asciibool, default True

Force encoded string to be ASCII.

date_unitstring, default ‘ms’ (milliseconds)

The time unit to encode to, governs timestamp and ISO8601 precision. One of ‘s’, ‘ms’, ‘us’, ‘ns’ for second, millisecond, microsecond, and nanosecond respectively.

default_handlercallable, default None

Handler to call if object cannot otherwise be converted to a suitable format for JSON. Should receive a single argument which is the object to convert and return a serializable object.

linesbool, default False

If ‘orient’ is ‘records’ write out line delimited json format. Will throw ValueError if incorrect ‘orient’ since others are not list like.

compression{‘infer’, ‘gzip’, ‘bz2’, ‘zip’, ‘xz’, None}

A string representing the compression to use in the output file, only used when the first argument is a filename. By default, the compression is inferred from the filename.

indexbool, default True

Whether to include the index values in the JSON string. Not including the index (index=False) is only supported when orient is ‘split’ or ‘table’.

to_pandas(index=True, **kwargs)

Convert to a Pandas Series.

Parameters
indexBoolean, Default True

If index is True, converts the index of cudf.Series and sets it to the pandas.Series. If index is False, no index conversion is performed and pandas.Series will assign a default index.

Examples

>>> import cudf
>>> ser = cudf.Series([-3, 2, 0])
>>> pds = ser.to_pandas()
>>> pds
0   -3
1    2
2    0
dtype: int64
>>> type(pds)
<class 'pandas.core.series.Series'>
to_string()

Convert to string

Uses Pandas formatting internals to produce output identical to Pandas. Use the Pandas formatting settings directly in Pandas to control cuDF output.

truediv(other, fill_value=None, axis=0)

Floating division of series and other, element-wise (binary operator truediv).

Parameters
otherSeries or scalar value
fill_valueNone or value

Value to fill nulls with before computation. If data in both corresponding Series locations is null the result will be null

unique()

Returns unique values of this Series.

property valid_count

Number of non-null values

value_counts(normalize=False, sort=True, ascending=False, bins=None, dropna=True)

Return a Series containing counts of unique values.

The resulting object will be in descending order so that the first element is the most frequently-occurring element. Excludes NA values by default.

Parameters
normalizebool, default False

If True then the object returned will contain the relative frequencies of the unique values.

sortbool, default True

Sort by frequencies.

ascendingbool, default False

Sort in ascending order.

binsint, optional

Rather than count values, group them into half-open bins, works with numeric data. This Parameter is not yet supported.

dropnabool, default True

Don’t include counts of NaN and None.

Returns
resultSeries contanining counts of unique values.

See also

Series.count

Number of non-NA elements in a Series.

cudf.core.dataframe.DataFrame.count

Number of non-NA elements in a DataFrame.

Examples

>>> import cudf
>>> sr = cudf.Series([1.0, 2.0, 2.0, 3.0, 3.0, 3.0, None])
>>> sr
0     1.0
1     2.0
2     2.0
3     3.0
4     3.0
5     3.0
6    <NA>
dtype: float64
>>> sr.value_counts()
3.0    3
2.0    2
1.0    1
dtype: int32

The order of the counts can be changed by passing ascending=True:

>>> sr.value_counts(ascending=True)
1.0    1
2.0    2
3.0    3
dtype: int32

With normalize set to True, returns the relative frequency by dividing all values by the sum of values.

>>> sr.value_counts(normalize=True)
3.0    0.500000
2.0    0.333333
1.0    0.166667
dtype: float64

To include NA value counts, pass dropna=False:

>>> sr = cudf.Series([1.0, 2.0, 2.0, 3.0, None, 3.0, 3.0, None])
>>> sr
0     1.0
1     2.0
2     2.0
3     3.0
4    <NA>
5     3.0
6     3.0
7    <NA>
dtype: float64
>>> sr.value_counts(dropna=False)
3.0     3
2.0     2
<NA>    2
1.0     1
dtype: int32
property values

Return a CuPy representation of the Series.

Only the values in the Series will be returned.

Returns
outcupy.ndarray

The values of the Series.

Examples

>>> import cudf
>>> ser = cudf.Series([1, -10, 100, 20])
>>> ser.values
array([  1, -10, 100,  20])
>>> type(ser.values)
<class 'cupy.core.core.ndarray'>
property values_host

Return a numpy representation of the Series.

Only the values in the Series will be returned.

Returns
outnumpy.ndarray

The values of the Series.

Examples

>>> import cudf
>>> ser = cudf.Series([1, -10, 100, 20])
>>> ser.values_host
array([  1, -10, 100,  20])
>>> type(ser.values_host)
<class 'numpy.ndarray'>
values_to_string(nrows=None)

Returns a list of string for each element.

var(axis=None, skipna=None, level=None, ddof=1, numeric_only=None, **kwargs)

Return unbiased variance of the Series.

Normalized by N-1 by default. This can be changed using the ddof argument

Parameters
skipnabool, default True

Exclude NA/null values. If an entire row/column is NA, the result will be NA.

ddofint, default 1

Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements.

Returns
scalar

Notes

Parameters currently not supported are axis, level and numeric_only

where(cond, other=None, inplace=False)

Replace values where the condition is False.

Parameters
condbool Series/DataFrame, array-like

Where cond is True, keep the original value. Where False, replace with corresponding value from other. Callables are not supported.

other: scalar, list of scalars, Series/DataFrame

Entries where cond is False are replaced with corresponding value from other. Callables are not supported. Default is None.

DataFrame expects only Scalar or array like with scalars or dataframe with same dimension as self.

Series expects only scalar or series like with same length

inplacebool, default False

Whether to perform the operation in place on the data.

Returns
Same type as caller

Examples

>>> import cudf
>>> df = cudf.DataFrame({"A":[1, 4, 5], "B":[3, 5, 8]})
>>> df.where(df % 2 == 0, [-1, -1])
   A  B
0 -1 -1
1  4 -1
2 -1  8
>>> ser = cudf.Series([4, 3, 2, 1, 0])
>>> ser.where(ser > 2, 10)
0     4
1     3
2    10
3    10
4    10
dtype: int64
>>> ser.where(ser > 2)
0       4
1       3
2    null
3    null
4    null
dtype: int64

Strings

class cudf.core.column.string.StringMethods(column, parent=None)

Vectorized string functions for Series and Index.

This mimics pandas df.str interface. nulls stay null unless handled otherwise by a particular method. Patterned after Python’s string methods, with some inspiration from R’s stringr package.

Methods

byte_count(**kwargs)

Computes the number of bytes of each string in the Series/Index.

capitalize(**kwargs)

Convert strings in the Series/Index to be capitalized.

cat([others, sep, na_rep])

Concatenate strings in the Series/Index with given separator.

center(width[, fillchar])

Filling left and right side of strings in the Series/Index with an additional character.

character_ngrams([n])

Generate the n-grams from characters in a column of strings.

character_tokenize(**kwargs)

Each string is split into individual characters.

code_points(**kwargs)

Returns an array by filling it with the UTF-8 code point values for each character of each string.

contains(pat[, case, flags, na, regex])

Test if pattern or regex is contained within a string of a Series or Index.

count(pat[, flags])

Count occurrences of pattern in each string of the Series/Index.

detokenize(indices[, separator])

Combines tokens into strings by concatenating them in the order in which they appear in the indices column.

edit_distance(targets, **kwargs)

The targets strings are measured against the strings in this instance using the Levenshtein edit distance algorithm.

endswith(pat, **kwargs)

Test if the end of each string element matches a pattern.

extract(pat[, flags, expand])

Extract capture groups in the regex pat as columns in a DataFrame.

filter_alphanum([repl, keep])

Remove non-alphanumeric characters from strings in this column.

filter_characters(table[, keep, repl])

Remove characters from each string using the character ranges in the given mapping table.

filter_tokens(min_token_length[, …])

Remove tokens from within each string in the series that are smaller than min_token_length and optionally replace them with the replacement string.

find(sub[, start, end])

Return lowest indexes in each strings in the Series/Index where the substring is fully contained between [start:end].

findall(pat[, flags])

Find all occurrences of pattern or regular expression in the Series/Index.

get([i])

Extract element from each component at specified position.

htoi()

Returns integer value represented by each hex string.

index(sub[, start, end])

Return lowest indexes in each strings where the substring is fully contained between [start:end].

insert([start, repl])

Insert the specified string into each string in the specified position.

ip2int()

This converts ip strings to integers

is_consonant(position, **kwargs)

Return true for strings where the character at position is a consonant.

is_vowel(position, **kwargs)

Return true for strings where the character at position is a vowel – not a consonant.

isalnum(**kwargs)

Check whether all characters in each string are alphanumeric.

isalpha(**kwargs)

Check whether all characters in each string are alphabetic.

isdecimal(**kwargs)

Check whether all characters in each string are decimal.

isdigit(**kwargs)

Check whether all characters in each string are digits.

isempty(**kwargs)

Check whether each string is an empty string.

isfloat(**kwargs)

Check whether all characters in each string form floating value.

ishex(**kwargs)

Check whether all characters in each string form a hex integer.

isinteger(**kwargs)

Check whether all characters in each string form integer.

isipv4(**kwargs)

Check whether all characters in each string form an IPv4 address.

islower(**kwargs)

Check whether all characters in each string are lowercase.

isnumeric(**kwargs)

Check whether all characters in each string are numeric.

isspace(**kwargs)

Check whether all characters in each string are whitespace.

isupper(**kwargs)

Check whether all characters in each string are uppercase.

join(sep)

Join lists contained as elements in the Series/Index with passed delimiter.

len(**kwargs)

Computes the length of each element in the Series/Index.

ljust(width[, fillchar])

Filling right side of strings in the Series/Index with an additional character.

lower(**kwargs)

Converts all characters to lowercase.

lstrip([to_strip])

Remove leading and trailing characters.

match(pat[, case, flags])

Determine if each string matches a regular expression.

ngrams([n, separator])

Generate the n-grams from a set of tokens, each record in series is treated a token.

ngrams_tokenize([n, delimiter, separator])

Generate the n-grams using tokens from each string.

normalize_characters([do_lower])

Normalizes strings characters for tokenizing.

normalize_spaces(**kwargs)

Remove extra whitespace between tokens and trim whitespace from the beginning and the end of each string.

pad(width[, side, fillchar])

Pad strings in the Series/Index up to width.

partition([sep, expand])

Split the string at the first occurrence of sep.

porter_stemmer_measure(**kwargs)

Compute the Porter Stemmer measure for each string.

replace(pat, repl[, n, case, flags, regex])

Replace occurrences of pattern/regex in the Series/Index with some other string.

replace_tokens(targets, replacements[, …])

The targets tokens are searched for within each string in the series and replaced with the corresponding replacements if found.

replace_with_backrefs(pat, repl, **kwargs)

Use the repl back-ref template to create a new string with the extracted elements found using the pat expression.

rfind(sub[, start, end])

Return highest indexes in each strings in the Series/Index where the substring is fully contained between [start:end].

rindex(sub[, start, end])

Return highest indexes in each strings where the substring is fully contained between [start:end].

rjust(width[, fillchar])

Filling left side of strings in the Series/Index with an additional character.

rpartition([sep, expand])

Split the string at the last occurrence of sep.

rsplit([pat, n, expand])

Split strings around given separator/delimiter.

rstrip([to_strip])

Remove leading and trailing characters.

slice([start, stop, step])

Slice substrings from each element in the Series or Index.

slice_from(starts, stops, **kwargs)

Return substring of each string using positions for each string.

slice_replace([start, stop, repl])

Replace the specified section of each string with a new string.

split([pat, n, expand])

Split strings around given separator/delimiter.

startswith(pat, **kwargs)

Test if the start of each string element matches a pattern.

strip([to_strip])

Remove leading and trailing characters.

subword_tokenize(hash_file[, max_length, …])

Run CUDA BERT subword tokenizer on cuDF strings column.

swapcase(**kwargs)

Change each lowercase character to uppercase and vice versa.

title(**kwargs)

Uppercase the first letter of each letter after a space and lowercase the rest.

token_count([delimiter])

Each string is split into tokens using the provided delimiter.

tokenize([delimiter])

Each string is split into tokens using the provided delimiter(s).

translate(table, **kwargs)

Map all characters in the string through the given mapping table.

upper(**kwargs)

Convert each string to uppercase.

url_decode(**kwargs)

Returns a URL-decoded format of each string.

url_encode(**kwargs)

Returns a URL-encoded format of each string.

wrap(width, **kwargs)

Wrap long strings in the Series/Index to be formatted in paragraphs with length less than a given width.

zfill(width, **kwargs)

Pad strings in the Series/Index by prepending ‘0’ characters.

byte_count(**kwargs)

Computes the number of bytes of each string in the Series/Index.

ReturnsSeries or Index of int

A Series