Skip to content

getml.data.DataFrame

DataFrame(
    name: str,
    roles: Optional[
        Union[Dict[Union[Role, str], Iterable[str]], Roles]
    ] = None,
)

Handler for the data stored in the getML Engine.

The DataFrame class represents a data frame object in the getML Engine but does not contain any actual data itself. To create such a data frame object, fill it with data via the Python API, and to retrieve a handler for it, you can use one of the from_csv, from_db, from_json, or from_pandas class methods. The Importing Data section in the user guide explains the particularities of each of those flavors of the unified import interface.

If the data frame object is already present in the Engine - either in memory as a temporary object or on disk when save was called earlier -, the load_data_frame function will create a new handler without altering the underlying data. For more information about the lifecycle of the data in the getML Engine and its synchronization with the Python API please see the corresponding User Guide.

ATTRIBUTE DESCRIPTION
name

Unique identifier used to link the handler with the underlying data frame object in the Engine.

roles

Maps the roles to the column names (see colnames).

The roles dictionary is expected to have the following format

roles = {getml.data.role.numeric: ["colname1", "colname2"],
         getml.data.role.target: ["colname3"]}
Otherwise, you can use the Roles class.

Example

Creating a new data frame object in the getML Engine and importing data is done by one the class functions from_csv, from_db, from_json, or from_pandas.

random = numpy.random.RandomState(7263)

table = pandas.DataFrame()
table['column_01'] = random.randint(0, 10, 1000).astype(numpy.str)
table['join_key'] = numpy.arange(1000)
table['time_stamp'] = random.rand(1000)
table['target'] = random.rand(1000)

df_table = getml.DataFrame.from_pandas(table, name = 'table')
In addition to creating a new data frame object in the getML Engine and filling it with all the content of table, the from_pandas function also returns a DataFrame handler to the underlying data.

You don't have to create the data frame objects anew for each session. You can use their save method to write them to disk, the list_data_frames function to list all available objects in the Engine, and load_data_frame to create a DataFrame handler for a data set already present in the getML Engine (see User Guide for details).

df_table.save()

getml.data.list_data_frames()

df_table_reloaded = getml.data.load_data_frame('table')
Note

Although the Python API does not store the actual data itself, you can use the to_csv, to_db, to_json, and to_pandas methods to retrieve them.

Source code in getml/data/data_frame.py
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
def __init__(
    self,
    name: str,
    roles: Optional[Union[Dict[Union[Role, str], Iterable[str]], Roles]] = None,
):
    # ------------------------------------------------------------

    if not isinstance(name, str):
        raise TypeError("'name' must be str.")

    vars(self)["name"] = name

    if roles is None:
        roles = {}

    if isinstance(roles, dict):
        roles = Roles.from_dict(roles)

    # ------------------------------------------------------------

    vars(self)["_categorical_columns"] = [
        StringColumn(name=cname, role=roles_.categorical, df_name=self.name)
        for cname in roles.categorical
    ]

    vars(self)["_join_key_columns"] = [
        StringColumn(name=cname, role=roles_.join_key, df_name=self.name)
        for cname in roles.join_key
    ]

    vars(self)["_numerical_columns"] = [
        FloatColumn(name=cname, role=roles_.numerical, df_name=self.name)
        for cname in roles.numerical
    ]

    vars(self)["_target_columns"] = [
        FloatColumn(name=cname, role=roles_.target, df_name=self.name)
        for cname in roles.target
    ]

    vars(self)["_text_columns"] = [
        StringColumn(name=cname, role=roles_.text, df_name=self.name)
        for cname in roles.text
    ]

    vars(self)["_time_stamp_columns"] = [
        FloatColumn(name=cname, role=roles_.time_stamp, df_name=self.name)
        for cname in roles.time_stamp
    ]

    vars(self)["_unused_float_columns"] = [
        FloatColumn(name=cname, role=roles_.unused_float, df_name=self.name)
        for cname in roles.unused_float
    ]

    vars(self)["_unused_string_columns"] = [
        StringColumn(name=cname, role=roles_.unused_string, df_name=self.name)
        for cname in roles.unused_string
    ]

    # ------------------------------------------------------------

    self._check_duplicates()

colnames property

colnames: List[str]

List of the names of all columns.

RETURNS DESCRIPTION
List[str]

List of the names of all columns.

columns property

columns: List[str]

Alias for colnames.

RETURNS DESCRIPTION
List[str]

List of the names of all columns.

last_change property

last_change: str

A string describing the last time this data frame has been changed.

memory_usage property

memory_usage

Convenience wrapper that returns the memory usage in MB.

roles property

roles

The roles of the columns included in this DataFrame.

rowid property

rowid

The rowids for this data frame.

shape property

shape

A tuple containing the number of rows and columns of the DataFrame.

add

add(
    col: Union[StringColumn, FloatColumn, ndarray],
    name: str,
    role: Optional[Role] = None,
    subroles: Optional[Union[Role, Iterable[str]]] = None,
    unit: str = "",
    time_formats: Optional[Iterable[str]] = None,
)

Adds a column to the current DataFrame.

PARAMETER DESCRIPTION
col

The column or numpy.ndarray to be added.

TYPE: Union[StringColumn, FloatColumn, ndarray]

name

Name of the new column.

TYPE: str

role

Role of the new column. Must be from roles.

TYPE: Optional[Role] DEFAULT: None

subroles

Subroles of the new column. Must be from subroles.

TYPE: Optional[Union[Role, Iterable[str]]] DEFAULT: None

unit

Unit of the column.

TYPE: str DEFAULT: ''

time_formats

Formats to be used to parse the time stamps.

This is only necessary, if an implicit conversion from a StringColumn to a time stamp is taking place.

The formats are allowed to contain the following special characters:

  • %w - abbreviated weekday (Mon, Tue, ...)
  • %W - full weekday (Monday, Tuesday, ...)
  • %b - abbreviated month (Jan, Feb, ...)
  • %B - full month (January, February, ...)
  • %d - zero-padded day of month (01 .. 31)
  • %e - day of month (1 .. 31)
  • %f - space-padded day of month ( 1 .. 31)
  • %m - zero-padded month (01 .. 12)
  • %n - month (1 .. 12)
  • %o - space-padded month ( 1 .. 12)
  • %y - year without century (70)
  • %Y - year with century (1970)
  • %H - hour (00 .. 23)
  • %h - hour (00 .. 12)
  • %a - am/pm
  • %A - AM/PM
  • %M - minute (00 .. 59)
  • %S - second (00 .. 59)
  • %s - seconds and microseconds (equivalent to %S.%F)
  • %i - millisecond (000 .. 999)
  • %c - centisecond (0 .. 9)
  • %F - fractional seconds/microseconds (000000 - 999999)
  • %z - time zone differential in ISO 8601 format (Z or +NN.NN)
  • %Z - time zone differential in RFC format (GMT or +NNNN)
  • %% - percent sign

TYPE: Optional[Iterable[str]] DEFAULT: None

Source code in getml/data/data_frame.py
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
def add(
    self,
    col: Union[StringColumn, FloatColumn, np.ndarray],
    name: str,
    role: Optional[Role] = None,
    subroles: Optional[Union[Role, Iterable[str]]] = None,
    unit: str = "",
    time_formats: Optional[Iterable[str]] = None,
):
    """Adds a column to the current [`DataFrame`][getml.DataFrame].

    Args:
        col:
            The column or numpy.ndarray to be added.

        name:
            Name of the new column.

        role:
            Role of the new column. Must be from [`roles`][getml.data.roles].

        subroles:
            Subroles of the new column. Must be from [`subroles`][getml.data.subroles].

        unit:
            Unit of the column.

        time_formats:
            Formats to be used to parse the time stamps.

            This is only necessary, if an implicit conversion from
            a [`StringColumn`][getml.data.columns.StringColumn] to a time
            stamp is taking place.

            The formats are allowed to contain the following
            special characters:

            * %w - abbreviated weekday (Mon, Tue, ...)
            * %W - full weekday (Monday, Tuesday, ...)
            * %b - abbreviated month (Jan, Feb, ...)
            * %B - full month (January, February, ...)
            * %d - zero-padded day of month (01 .. 31)
            * %e - day of month (1 .. 31)
            * %f - space-padded day of month ( 1 .. 31)
            * %m - zero-padded month (01 .. 12)
            * %n - month (1 .. 12)
            * %o - space-padded month ( 1 .. 12)
            * %y - year without century (70)
            * %Y - year with century (1970)
            * %H - hour (00 .. 23)
            * %h - hour (00 .. 12)
            * %a - am/pm
            * %A - AM/PM
            * %M - minute (00 .. 59)
            * %S - second (00 .. 59)
            * %s - seconds and microseconds (equivalent to %S.%F)
            * %i - millisecond (000 .. 999)
            * %c - centisecond (0 .. 9)
            * %F - fractional seconds/microseconds (000000 - 999999)
            * %z - time zone differential in ISO 8601 format (Z or +NN.NN)
            * %Z - time zone differential in RFC format (GMT or +NNNN)
            * %% - percent sign
    """

    if isinstance(col, np.ndarray):
        self._add_numpy_array(col, name, role, subroles, unit)
        return

    col, role, subroles = _with_column(
        col, name, role, subroles, unit, time_formats
    )

    is_string = isinstance(col, (StringColumnView, StringColumn))

    if is_string:
        self._add_categorical_column(col, name, role, subroles, unit)
    else:
        self._add_column(col, name, role, subroles, unit)

copy

copy(name: str) -> DataFrame

Creates a deep copy of the data frame under a new name.

PARAMETER DESCRIPTION
name

The name of the new data frame.

TYPE: str

RETURNS DESCRIPTION
DataFrame

A handle to the deep copy.

Source code in getml/data/data_frame.py
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
def copy(self, name: str) -> DataFrame:
    """
    Creates a deep copy of the data frame under a new name.

    Args:
        name:
            The name of the new data frame.

    Returns:
            A handle to the deep copy.
    """

    if not isinstance(name, str):
        raise TypeError("'name' must be a string.")

    cmd: Dict[str, Any] = {}

    cmd["type_"] = "DataFrame.concat"
    cmd["name_"] = name

    cmd["data_frames_"] = [self._getml_deserialize()]

    comm.send(cmd)

    return DataFrame(name=name).refresh()

delete

delete()

Permanently deletes the data frame. delete first unloads the data frame from memory and then deletes it from disk.

Source code in getml/data/data_frame.py
842
843
844
845
846
847
848
849
def delete(self):
    """
    Permanently deletes the data frame. `delete` first unloads the data frame
    from memory and then deletes it from disk.
    """
    # ------------------------------------------------------------

    self._delete()

drop

Returns a new View that has one or several columns removed.

PARAMETER DESCRIPTION
cols

The columns or the names thereof.

TYPE: Union[FloatColumn, StringColumn, str, Union[Iterable[FloatColumn], Iterable[StringColumn], Iterable[str]]]

RETURNS DESCRIPTION
View

A new View object with the specified columns removed.

Source code in getml/data/data_frame.py
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
def drop(
    self,
    cols: Union[
        FloatColumn,
        StringColumn,
        str,
        Union[Iterable[FloatColumn], Iterable[StringColumn], Iterable[str]],
    ],
) -> View:
    """Returns a new [`View`][getml.data.View] that has one or several columns removed.

    Args:
        cols:
            The columns or the names thereof.

    Returns:
        A new [`View`][getml.data.View] object with the specified columns removed.
    """

    names = _handle_cols(cols)

    return View(base=self, dropped=names)

freeze

freeze()

Freezes the data frame.

After you have frozen the data frame, the data frame is immutable and in-place operations are no longer possible. However, you can still create views. In other words, operations like set_role are no longer possible, but operations like with_role are.

Source code in getml/data/data_frame.py
878
879
880
881
882
883
884
885
886
887
888
889
890
def freeze(self):
    """Freezes the data frame.

    After you have frozen the data frame, the data frame is immutable
    and in-place operations are no longer possible. However, you can
    still create views. In other words, operations like
    [`set_role`][getml.DataFrame.set_role] are no longer possible,
    but operations like [`with_role`][getml.DataFrame.with_role] are.
    """
    cmd: Dict[str, Any] = {}
    cmd["type_"] = "DataFrame.freeze"
    cmd["name_"] = self.name
    comm.send(cmd)

from_arrow classmethod

from_arrow(
    table: Table,
    name: str,
    roles: Optional[
        Union[Dict[Union[Role, str], Iterable[str]], Roles]
    ] = None,
    ignore: bool = False,
    dry: bool = False,
) -> Union[DataFrame, Roles]

Create a DataFrame from an Arrow Table.

This is one of the fastest way to get data into the getML Engine.

PARAMETER DESCRIPTION
table

The arrow tablelike to be read.

TYPE: Table

name

Name of the data frame to be created.

TYPE: str

roles

Maps the roles to the column names (see colnames).

The roles dictionary is expected to have the following format:

roles = {getml.data.role.numeric: ["colname1", "colname2"],
         getml.data.role.target: ["colname3"]}
Otherwise, you can use the Roles class.

TYPE: Optional[Union[Dict[Union[Role, str], Iterable[str]], Roles]] DEFAULT: None

ignore

Only relevant when roles is not None. Determines what you want to do with any colnames not mentioned in roles. Do you want to ignore them (True) or read them in as unused columns (False)?

TYPE: bool DEFAULT: False

dry

If set to True, the data will not be read. Instead, the method will return the inffered roles.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
Union[DataFrame, Roles]

Handler of the underlying data.

Source code in getml/data/data_frame.py
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
@classmethod
def from_arrow(
    cls,
    table: pa.Table,
    name: str,
    roles: Optional[Union[Dict[Union[Role, str], Iterable[str]], Roles]] = None,
    ignore: bool = False,
    dry: bool = False,
) -> Union[DataFrame, Roles]:
    """Create a DataFrame from an Arrow Table.

    This is one of the fastest way to get data into the
    getML Engine.

    Args:
        table:
            The arrow tablelike to be read.

        name:
            Name of the data frame to be created.

        roles:
            Maps the [`roles`][getml.data.roles] to the
            column names (see [`colnames`][getml.DataFrame.colnames]).

            The `roles` dictionary is expected to have the following format:
            ```python
            roles = {getml.data.role.numeric: ["colname1", "colname2"],
                     getml.data.role.target: ["colname3"]}
            ```
            Otherwise, you can use the [`Roles`][getml.data.Roles] class.

        ignore:
            Only relevant when roles is not None.
            Determines what you want to do with any colnames not
            mentioned in roles. Do you want to ignore them (True)
            or read them in as unused columns (False)?

        dry:
            If set to True, the data will not be read. Instead, the method
            will return the inffered roles.

    Returns:
            Handler of the underlying data.
    """

    # ------------------------------------------------------------

    if not isinstance(name, str):
        raise TypeError("'name' must be str.")

    # The content of roles is checked in the class constructor called below.
    if roles is not None and not isinstance(roles, (dict, Roles)):
        raise TypeError("'roles' must be a geml.data.Roles object, a dict or None.")

    if not isinstance(ignore, bool):
        raise TypeError("'ignore' must be bool.")

    if not isinstance(dry, bool):
        raise TypeError("'dry' must be bool.")

    # ------------------------------------------------------------

    sniffed_roles = sniff_arrow(table)

    roles = _prepare_roles(roles, sniffed_roles, ignore_sniffed_roles=ignore)

    if dry:
        return roles

    data_frame = cls(name, roles)

    return data_frame.read_arrow(table=table, append=False)

from_csv classmethod

from_csv(
    fnames: Union[str, Iterable[str]],
    name: str,
    num_lines_sniffed: None = None,
    num_lines_read: int = 0,
    quotechar: str = '"',
    sep: str = ",",
    skip: int = 0,
    colnames: Iterable[str] = (),
    roles: Optional[
        Union[Dict[Union[Role, str], Iterable[str]], Roles]
    ] = None,
    ignore: bool = False,
    dry: bool = False,
    verbose: bool = True,
    block_size: int = DEFAULT_CSV_READ_BLOCK_SIZE,
    in_batches: bool = False,
) -> Union[DataFrame, Roles]

Create a DataFrame from CSV files.

The getML Engine will construct a data frame object in the Engine, fill it with the data read from the CSV file(s), and return a corresponding DataFrame handle.

PARAMETER DESCRIPTION
fnames

CSV file paths to be read.

TYPE: Union[str, Iterable[str]]

name

Name of the data frame to be created.

TYPE: str

num_lines_sniffed

Number of lines analyzed by the sniffer.

TYPE: None DEFAULT: None

num_lines_read

Number of lines read from each file. Set to 0 to read in the entire file.

TYPE: int DEFAULT: 0

quotechar

The character used to wrap strings.

TYPE: str DEFAULT: '"'

sep

The separator used for separating fields.

TYPE: str DEFAULT: ','

skip

Number of lines to skip at the beginning of each file.

TYPE: int DEFAULT: 0

colnames

The first line of a CSV file usually contains the column names. When this is not the case, you need to explicitly pass them.

TYPE: Iterable[str] DEFAULT: ()

roles

Maps the roles to the column names (see colnames).

The roles dictionary is expected to have the following format

roles = {getml.data.role.numeric: ["colname1", "colname2"],
         getml.data.role.target: ["colname3"]}
Otherwise, you can use the Roles class.

TYPE: Optional[Union[Dict[Union[Role, str], Iterable[str]], Roles]] DEFAULT: None

ignore

Only relevant when roles is not None. Determines what you want to do with any colnames not mentioned in roles. Do you want to ignore them (True) or read them in as unused columns (False)?

TYPE: bool DEFAULT: False

dry

If set to True, the data will not be read. Instead, the method will return the inffered roles.

TYPE: bool DEFAULT: False

verbose

If True, when fnames are urls, the filenames are printed to stdout during the download.

TYPE: bool DEFAULT: True

block_size

The number of bytes read with each batch. Passed down to pyarrow.

TYPE: int DEFAULT: DEFAULT_CSV_READ_BLOCK_SIZE

in_batches

If True, read blocks streamwise manner and send those batches to the engine. Blocks are read and sent to the engine sequentially. While more memory efficient, streaming in batches is slower as it is inherently single-threaded. If False (default) the data is read with multiple threads into arrow first and sent to the engine afterwards.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
Union[DataFrame, Roles]

Handler of the underlying data.

Deprecated

1.5: The num_lines_sniffed parameter is deprecated.

Note

It is assumed that the first line of each CSV file contains a header with the column names.

Example

Let's assume you have two CSV files - file1.csv and file2.csv - in the current working directory. You can import their data into the getML Engine using.

df_expd = data.DataFrame.from_csv(
    fnames=["file1.csv", "file2.csv"],
    name="MY DATA FRAME",
    sep=';',
    quotechar='"'
    )

# However, the CSV format lacks type safety. If you want to
# build a reliable pipeline, it is a good idea
# to hard-code the roles:

roles = {"categorical": ["col1", "col2"], "target": ["col3"]}

df_expd = data.DataFrame.from_csv(
    fnames=["file1.csv", "file2.csv"],
    name="MY DATA FRAME",
    sep=';',
    quotechar='"',
    roles=roles
    )

# If you think that typing out all the roles by hand is too
# cumbersome, you can use a dry run:

roles = data.DataFrame.from_csv(
    fnames=["file1.csv", "file2.csv"],
    name="MY DATA FRAME",
    sep=';',
    quotechar='"',
    dry=True
)

This will return the roles dictionary it would have used. You can now hard-code this.

Source code in getml/data/data_frame.py
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
@classmethod
def from_csv(
    cls,
    fnames: Union[str, Iterable[str]],
    name: str,
    num_lines_sniffed: None = None,
    num_lines_read: int = 0,
    quotechar: str = '"',
    sep: str = ",",
    skip: int = 0,
    colnames: Iterable[str] = (),
    roles: Optional[Union[Dict[Union[Role, str], Iterable[str]], Roles]] = None,
    ignore: bool = False,
    dry: bool = False,
    verbose: bool = True,
    block_size: int = DEFAULT_CSV_READ_BLOCK_SIZE,
    in_batches: bool = False,
) -> Union[DataFrame, Roles]:
    """Create a DataFrame from CSV files.

    The getML Engine will construct a data
    frame object in the Engine, fill it with the data read from
    the CSV file(s), and return a corresponding
    [`DataFrame`][getml.DataFrame] handle.

    Args:
        fnames:
            CSV file paths to be read.

        name:
            Name of the data frame to be created.

        num_lines_sniffed:
            Number of lines analyzed by the sniffer.

        num_lines_read:
            Number of lines read from each file.
            Set to 0 to read in the entire file.

        quotechar:
            The character used to wrap strings.

        sep:
            The separator used for separating fields.

        skip:
            Number of lines to skip at the beginning of each file.

        colnames: The first line of a CSV file
            usually contains the column names. When this is not the case,
            you need to explicitly pass them.

        roles:
            Maps the [`roles`][getml.data.roles] to the
            column names (see [`colnames`][getml.DataFrame.colnames]).

            The `roles` dictionary is expected to have the following format
            ```python
            roles = {getml.data.role.numeric: ["colname1", "colname2"],
                     getml.data.role.target: ["colname3"]}
            ```
            Otherwise, you can use the [`Roles`][getml.data.Roles] class.

        ignore:
            Only relevant when roles is not None.
            Determines what you want to do with any colnames not
            mentioned in roles. Do you want to ignore them (True)
            or read them in as unused columns (False)?

        dry:
            If set to True, the data will not be read. Instead, the method
            will return the inffered roles.

        verbose:
            If True, when fnames are urls, the filenames are
            printed to stdout during the download.

        block_size:
            The number of bytes read with each batch. Passed down to
            pyarrow.

        in_batches:
            If True, read blocks streamwise manner and send those batches to
            the engine. Blocks are read and sent to the engine sequentially.
            While more memory efficient, streaming in batches is slower as
            it is inherently single-threaded. If False (default) the data is
            read with multiple threads into arrow first and sent to the engine
            afterwards.

    Returns:
            Handler of the underlying data.


    Deprecated:
        1.5: The `num_lines_sniffed` parameter is deprecated.

    Note:
        It is assumed that the first line of each CSV file
        contains a header with the column names.

    ??? example
        Let's assume you have two CSV files - *file1.csv* and
        *file2.csv* - in the current working directory. You can
        import their data into the getML Engine using.
        ```python
        df_expd = data.DataFrame.from_csv(
            fnames=["file1.csv", "file2.csv"],
            name="MY DATA FRAME",
            sep=';',
            quotechar='"'
            )

        # However, the CSV format lacks type safety. If you want to
        # build a reliable pipeline, it is a good idea
        # to hard-code the roles:

        roles = {"categorical": ["col1", "col2"], "target": ["col3"]}

        df_expd = data.DataFrame.from_csv(
            fnames=["file1.csv", "file2.csv"],
            name="MY DATA FRAME",
            sep=';',
            quotechar='"',
            roles=roles
            )

        # If you think that typing out all the roles by hand is too
        # cumbersome, you can use a dry run:

        roles = data.DataFrame.from_csv(
            fnames=["file1.csv", "file2.csv"],
            name="MY DATA FRAME",
            sep=';',
            quotechar='"',
            dry=True
        )
        ```

        This will return the roles dictionary it would have used. You
        can now hard-code this.

    """

    if num_lines_sniffed is not None:
        warnings.warn(
            "The 'num_lines_sniffed' parameter is deprecated and will be ignored.",
            DeprecationWarning,
        )

    if isinstance(fnames, str):
        fnames = [fnames]

    if not _is_non_empty_typed_list(fnames, str):
        raise TypeError("'fnames' must be either a str or a list of str.")

    if not isinstance(name, str):
        raise TypeError("'name' must be str.")

    if not isinstance(num_lines_read, numbers.Real):
        raise TypeError("'num_lines_read' must be a real number")

    if not isinstance(quotechar, str):
        raise TypeError("'quotechar' must be str.")

    if not isinstance(sep, str):
        raise TypeError("'sep' must be str.")

    if not isinstance(skip, numbers.Real):
        raise TypeError("'skip' must be a real number")

    if roles is not None and not isinstance(roles, (dict, Roles)):
        raise TypeError("'roles' must be a geml.data.Roles object, a dict or None.")

    if not isinstance(ignore, bool):
        raise TypeError("'ignore' must be bool.")

    if not isinstance(ignore, bool):
        raise TypeError("'dry' must be bool.")

    if colnames:
        if not _is_iterable_not_str_of_type(colnames, str):
            raise TypeError("'colnames' must be an iterable of str")

    fnames = _retrieve_urls(fnames, verbose=verbose)

    sniffed_roles = sniff_csv(
        fnames=fnames,
        quotechar=quotechar,
        sep=sep,
        skip=int(skip),
        colnames=colnames,
    )

    roles = _prepare_roles(roles, sniffed_roles, ignore_sniffed_roles=ignore)

    if dry:
        return roles

    data_frame = cls(name, roles)

    return data_frame.read_csv(
        fnames=fnames,
        append=False,
        quotechar=quotechar,
        sep=sep,
        num_lines_read=num_lines_read,
        skip=skip,
        colnames=colnames,
        block_size=block_size,
        in_batches=in_batches,
    )

from_db classmethod

from_db(
    table_name: str,
    name: Optional[str] = None,
    roles: Optional[
        Union[Dict[Union[Role, str], Iterable[str]], Roles]
    ] = None,
    ignore: bool = False,
    dry: bool = False,
    conn: Optional[Connection] = None,
) -> Union[DataFrame, Roles]

Create a DataFrame from a table in a database.

It will construct a data frame object in the Engine, fill it with the data read from table table_name in the connected database (see database), and return a corresponding DataFrame handle.

PARAMETER DESCRIPTION
table_name

Name of the table to be read.

TYPE: str

name

Name of the data frame to be created. If not passed, then the table_name will be used.

TYPE: Optional[str] DEFAULT: None

roles

Maps the roles to the column names (see colnames).

The roles dictionary is expected to have the following format:

roles = {getml.data.role.numeric: ["colname1", "colname2"],
         getml.data.role.target: ["colname3"]}
Otherwise, you can use the Roles class.

TYPE: Optional[Union[Dict[Union[Role, str], Iterable[str]], Roles]] DEFAULT: None

ignore

Only relevant when roles is not None. Determines what you want to do with any colnames not mentioned in roles. Do you want to ignore them (True) or read them in as unused columns (False)?

TYPE: bool DEFAULT: False

dry

If set to True, the data will not be read. Instead, the method will return the inffered roles.

TYPE: bool DEFAULT: False

conn

The database connection to be used. If you don't explicitly pass a connection, the Engine will use the default connection.

TYPE: Optional[Connection] DEFAULT: None

RETURNS DESCRIPTION
Union[DataFrame, Roles]

Handler of the underlying data.

Example
getml.database.connect_mysql(
    host="db.relational-data.org",
    port=3306,
    dbname="financial",
    user="guest",
    password="relational"
)

loan = getml.DataFrame.from_db(
    table_name='loan', name='data_frame_loan')
Source code in getml/data/data_frame.py
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
@classmethod
def from_db(
    cls,
    table_name: str,
    name: Optional[str] = None,
    roles: Optional[Union[Dict[Union[Role, str], Iterable[str]], Roles]] = None,
    ignore: bool = False,
    dry: bool = False,
    conn: Optional[Connection] = None,
) -> Union[DataFrame, Roles]:
    """Create a DataFrame from a table in a database.

    It will construct a data frame object in the Engine, fill it
    with the data read from table `table_name` in the connected
    database (see [`database`][getml.database]), and return a
    corresponding [`DataFrame`][getml.DataFrame] handle.

    Args:
        table_name:
            Name of the table to be read.

        name:
            Name of the data frame to be created. If not passed,
            then the *table_name* will be used.

        roles:
            Maps the [`roles`][getml.data.roles] to the
            column names (see [`colnames`][getml.DataFrame.colnames]).

            The `roles` dictionary is expected to have the following format:
            ```python
            roles = {getml.data.role.numeric: ["colname1", "colname2"],
                     getml.data.role.target: ["colname3"]}
            ```
            Otherwise, you can use the [`Roles`][getml.data.Roles] class.

        ignore:
            Only relevant when roles is not None.
            Determines what you want to do with any colnames not
            mentioned in roles. Do you want to ignore them (True)
            or read them in as unused columns (False)?

        dry:
            If set to True, the data will not be read. Instead, the method
            will return the inffered roles.

        conn:
            The database connection to be used.
            If you don't explicitly pass a connection, the Engine
            will use the default connection.

    Returns:
            Handler of the underlying data.

    ??? example
        ```python
        getml.database.connect_mysql(
            host="db.relational-data.org",
            port=3306,
            dbname="financial",
            user="guest",
            password="relational"
        )

        loan = getml.DataFrame.from_db(
            table_name='loan', name='data_frame_loan')
        ```
    """

    # -------------------------------------------

    name = name or table_name

    # -------------------------------------------

    if not isinstance(table_name, str):
        raise TypeError("'table_name' must be str.")

    if not isinstance(name, str):
        raise TypeError("'name' must be str.")

    # The content of roles is checked in the class constructor called below.
    if roles is not None and not isinstance(roles, (dict, Roles)):
        raise TypeError(
            "'roles' must be a getml.data.Roles object, a dict or None."
        )

    if not isinstance(ignore, bool):
        raise TypeError("'ignore' must be bool.")

    if not isinstance(dry, bool):
        raise TypeError("'dry' must be bool.")

    # -------------------------------------------

    conn = conn or database.Connection()

    # ------------------------------------------------------------

    sniffed_roles = _sniff_db(table_name, conn)

    roles = _prepare_roles(roles, sniffed_roles, ignore_sniffed_roles=ignore)

    if dry:
        return roles

    # ------------------------------------------------------------

    data_frame = cls(name, roles)

    return data_frame.read_db(table_name=table_name, append=False, conn=conn)

from_dict classmethod

from_dict(
    data: Dict[Hashable, Iterable[Any]],
    name: str,
    roles: Optional[
        Union[Dict[Union[Role, str], Iterable[str]], Roles]
    ] = None,
    ignore: bool = False,
    dry: bool = False,
) -> Union[DataFrame, Roles]

Create a new DataFrame from a dict

PARAMETER DESCRIPTION
data

The dict containing the data. The data should be in the following format:

data = {'col1': [1.0, 2.0, 1.0], 'col2': ['A', 'B', 'C']}

TYPE: Dict[Hashable, Iterable[Any]]

name

Name of the data frame to be created.

TYPE: str

roles

Maps the roles to the column names (see colnames).

The roles dictionary is expected to have the following format:

roles = {getml.data.role.numeric: ["colname1", "colname2"],
         getml.data.role.target: ["colname3"]}
Otherwise, you can use the Roles class.

TYPE: Optional[Union[Dict[Union[Role, str], Iterable[str]], Roles]] DEFAULT: None

ignore

Only relevant when roles is not None. Determines what you want to do with any colnames not mentioned in roles. Do you want to ignore them (True) or read them in as unused columns (False)?

TYPE: bool DEFAULT: False

dry

If set to True, the data will not be read. Instead, the method will return the inffered roles.

TYPE: bool DEFAULT: False

Returns: Handler of the underlying data.

Source code in getml/data/data_frame.py
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
@classmethod
def from_dict(
    cls,
    data: Dict[Hashable, Iterable[Any]],
    name: str,
    roles: Optional[Union[Dict[Union[Role, str], Iterable[str]], Roles]] = None,
    ignore: bool = False,
    dry: bool = False,
) -> Union[DataFrame, Roles]:
    """Create a new DataFrame from a dict

    Args:
        data:
            The dict containing the data.
            The data should be in the following format:
            ```python
            data = {'col1': [1.0, 2.0, 1.0], 'col2': ['A', 'B', 'C']}
            ```
        name:
            Name of the data frame to be created.

        roles:
            Maps the [`roles`][getml.data.roles] to the
            column names (see [`colnames`][getml.DataFrame.colnames]).

            The `roles` dictionary is expected to have the following format:
            ```python
            roles = {getml.data.role.numeric: ["colname1", "colname2"],
                     getml.data.role.target: ["colname3"]}
            ```
            Otherwise, you can use the [`Roles`][getml.data.Roles] class.

        ignore:
            Only relevant when roles is not None.
            Determines what you want to do with any colnames not
            mentioned in roles. Do you want to ignore them (True)
            or read them in as unused columns (False)?

        dry:
            If set to True, the data will not be read. Instead, the method
            will return the inffered roles.
    Returns:
            Handler of the underlying data.
    """

    if not isinstance(data, dict):
        raise TypeError("'data' must be dict.")

    return cls.from_arrow(
        table=pa.Table.from_pydict(data),
        name=name,
        roles=roles,
        ignore=ignore,
        dry=dry,
    )

from_json classmethod

from_json(
    json_str: str,
    name: str,
    roles: Optional[
        Union[Dict[Union[Role, str], Iterable[str]], Roles]
    ] = None,
    ignore: bool = False,
    dry: bool = False,
) -> Union[DataFrame, Roles]

Create a new DataFrame from a JSON string.

It will construct a data frame object in the Engine, fill it with the data read from the JSON string, and return a corresponding DataFrame handle.

PARAMETER DESCRIPTION
json_str

The JSON string containing the data. The json_str should be in the following format:

json_str = "{'col1': [1.0, 2.0, 1.0], 'col2': ['A', 'B', 'C']}"

TYPE: str

name

Name of the data frame to be created.

TYPE: str

roles

Maps the roles to the column names (see colnames).

The roles dictionary is expected to have the following format:

roles = {getml.data.role.numeric: ["colname1", "colname2"],
         getml.data.role.target: ["colname3"]}
Otherwise, you can use the Roles class.

TYPE: Optional[Union[Dict[Union[Role, str], Iterable[str]], Roles]] DEFAULT: None

ignore

Only relevant when roles is not None. Determines what you want to do with any colnames not mentioned in roles. Do you want to ignore them (True) or read them in as unused columns (False)?

TYPE: bool DEFAULT: False

dry

If set to True, the data will not be read. Instead, the method will return the inffered roles.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
Union[DataFrame, Roles]

Handler of the underlying data.

Source code in getml/data/data_frame.py
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
@classmethod
def from_json(
    cls,
    json_str: str,
    name: str,
    roles: Optional[Union[Dict[Union[Role, str], Iterable[str]], Roles]] = None,
    ignore: bool = False,
    dry: bool = False,
) -> Union[DataFrame, Roles]:
    """Create a new DataFrame from a JSON string.

    It will construct a data frame object in the Engine, fill it
    with the data read from the JSON string, and return a
    corresponding [`DataFrame`][getml.DataFrame] handle.

    Args:
        json_str:
            The JSON string containing the data.
            The json_str should be in the following format:
            ```python
            json_str = "{'col1': [1.0, 2.0, 1.0], 'col2': ['A', 'B', 'C']}"
            ```
        name:
            Name of the data frame to be created.

        roles:
            Maps the [`roles`][getml.data.roles] to the
            column names (see [`colnames`][getml.DataFrame.colnames]).

            The `roles` dictionary is expected to have the following format:
            ```python
            roles = {getml.data.role.numeric: ["colname1", "colname2"],
                     getml.data.role.target: ["colname3"]}
            ```
            Otherwise, you can use the [`Roles`][getml.data.Roles] class.

        ignore:
            Only relevant when roles is not None.
            Determines what you want to do with any colnames not
            mentioned in roles. Do you want to ignore them (True)
            or read them in as unused columns (False)?

        dry:
            If set to True, the data will not be read. Instead, the method
            will return the inffered roles.

    Returns:
        Handler of the underlying data.

    """

    if not isinstance(json_str, str):
        raise TypeError("'json_str' must be str.")

    return cls.from_dict(
        data=json.loads(json_str),
        name=name,
        roles=roles,
        ignore=ignore,
        dry=dry,
    )

from_pandas classmethod

from_pandas(
    pandas_df: DataFrame,
    name: str,
    roles: Optional[
        Union[Dict[Union[Role, str], Iterable[str]], Roles]
    ] = None,
    ignore: bool = False,
    dry: bool = False,
) -> Union[DataFrame, Roles]

Create a DataFrame from a pandas.DataFrame.

It will construct a data frame object in the Engine, fill it with the data read from the pandas.DataFrame, and return a corresponding DataFrame handle.

PARAMETER DESCRIPTION
pandas_df

The table to be read.

TYPE: DataFrame

name

Name of the data frame to be created.

TYPE: str

roles

Maps the roles to the column names (see colnames).

The roles dictionary is expected to have the following format:

 roles = {getml.data.role.numeric: ["colname1", "colname2"],
          getml.data.role.target: ["colname3"]}
Otherwise, you can use the Roles class.

TYPE: Optional[Union[Dict[Union[Role, str], Iterable[str]], Roles]] DEFAULT: None

ignore

Only relevant when roles is not None. Determines what you want to do with any colnames not mentioned in roles. Do you want to ignore them (True) or read them in as unused columns (False)?

TYPE: bool DEFAULT: False

dry

If set to True, the data will not be read. Instead, the method will return the inffered roles.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
Union[DataFrame, Roles]

Handler of the underlying data.

Source code in getml/data/data_frame.py
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
@classmethod
def from_pandas(
    cls,
    pandas_df: pd.DataFrame,
    name: str,
    roles: Optional[Union[Dict[Union[Role, str], Iterable[str]], Roles]] = None,
    ignore: bool = False,
    dry: bool = False,
) -> Union[DataFrame, Roles]:
    """Create a DataFrame from a `pandas.DataFrame`.

    It will construct a data frame object in the Engine, fill it
    with the data read from the `pandas.DataFrame`, and
    return a corresponding [`DataFrame`][getml.DataFrame] handle.

    Args:
        pandas_df:
            The table to be read.

        name:
            Name of the data frame to be created.

        roles:
            Maps the [`roles`][getml.data.roles] to the
            column names (see [`colnames`][getml.DataFrame.colnames]).

            The `roles` dictionary is expected to have the following format:
            ```python
             roles = {getml.data.role.numeric: ["colname1", "colname2"],
                      getml.data.role.target: ["colname3"]}
            ```
            Otherwise, you can use the [`Roles`][getml.data.Roles] class.

        ignore:
            Only relevant when roles is not None.
            Determines what you want to do with any colnames not
            mentioned in roles. Do you want to ignore them (True)
            or read them in as unused columns (False)?

        dry:
            If set to True, the data will not be read. Instead, the method
            will return the inffered roles.

    Returns:
        Handler of the underlying data.
    """

    # ------------------------------------------------------------

    if not isinstance(pandas_df, pd.DataFrame):
        raise TypeError("'pandas_df' must be of type pandas.DataFrame.")

    if not isinstance(name, str):
        raise TypeError("'name' must be str.")

    # The content of roles is checked in the class constructor called below.
    if roles is not None and not isinstance(roles, (dict, Roles)):
        raise TypeError("'roles' must be a geml.data.Roles object, a dict or None.")

    if not isinstance(ignore, bool):
        raise TypeError("'ignore' must be bool.")

    if not isinstance(dry, bool):
        raise TypeError("'dry' must be bool.")

    # ------------------------------------------------------------

    sniffed_roles = _sniff_pandas(pandas_df)

    roles = _prepare_roles(roles, sniffed_roles, ignore_sniffed_roles=ignore)

    if dry:
        return roles

    data_frame = cls(name, roles)

    return data_frame.read_pandas(pandas_df=pandas_df, append=False)

from_parquet classmethod

from_parquet(
    fnames: Union[str, Iterable[str]],
    name: str,
    roles: Optional[
        Union[Dict[Union[Role, str], Iterable[str]], Roles]
    ] = None,
    ignore: bool = False,
    dry: bool = False,
    colnames: Iterable[str] = (),
) -> Union[DataFrame, Roles]

Create a DataFrame from parquet files.

This is one of the fastest way to get data into the getML Engine.

PARAMETER DESCRIPTION
fnames

The path of the parquet file(s) to be read.

TYPE: Union[str, Iterable[str]]

name

Name of the data frame to be created.

TYPE: str

roles

Maps the roles to the column names (see colnames).

The roles dictionary is expected to have the following format:

roles = {getml.data.role.numeric: ["colname1", "colname2"],
         getml.data.role.target: ["colname3"]}
Otherwise, you can use the Roles class.

TYPE: Optional[Union[Dict[Union[Role, str], Iterable[str]], Roles]] DEFAULT: None

ignore

Only relevant when roles is not None. Determines what you want to do with any colnames not mentioned in roles. Do you want to ignore them (True) or read them in as unused columns (False)?

TYPE: bool DEFAULT: False

dry

If set to True, the data will not be read. Instead, the method will return the inffered roles.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
Union[DataFrame, Roles]

Handler of the underlying data.

Source code in getml/data/data_frame.py
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
@classmethod
def from_parquet(
    cls,
    fnames: Union[str, Iterable[str]],
    name: str,
    roles: Optional[Union[Dict[Union[Role, str], Iterable[str]], Roles]] = None,
    ignore: bool = False,
    dry: bool = False,
    colnames: Iterable[str] = (),
) -> Union[DataFrame, Roles]:
    """Create a DataFrame from parquet files.

    This is one of the fastest way to get data into the
    getML Engine.

    Args:
        fnames:
            The path of the parquet file(s) to be read.

        name:
            Name of the data frame to be created.

        roles:
            Maps the [`roles`][getml.data.roles] to the
            column names (see [`colnames`][getml.DataFrame.colnames]).

            The `roles` dictionary is expected to have the following format:
            ```python
            roles = {getml.data.role.numeric: ["colname1", "colname2"],
                     getml.data.role.target: ["colname3"]}
            ```
            Otherwise, you can use the [`Roles`][getml.data.Roles] class.

        ignore:
            Only relevant when roles is not None.
            Determines what you want to do with any colnames not
            mentioned in roles. Do you want to ignore them (True)
            or read them in as unused columns (False)?

        dry:
            If set to True, the data will not be read. Instead, the method
            will return the inffered roles.

    Returns:
        Handler of the underlying data.
    """

    # ------------------------------------------------------------

    if isinstance(fnames, str):
        fnames = [fnames]

    if not isinstance(name, str):
        raise TypeError("'name' must be str.")

    # The content of roles is checked in the class constructor called below.
    if roles is not None and not isinstance(roles, (dict, Roles)):
        raise TypeError("'roles' must be a geml.data.Roles object, a dict or None.")

    if not isinstance(ignore, bool):
        raise TypeError("'ignore' must be bool.")

    if not isinstance(dry, bool):
        raise TypeError("'dry' must be bool.")

    # ------------------------------------------------------------

    sniffed_roles = sniff_parquet(fnames, colnames)

    roles = _prepare_roles(roles, sniffed_roles, ignore_sniffed_roles=ignore)

    if dry:
        return roles

    data_frame = cls(name, roles)

    return data_frame.read_parquet(fnames=fnames, append=False, colnames=colnames)

from_pyspark classmethod

from_pyspark(
    spark_df: DataFrame,
    name: str,
    roles: Optional[
        Union[Dict[Union[Role, str], Iterable[str]], Roles]
    ] = None,
    ignore: bool = False,
    dry: bool = False,
) -> Union[DataFrame, Roles]

Create a DataFrame from a pyspark.sql.DataFrame.

It will construct a data frame object in the Engine, fill it with the data read from the pyspark.sql.DataFrame, and return a corresponding DataFrame handle.

PARAMETER DESCRIPTION
spark_df

The table to be read.

TYPE: DataFrame

name

Name of the data frame to be created.

TYPE: str

roles

Maps the roles to the column names (see colnames).

The roles dictionary is expected to have the following format:

roles = {getml.data.role.numeric: ["colname1", "colname2"],
         getml.data.role.target: ["colname3"]}

Otherwise, you can use the Roles class.

TYPE: Optional[Union[Dict[Union[Role, str], Iterable[str]], Roles]] DEFAULT: None

ignore

Only relevant when roles is not None. Determines what you want to do with any colnames not mentioned in roles. Do you want to ignore them (True) or read them in as unused columns (False)?

TYPE: bool DEFAULT: False

dry

If set to True, the data will not be read. Instead, the method will return the inffered roles.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
Union[DataFrame, Roles]

Handler of the underlying data.

Source code in getml/data/data_frame.py
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
@classmethod
def from_pyspark(
    cls,
    spark_df: pyspark.sql.DataFrame,
    name: str,
    roles: Optional[Union[Dict[Union[Role, str], Iterable[str]], Roles]] = None,
    ignore: bool = False,
    dry: bool = False,
) -> Union[DataFrame, Roles]:
    """Create a DataFrame from a `pyspark.sql.DataFrame`.

    It will construct a data frame object in the Engine, fill it
    with the data read from the `pyspark.sql.DataFrame`, and
    return a corresponding [`DataFrame`][getml.DataFrame] handle.

    Args:
        spark_df:
            The table to be read.

        name:
            Name of the data frame to be created.

        roles:
            Maps the [`roles`][getml.data.roles] to the
            column names (see [`colnames`][getml.DataFrame.colnames]).

            The `roles` dictionary is expected to have the following format:
            ```python
            roles = {getml.data.role.numeric: ["colname1", "colname2"],
                     getml.data.role.target: ["colname3"]}
            ```

            Otherwise, you can use the [`Roles`][getml.data.Roles] class.

        ignore:
            Only relevant when roles is not None.
            Determines what you want to do with any colnames not
            mentioned in roles. Do you want to ignore them (True)
            or read them in as unused columns (False)?

        dry:
            If set to True, the data will not be read. Instead, the method
            will return the inffered roles.

    Returns:
            Handler of the underlying data.
    """

    # ------------------------------------------------------------

    if not isinstance(name, str):
        raise TypeError("'name' must be str.")

    # The content of roles is checked in the class constructor called below.
    if roles is not None and not isinstance(roles, (dict, Roles)):
        raise TypeError("'roles' must be a geml.data.Roles object, a dict or None.")

    if not isinstance(ignore, bool):
        raise TypeError("'ignore' must be bool.")

    if not isinstance(dry, bool):
        raise TypeError("'dry' must be bool.")

    # ------------------------------------------------------------

    head = spark_df.limit(2).toPandas()

    sniffed_roles = _sniff_pandas(head)

    roles = _prepare_roles(roles, sniffed_roles, ignore_sniffed_roles=ignore)

    if dry:
        return roles

    data_frame = cls(name, roles)

    return data_frame.read_pyspark(spark_df=spark_df, append=False)

from_s3 classmethod

from_s3(
    bucket: str,
    keys: Iterable[str],
    region: str,
    name: str,
    num_lines_sniffed: int = 1000,
    num_lines_read: int = 0,
    sep: str = ",",
    skip: int = 0,
    colnames: Optional[Iterable[str]] = None,
    roles: Optional[
        Union[Dict[Union[Role, str], Iterable[str]], Roles]
    ] = None,
    ignore: bool = False,
    dry: bool = False,
) -> Union[DataFrame, Roles]

Create a DataFrame from CSV files located in an S3 bucket.

This classmethod will construct a data frame object in the Engine, fill it with the data read from the CSV file(s), and return a corresponding DataFrame handle.

Enterprise edition

This feature is exclusive to the Enterprise edition and is not available in the Community edition. Discover the benefits of the Enterprise edition and compare their features.

For licensing information and technical support, please contact us.

Note

Note that S3 is not supported on Windows.

PARAMETER DESCRIPTION
bucket

The bucket from which to read the files.

TYPE: str

keys

The list of keys (files in the bucket) to be read.

TYPE: Iterable[str]

region

The region in which the bucket is located.

TYPE: str

name

Name of the data frame to be created.

TYPE: str

num_lines_sniffed

Number of lines analyzed by the sniffer.

TYPE: int DEFAULT: 1000

num_lines_read

Number of lines read from each file. Set to 0 to read in the entire file.

TYPE: int DEFAULT: 0

sep

The separator used for separating fields.

TYPE: str DEFAULT: ','

skip

Number of lines to skip at the beginning of each file.

TYPE: int DEFAULT: 0

colnames

The first line of a CSV file usually contains the column names. When this is not the case, you need to explicitly pass them.

TYPE: Optional[Iterable[str]] DEFAULT: None

roles

Maps the roles to the column names (see colnames).

The roles dictionary is expected to have the following format:

roles = {getml.data.role.numeric: ["colname1", "colname2"],
         getml.data.role.target: ["colname3"]}
Otherwise, you can use the Roles class.

TYPE: Optional[Union[Dict[Union[Role, str], Iterable[str]], Roles]] DEFAULT: None

ignore

Only relevant when roles is not None. Determines what you want to do with any colnames not mentioned in roles. Do you want to ignore them (True) or read them in as unused columns (False)?

TYPE: bool DEFAULT: False

dry

If set to True, the data will not be read. Instead, the method will return the inffered roles.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
Union[DataFrame, Roles]

Handler of the underlying data.

Example

Let's assume you have two CSV files - file1.csv and file2.csv - in the bucket. You can import their data into the getML Engine using the following commands:

getml.engine.set_s3_access_key_id("YOUR-ACCESS-KEY-ID")
getml.engine.set_s3_secret_access_key("YOUR-SECRET-ACCESS-KEY")

data_frame_expd = data.DataFrame.from_s3(
    bucket="your-bucket-name",
    keys=["file1.csv", "file2.csv"],
    region="us-east-2",
    name="MY DATA FRAME",
    sep=';'
)

You can also set the access credential as environment variables before you launch the getML Engine.

Also refer to the documentation on from_csv for further information on overriding the CSV sniffer for greater type safety.

Source code in getml/data/data_frame.py
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
@classmethod
def from_s3(
    cls,
    bucket: str,
    keys: Iterable[str],
    region: str,
    name: str,
    num_lines_sniffed: int = 1000,
    num_lines_read: int = 0,
    sep: str = ",",
    skip: int = 0,
    colnames: Optional[Iterable[str]] = None,
    roles: Optional[Union[Dict[Union[Role, str], Iterable[str]], Roles]] = None,
    ignore: bool = False,
    dry: bool = False,
) -> Union[DataFrame, Roles]:
    """Create a DataFrame from CSV files located in an S3 bucket.

    This classmethod will construct a data
    frame object in the Engine, fill it with the data read from
    the CSV file(s), and return a corresponding
    [`DataFrame`][getml.DataFrame] handle.

    enterprise-adm: Enterprise edition
        This feature is exclusive to the Enterprise edition and is not available in the Community edition. Discover the [benefits of the Enterprise edition][enterprise-benefits] and [compare their features][enterprise-feature-list].

        For licensing information and technical support, please [contact us][contact-page].

    Note:
        Note that S3 is not supported on Windows.

    Args:
        bucket:
            The bucket from which to read the files.

        keys:
            The list of keys (files in the bucket) to be read.

        region:
            The region in which the bucket is located.

        name:
            Name of the data frame to be created.

        num_lines_sniffed:
            Number of lines analyzed by the sniffer.

        num_lines_read:
            Number of lines read from each file.
            Set to 0 to read in the entire file.

        sep:
            The separator used for separating fields.

        skip:
            Number of lines to skip at the beginning of each file.

        colnames:
            The first line of a CSV file
            usually contains the column names. When this is not the case,
            you need to explicitly pass them.

        roles:
            Maps the [`roles`][getml.data.roles] to the
            column names (see [`colnames`][getml.DataFrame.colnames]).

            The `roles` dictionary is expected to have the following format:
            ```python
            roles = {getml.data.role.numeric: ["colname1", "colname2"],
                     getml.data.role.target: ["colname3"]}
            ```
            Otherwise, you can use the [`Roles`][getml.data.Roles] class.

        ignore:
            Only relevant when roles is not None.
            Determines what you want to do with any colnames not
            mentioned in roles. Do you want to ignore them (True)
            or read them in as unused columns (False)?

        dry:
            If set to True, the data will not be read. Instead, the method
            will return the inffered roles.

    Returns:
            Handler of the underlying data.

    ??? example
        Let's assume you have two CSV files - *file1.csv* and
        *file2.csv* - in the bucket. You can
        import their data into the getML Engine using the following
        commands:
        ```python
        getml.engine.set_s3_access_key_id("YOUR-ACCESS-KEY-ID")
        getml.engine.set_s3_secret_access_key("YOUR-SECRET-ACCESS-KEY")

        data_frame_expd = data.DataFrame.from_s3(
            bucket="your-bucket-name",
            keys=["file1.csv", "file2.csv"],
            region="us-east-2",
            name="MY DATA FRAME",
            sep=';'
        )
        ```

        You can also set the access credential as environment variables
        before you launch the getML Engine.

        Also refer to the documentation on [`from_csv`][getml.DataFrame.from_csv]
        for further information on overriding the CSV sniffer for greater
        type safety.

    """

    if isinstance(keys, str):
        keys = [keys]

    if not isinstance(bucket, str):
        raise TypeError("'bucket' must be str.")

    if not _is_non_empty_typed_list(keys, str):
        raise TypeError("'keys' must be either a string or a list of str")

    if not isinstance(region, str):
        raise TypeError("'region' must be str.")

    if not isinstance(name, str):
        raise TypeError("'name' must be str.")

    if not isinstance(num_lines_sniffed, numbers.Real):
        raise TypeError("'num_lines_sniffed' must be a real number")

    if not isinstance(num_lines_read, numbers.Real):
        raise TypeError("'num_lines_read' must be a real number")

    if not isinstance(sep, str):
        raise TypeError("'sep' must be str.")

    if not isinstance(skip, numbers.Real):
        raise TypeError("'skip' must be a real number")

    if roles is not None and not isinstance(roles, (dict, Roles)):
        raise TypeError("'roles' must be a geml.data.Roles object, a dict or None.")

    if not isinstance(ignore, bool):
        raise TypeError("'ignore' must be bool.")

    if not isinstance(dry, bool):
        raise TypeError("'dry' must be bool.")

    if colnames is not None and not _is_non_empty_typed_list(colnames, str):
        raise TypeError(
            "'colnames' must be either be None or a non-empty list of str."
        )

    sniffed_roles = _sniff_s3(
        bucket=bucket,
        keys=keys,
        region=region,
        num_lines_sniffed=int(num_lines_sniffed),
        sep=sep,
        skip=int(skip),
        colnames=colnames,
    )

    roles = _prepare_roles(roles, sniffed_roles, ignore)

    if dry:
        return roles

    data_frame = cls(name, roles)

    return data_frame.read_s3(
        bucket=bucket,
        keys=keys,
        region=region,
        append=False,
        sep=sep,
        num_lines_read=int(num_lines_read),
        skip=int(skip),
        colnames=colnames,
    )

from_view classmethod

from_view(
    view: View, name: str, dry: bool = False
) -> Union[DataFrame, Roles]

Create a DataFrame from a View.

This classmethod will construct a data frame object in the Engine, fill it with the data read from the View, and return a corresponding DataFrame handle.

PARAMETER DESCRIPTION
view

The view from which we want to read the data.

TYPE: View

name

Name of the data frame to be created.

TYPE: str

dry

If set to True, the data will not be read. Instead, the method will return an empty data frame with the roles set as inferred.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
Union[DataFrame, Roles]

Handler of the underlying data.

Source code in getml/data/data_frame.py
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
@classmethod
def from_view(
    cls,
    view: View,
    name: str,
    dry: bool = False,
) -> Union[DataFrame, Roles]:
    """Create a DataFrame from a [`View`][getml.data.View].

    This classmethod will construct a data
    frame object in the Engine, fill it with the data read from
    the [`View`][getml.data.View], and return a corresponding
    [`DataFrame`][getml.DataFrame] handle.

    Args:
        view:
            The view from which we want to read the data.

        name:
            Name of the data frame to be created.

        dry:
            If set to True, the data will not be read. Instead, the method
            will return an empty data frame with the roles set as inferred.

    Returns:
            Handler of the underlying data.


    """
    # ------------------------------------------------------------

    if not isinstance(view, View):
        raise TypeError("'view' must be getml.data.View.")

    if not isinstance(name, str):
        raise TypeError("'name' must be str.")

    if not isinstance(dry, bool):
        raise TypeError("'dry' must be bool.")

    # ------------------------------------------------------------

    if dry:
        return view.roles

    data_frame = cls(name, view.roles)

    # ------------------------------------------------------------

    return data_frame.read_view(view=view, append=False)

load

load() -> DataFrame

Loads saved data from disk.

The data frame object holding the same name as the current DataFrame instance will be loaded from disk into the getML Engine and updates the current handler using refresh.

Example

First, we have to create and import data sets.

d, _ = getml.datasets.make_numerical(population_name = 'test')
getml.data.list_data_frames()

In the output of list_data_frames we can find our underlying data frame object 'test' listed under the 'in_memory' key (it was created and imported by make_numerical). This means the getML Engine does only hold it in memory (RAM) yet, and we still have to save it to disk in order to load it again or to prevent any loss of information between different sessions.

d.save()
getml.data.list_data_frames()
d2 = getml.DataFrame(name = 'test').load()

RETURNS DESCRIPTION
DataFrame

Updated handle the underlying data frame in the getML

DataFrame

Engine.

Note

When invoking load all changes of the underlying data frame object that took place after the last call to the save method will be lost. Thus, this method enables you to undo changes applied to the DataFrame.

d, _ = getml.datasets.make_numerical()
d.save()

# Accidental change we want to undo
d.rm('column_01')

d.load()
If save hasn't been called on the current instance yet, or it wasn't stored to disk in a previous session, load will throw an exception

File or directory '../projects/X/data/Y/' not found!

Alternatively, load_data_frame offers an easier way of creating DataFrame handlers to data in the getML Engine.

Source code in getml/data/data_frame.py
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
def load(self) -> DataFrame:
    """Loads saved data from disk.

    The data frame object holding the same name as the current
    [`DataFrame`][getml.DataFrame] instance will be loaded from
    disk into the getML Engine and updates the current handler
    using [`refresh`][getml.DataFrame.refresh].

    ??? example
        First, we have to create and import data sets.
        ```python
        d, _ = getml.datasets.make_numerical(population_name = 'test')
        getml.data.list_data_frames()
        ```

        In the output of [`list_data_frames`][getml.data.list_data_frames] we
        can find our underlying data frame object 'test' listed
        under the 'in_memory' key (it was created and imported by
        [`make_numerical`][getml.datasets.make_numerical]). This means the
        getML Engine does only hold it in memory (RAM) yet, and we
        still have to [`save`][getml.DataFrame.save] it to
        disk in order to [`load`][getml.DataFrame.load] it
        again or to prevent any loss of information between
        different sessions.
        ```python
        d.save()
        getml.data.list_data_frames()
        d2 = getml.DataFrame(name = 'test').load()
        ```

    Returns:
            Updated handle the underlying data frame in the getML
            Engine.

    Note:
        When invoking [`load`][getml.DataFrame.load] all
        changes of the underlying data frame object that took
        place after the last call to the
        [`save`][getml.DataFrame.save] method will be
        lost. Thus, this method  enables you to undo changes
        applied to the [`DataFrame`][getml.DataFrame].
        ```python
        d, _ = getml.datasets.make_numerical()
        d.save()

        # Accidental change we want to undo
        d.rm('column_01')

        d.load()
        ```
        If [`save`][getml.DataFrame.save] hasn't been called
        on the current instance yet, or it wasn't stored to disk in
        a previous session, [`load`][getml.DataFrame.load]
        will throw an exception

            File or directory '../projects/X/data/Y/' not found!

        Alternatively, [`load_data_frame`][getml.data.load_data_frame]
        offers an easier way of creating
        [`DataFrame`][getml.DataFrame] handlers to data in the
        getML Engine.

    """

    cmd: Dict[str, Any] = {}
    cmd["type_"] = "DataFrame.load"
    cmd["name_"] = self.name
    comm.send(cmd)
    return self.refresh()

nbytes

nbytes() -> uint64

Size of the data stored in the underlying data frame in the getML Engine.

RETURNS DESCRIPTION
uint64

Size of the underlying object in bytes.

Source code in getml/data/data_frame.py
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
def nbytes(self) -> np.uint64:
    """Size of the data stored in the underlying data frame in the getML
    Engine.

    Returns:
            Size of the underlying object in bytes.

    """

    cmd: Dict[str, Any] = {}
    cmd["type_"] = "DataFrame.nbytes"
    cmd["name_"] = self.name

    with comm.send_and_get_socket(cmd) as sock:
        msg = comm.recv_string(sock)
        if msg != "Found!":
            sock.close()
            comm.handle_engine_exception(msg)
        nbytes = comm.recv_string(sock)

    return np.uint64(nbytes)

ncols

ncols() -> int

Number of columns in the current instance.

RETURNS DESCRIPTION
int

Overall number of columns

Source code in getml/data/data_frame.py
2285
2286
2287
2288
2289
2290
2291
2292
def ncols(self) -> int:
    """
    Number of columns in the current instance.

    Returns:
            Overall number of columns
    """
    return len(self.colnames)

nrows

nrows() -> int

Number of rows in the current instance.

RETURNS DESCRIPTION
int

Overall number of rows

Source code in getml/data/data_frame.py
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
def nrows(self) -> int:
    """
    Number of rows in the current instance.

    Returns:
            Overall number of rows
    """

    cmd: Dict[str, Any] = {}
    cmd["type_"] = "DataFrame.nrows"
    cmd["name_"] = self.name

    with comm.send_and_get_socket(cmd) as sock:
        msg = comm.recv_string(sock)
        if msg != "Found!":
            sock.close()
            comm.handle_engine_exception(msg)
        nrows = comm.recv_string(sock)

    return int(nrows)

read_arrow

read_arrow(
    table: Union[RecordBatch, Table, Iterable[RecordBatch]],
    append: bool = False,
) -> DataFrame

Uploads a pyarrow.Table or pyarrow.RecordBatch to the getML Engine.

Replaces the actual content of the underlying data frame in the getML Engine with table.

PARAMETER DESCRIPTION
table

The arrow tablelike to be read as a DataFrame.

TYPE: Union[RecordBatch, Table, Iterable[RecordBatch]]

append

If a data frame object holding the same name is already present in the getML Engine, should the content in query be appended or replace the existing data?

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
DataFrame

Current instance.

Note

For columns containing pandas.Timestamp there can be small inconsistencies in the order of microseconds when sending the data to the getML Engine. This is due to the way the underlying information is stored.

Source code in getml/data/data_frame.py
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
def read_arrow(
    self,
    table: Union[pa.RecordBatch, pa.Table, Iterable[pa.RecordBatch]],
    append: bool = False,
) -> DataFrame:
    """Uploads a `pyarrow.Table` or `pyarrow.RecordBatch` to the getML Engine.

    Replaces the actual content of the underlying data frame in
    the getML Engine with `table`.

    Args:
        table:
            The arrow tablelike to be read as a `DataFrame`.

        append:
            If a data frame object holding the same `name` is
            already present in the getML Engine, should the content in
            `query` be appended or replace the existing data?

    Returns:
            Current instance.

    Note:
        For columns containing `pandas.Timestamp` there can
        be small inconsistencies in the order of microseconds
        when sending the data to the getML Engine. This is due to
        the way the underlying information is stored.
    """

    # ------------------------------------------------------------

    inferred_schema, batches = to_arrow_batches(table)

    if not isinstance(append, bool):
        raise TypeError("'append' must be bool.")

    # ------------------------------------------------------------

    if self.ncols() == 0:
        raise Exception(
            """Reading data is only possible in a DataFrame with more than zero
            columns. You can pre-define columns during
            initialization of the DataFrame or use the classmethod
            from_pandas(...)."""
        )

    # ------------------------------------------------------------

    preprocessed_schema = preprocess_arrow_schema(inferred_schema, self.roles)
    batches = (cast_arrow_batch(batch, preprocessed_schema) for batch in batches)

    read_arrow_batches(batches, preprocessed_schema, self, append)

    return self.refresh()

read_csv

read_csv(
    fnames: Iterable[str],
    append: bool = False,
    quotechar: str = '"',
    sep: str = ",",
    num_lines_read: int = 0,
    skip: int = 0,
    colnames: Optional[Iterable[str]] = None,
    time_formats: Optional[Iterable[str]] = None,
    verbose: bool = True,
    block_size: int = DEFAULT_CSV_READ_BLOCK_SIZE,
    in_batches: bool = False,
) -> DataFrame

Read CSV files.

It is assumed that the first line of each CSV file contains a header with the column names.

PARAMETER DESCRIPTION
fnames

CSV file paths to be read.

TYPE: Iterable[str]

append

If a data frame object holding the same name is already present in the getML, should the content of the CSV files in fnames be appended or replace the existing data?

TYPE: bool DEFAULT: False

quotechar

The character used to wrap strings.

TYPE: str DEFAULT: '"'

sep

The separator used for separating fields.

TYPE: str DEFAULT: ','

num_lines_read

Number of lines read from each file. Set to 0 to read in the entire file.

TYPE: int DEFAULT: 0

skip

Number of lines to skip at the beginning of each file.

TYPE: int DEFAULT: 0

colnames

The first line of a CSV file usually contains the column names. When this is not the case, you need to explicitly pass them.

TYPE: Optional[Iterable[str]] DEFAULT: None

time_formats

The list of formats tried when parsing time stamps.

The formats are allowed to contain the following special characters:

  • %w - abbreviated weekday (Mon, Tue, ...)
  • %W - full weekday (Monday, Tuesday, ...)
  • %b - abbreviated month (Jan, Feb, ...)
  • %B - full month (January, February, ...)
  • %d - zero-padded day of month (01 .. 31)
  • %e - day of month (1 .. 31)
  • %f - space-padded day of month ( 1 .. 31)
  • %m - zero-padded month (01 .. 12)
  • %n - month (1 .. 12)
  • %o - space-padded month ( 1 .. 12)
  • %y - year without century (70)
  • %Y - year with century (1970)
  • %H - hour (00 .. 23)
  • %h - hour (00 .. 12)
  • %a - am/pm
  • %A - AM/PM
  • %M - minute (00 .. 59)
  • %S - second (00 .. 59)
  • %s - seconds and microseconds (equivalent to %S.%F)
  • %i - millisecond (000 .. 999)
  • %c - centisecond (0 .. 9)
  • %F - fractional seconds/microseconds (000000 - 999999)
  • %z - time zone differential in ISO 8601 format (Z or +NN.NN)
  • %Z - time zone differential in RFC format (GMT or +NNNN)
  • %% - percent sign

TYPE: Optional[Iterable[str]] DEFAULT: None

verbose

If True, when fnames are urls, the filenames are printed to stdout during the download.

TYPE: bool DEFAULT: True

block_size

The number of bytes read with each batch. Passed down to pyarrow.

TYPE: int DEFAULT: DEFAULT_CSV_READ_BLOCK_SIZE

in_batches

If True, read blocks streamwise manner and send those batches to the engine. Blocks are read and sent to the engine sequentially. While more memory efficient, streaming in batches is slower as it is inherently single-threaded. If False (default) the data is read with multiple threads into arrow first and sent to the engine afterwards.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
DataFrame

Handler of the underlying data.

Source code in getml/data/data_frame.py
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
def read_csv(
    self,
    fnames: Iterable[str],
    append: bool = False,
    quotechar: str = '"',
    sep: str = ",",
    num_lines_read: int = 0,
    skip: int = 0,
    colnames: Optional[Iterable[str]] = None,
    time_formats: Optional[Iterable[str]] = None,
    verbose: bool = True,
    block_size: int = DEFAULT_CSV_READ_BLOCK_SIZE,
    in_batches: bool = False,
) -> DataFrame:
    """Read CSV files.

    It is assumed that the first line of each CSV file contains a
    header with the column names.

    Args:
        fnames:
            CSV file paths to be read.

        append:
            If a data frame object holding the same ``name`` is
            already present in the getML, should the content of
            the CSV files in `fnames` be appended or replace the
            existing data?

        quotechar:
            The character used to wrap strings.

        sep:
            The separator used for separating fields.

        num_lines_read:
            Number of lines read from each file.
            Set to 0 to read in the entire file.

        skip:
            Number of lines to skip at the beginning of each file.

        colnames:
            The first line of a CSV file
            usually contains the column names.
            When this is not the case, you need to explicitly pass them.

        time_formats:
            The list of formats tried when parsing time stamps.

            The formats are allowed to contain the following
            special characters:

            * %w - abbreviated weekday (Mon, Tue, ...)
            * %W - full weekday (Monday, Tuesday, ...)
            * %b - abbreviated month (Jan, Feb, ...)
            * %B - full month (January, February, ...)
            * %d - zero-padded day of month (01 .. 31)
            * %e - day of month (1 .. 31)
            * %f - space-padded day of month ( 1 .. 31)
            * %m - zero-padded month (01 .. 12)
            * %n - month (1 .. 12)
            * %o - space-padded month ( 1 .. 12)
            * %y - year without century (70)
            * %Y - year with century (1970)
            * %H - hour (00 .. 23)
            * %h - hour (00 .. 12)
            * %a - am/pm
            * %A - AM/PM
            * %M - minute (00 .. 59)
            * %S - second (00 .. 59)
            * %s - seconds and microseconds (equivalent to %S.%F)
            * %i - millisecond (000 .. 999)
            * %c - centisecond (0 .. 9)
            * %F - fractional seconds/microseconds (000000 - 999999)
            * %z - time zone differential in ISO 8601 format (Z or +NN.NN)
            * %Z - time zone differential in RFC format (GMT or +NNNN)
            * %% - percent sign

        verbose:
            If True, when `fnames` are urls, the filenames are printed to
            stdout during the download.

        block_size:
            The number of bytes read with each batch. Passed down to
            pyarrow.

        in_batches:
            If True, read blocks streamwise manner and send those batches to
            the engine. Blocks are read and sent to the engine sequentially.
            While more memory efficient, streaming in batches is slower as
            it is inherently single-threaded. If False (default) the data is
            read with multiple threads into arrow first and sent to the engine
            afterwards.

    Returns:
            Handler of the underlying data.

    """

    time_formats = time_formats or constants.TIME_FORMATS

    if isinstance(fnames, str):
        fnames = [fnames]

    if not _is_non_empty_typed_list(fnames, str):
        raise TypeError("'fnames' must be either a string or a list of str")

    if not isinstance(append, bool):
        raise TypeError("'append' must be bool.")

    if not isinstance(quotechar, str):
        raise TypeError("'quotechar' must be str.")

    if not isinstance(sep, str):
        raise TypeError("'sep' must be str.")

    if not isinstance(num_lines_read, numbers.Real):
        raise TypeError("'num_lines_read' must be a real number")

    if not isinstance(skip, numbers.Real):
        raise TypeError("'skip' must be a real number")

    if not _is_non_empty_typed_list(time_formats, str):
        raise TypeError("'time_formats' must be a non-empty list of str")

    if colnames:
        if not _is_iterable_not_str_of_type(colnames, str):
            raise TypeError("'colnames' must be an iterable of str")

    if self.ncols() == 0:
        raise Exception(
            """Reading data is only possible in a DataFrame with more than zero
            columns. You can pre-define columns during
            initialization of the DataFrame or use the classmethod
            from_csv(...)."""
        )

    if not _is_non_empty_typed_list(fnames, str):
        raise TypeError(
            """'fnames' must be a list containing at
            least one path to a CSV file"""
        )

    fnames_ = _retrieve_urls(fnames, verbose)

    if colnames is None:
        colnames = ()

    stream_read_csv = stream_csv if in_batches else read_csv

    readers = (
        stream_read_csv(
            Path(fname),
            roles=self.roles,
            skip_rows=skip,
            column_names=colnames,
            delimiter=sep,
            quote_char=quotechar,
            block_size=block_size,
        )
        for fname in fnames_
    )

    for batches in readers:
        first_batch = next(batches)
        schema = first_batch.schema
        read_arrow_batches(iter((first_batch, *batches)), schema, self, append)
        if not append:
            append = True

    return self

read_json

read_json(
    json_str: str,
    append: bool = False,
    time_formats: Optional[Iterable[str]] = None,
) -> DataFrame

Fill from JSON

Fills the data frame with data from a JSON string.

Args:

json_str:
    The JSON string containing the data.

append:
    If a data frame object holding the same ``name`` is
    already present in the getML, should the content of
    `json_str` be appended or replace the existing data?

time_formats:
    The list of formats tried when parsing time stamps.
    The formats are allowed to contain the following
    special characters:

    * %w - abbreviated weekday (Mon, Tue, ...)
    * %W - full weekday (Monday, Tuesday, ...)
    * %b - abbreviated month (Jan, Feb, ...)
    * %B - full month (January, February, ...)
    * %d - zero-padded day of month (01 .. 31)
    * %e - day of month (1 .. 31)
    * %f - space-padded day of month ( 1 .. 31)
    * %m - zero-padded month (01 .. 12)
    * %n - month (1 .. 12)
    * %o - space-padded month ( 1 .. 12)
    * %y - year without century (70)
    * %Y - year with century (1970)
    * %H - hour (00 .. 23)
    * %h - hour (00 .. 12)
    * %a - am/pm
    * %A - AM/PM
    * %M - minute (00 .. 59)
    * %S - second (00 .. 59)
    * %s - seconds and microseconds (equivalent to %S.%F)
    * %i - millisecond (000 .. 999)
    * %c - centisecond (0 .. 9)
    * %F - fractional seconds/microseconds (000000 - 999999)
    * %z - time zone differential in ISO 8601 format (Z or +NN.NN)
    * %Z - time zone differential in RFC format (GMT or +NNNN)
    * %% - percent sign
RETURNS DESCRIPTION
DataFrame

Handler of the underlying data.

Note

This does not support NaN values. If you want support for NaN, use from_json instead.

Source code in getml/data/data_frame.py
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
def read_json(
    self,
    json_str: str,
    append: bool = False,
    time_formats: Optional[Iterable[str]] = None,
) -> DataFrame:
    """Fill from JSON

    Fills the data frame with data from a JSON string.

    Args:

        json_str:
            The JSON string containing the data.

        append:
            If a data frame object holding the same ``name`` is
            already present in the getML, should the content of
            `json_str` be appended or replace the existing data?

        time_formats:
            The list of formats tried when parsing time stamps.
            The formats are allowed to contain the following
            special characters:

            * %w - abbreviated weekday (Mon, Tue, ...)
            * %W - full weekday (Monday, Tuesday, ...)
            * %b - abbreviated month (Jan, Feb, ...)
            * %B - full month (January, February, ...)
            * %d - zero-padded day of month (01 .. 31)
            * %e - day of month (1 .. 31)
            * %f - space-padded day of month ( 1 .. 31)
            * %m - zero-padded month (01 .. 12)
            * %n - month (1 .. 12)
            * %o - space-padded month ( 1 .. 12)
            * %y - year without century (70)
            * %Y - year with century (1970)
            * %H - hour (00 .. 23)
            * %h - hour (00 .. 12)
            * %a - am/pm
            * %A - AM/PM
            * %M - minute (00 .. 59)
            * %S - second (00 .. 59)
            * %s - seconds and microseconds (equivalent to %S.%F)
            * %i - millisecond (000 .. 999)
            * %c - centisecond (0 .. 9)
            * %F - fractional seconds/microseconds (000000 - 999999)
            * %z - time zone differential in ISO 8601 format (Z or +NN.NN)
            * %Z - time zone differential in RFC format (GMT or +NNNN)
            * %% - percent sign

    Returns:
            Handler of the underlying data.

    Note:
        This does not support NaN values. If you want support for NaN,
        use [`from_json`][getml.DataFrame.from_json] instead.

    """

    time_formats = time_formats or constants.TIME_FORMATS

    if self.ncols() == 0:
        raise Exception(
            """Reading data is only possible in a DataFrame with more than zero
            columns. You can pre-define columns during
            initialization of the DataFrame or use the classmethod
            from_json(...)."""
        )

    if not isinstance(json_str, str):
        raise TypeError("'json_str' must be of type str")

    if not isinstance(append, bool):
        raise TypeError("'append' must be of type bool")

    if not _is_non_empty_typed_list(time_formats, str):
        raise TypeError(
            """'time_formats' must be a list of strings
            containing at least one time format"""
        )

    cmd: Dict[str, Any] = {}
    cmd["type_"] = "DataFrame.from_json"
    cmd["name_"] = self.name

    cmd["categorical_"] = self._categorical_names
    cmd["join_keys_"] = self._join_key_names
    cmd["numerical_"] = self._numerical_names
    cmd["targets_"] = self._target_names
    cmd["text_"] = self._text_names
    cmd["time_stamps_"] = self._time_stamp_names
    cmd["unused_floats_"] = self._unused_float_names
    cmd["unused_strings_"] = self._unused_string_names

    cmd["append_"] = append
    cmd["time_formats_"] = time_formats

    with comm.send_and_get_socket(cmd) as sock:
        comm.send_string(sock, json_str)
        msg = comm.recv_string(sock)

    if msg != "Success!":
        comm.handle_engine_exception(msg)

    return self

read_parquet

read_parquet(
    fnames: Union[str, Iterable[str]],
    append: bool = False,
    verbose: bool = False,
    colnames: Iterable[str] = (),
) -> DataFrame

Read a parquet file.

PARAMETER DESCRIPTION
fnames

The filepath of the parquet file(s) to be read.

TYPE: Union[str, Iterable[str]]

append

If a data frame object holding the same name is already present in the getML, should the content of the CSV files in fnames be appended or replace the existing data?

TYPE: bool DEFAULT: False

verbose

If True, when fnames are urls, the filenames are printed to stdout during the download.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
DataFrame

Handler of the underlying data.

Source code in getml/data/data_frame.py
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
def read_parquet(
    self,
    fnames: Union[str, Iterable[str]],
    append: bool = False,
    verbose: bool = False,
    colnames: Iterable[str] = (),
) -> DataFrame:
    """Read a parquet file.

    Args:
        fnames:
            The filepath of the parquet file(s) to be read.

        append:
            If a data frame object holding the same ``name`` is
            already present in the getML, should the content of
            the CSV files in `fnames` be appended or replace the
            existing data?

        verbose:
            If True, when `fnames` are urls, the filenames are printed to
            stdout during the download.

    Returns:
        Handler of the underlying data.
    """

    if isinstance(fnames, str):
        fnames = [fnames]

    if not isinstance(append, bool):
        raise TypeError("'append' must be bool.")

    if not colnames:
        colnames = self.colnames

    if self.ncols() == 0:
        raise Exception(
            """Reading data is only possible in a DataFrame with more than
            zero columns. You can pre-define columns during
            initialization of the DataFrame or use the classmethod
            from_parquet(...)."""
        )

    fnames = _retrieve_urls(fnames, verbose)

    readers = (pq.ParquetFile(fname) for fname in fnames)

    for reader in readers:
        inferred_schema = reader.schema_arrow
        preprocessed_schema = preprocess_arrow_schema(inferred_schema, self.roles)
        read_arrow_batches(
            reader.iter_batches(columns=colnames),
            preprocessed_schema,
            self,
            append,
        )
        if not append:
            append = True

    return self

read_s3

read_s3(
    bucket: str,
    keys: Iterable[str],
    region: str,
    append: bool = False,
    sep: str = ",",
    num_lines_read: int = 0,
    skip: int = 0,
    colnames: Optional[Iterable[str]] = None,
    time_formats: Optional[Iterable[str]] = None,
) -> DataFrame

Read CSV files from an S3 bucket.

It is assumed that the first line of each CSV file contains a header with the column names.

Enterprise edition

This feature is exclusive to the Enterprise edition and is not available in the Community edition. Discover the benefits of the Enterprise edition and compare their features.

For licensing information and technical support, please contact us.

Note

Note that S3 is not supported on Windows.

PARAMETER DESCRIPTION
bucket

The bucket from which to read the files.

TYPE: str

keys

The list of keys (files in the bucket) to be read.

TYPE: Iterable[str]

region

The region in which the bucket is located.

TYPE: str

append

If a data frame object holding the same name is already present in the getML, should the content of the CSV files in fnames be appended or replace the existing data?

TYPE: bool DEFAULT: False

sep

The separator used for separating fields.

TYPE: str DEFAULT: ','

num_lines_read

Number of lines read from each file. Set to 0 to read in the entire file.

TYPE: int DEFAULT: 0

skip

Number of lines to skip at the beginning of each file.

TYPE: int DEFAULT: 0

colnames

The first line of a CSV file usually contains the column names. When this is not the case, you need to explicitly pass them.

TYPE: Optional[Iterable[str]] DEFAULT: None

time_formats

The list of formats tried when parsing time stamps.

The formats are allowed to contain the following special characters:

  • %w - abbreviated weekday (Mon, Tue, ...)
  • %W - full weekday (Monday, Tuesday, ...)
  • %b - abbreviated month (Jan, Feb, ...)
  • %B - full month (January, February, ...)
  • %d - zero-padded day of month (01 .. 31)
  • %e - day of month (1 .. 31)
  • %f - space-padded day of month ( 1 .. 31)
  • %m - zero-padded month (01 .. 12)
  • %n - month (1 .. 12)
  • %o - space-padded month ( 1 .. 12)
  • %y - year without century (70)
  • %Y - year with century (1970)
  • %H - hour (00 .. 23)
  • %h - hour (00 .. 12)
  • %a - am/pm
  • %A - AM/PM
  • %M - minute (00 .. 59)
  • %S - second (00 .. 59)
  • %s - seconds and microseconds (equivalent to %S.%F)
  • %i - millisecond (000 .. 999)
  • %c - centisecond (0 .. 9)
  • %F - fractional seconds/microseconds (000000 - 999999)
  • %z - time zone differential in ISO 8601 format (Z or +NN.NN)
  • %Z - time zone differential in RFC format (GMT or +NNNN)
  • %% - percent sign

TYPE: Optional[Iterable[str]] DEFAULT: None

RETURNS DESCRIPTION
DataFrame

Handler of the underlying data.

Source code in getml/data/data_frame.py
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
def read_s3(
    self,
    bucket: str,
    keys: Iterable[str],
    region: str,
    append: bool = False,
    sep: str = ",",
    num_lines_read: int = 0,
    skip: int = 0,
    colnames: Optional[Iterable[str]] = None,
    time_formats: Optional[Iterable[str]] = None,
) -> DataFrame:
    """Read CSV files from an S3 bucket.

    It is assumed that the first line of each CSV file contains a
    header with the column names.

    enterprise-adm: Enterprise edition
        This feature is exclusive to the Enterprise edition and is not available in the Community edition. Discover the [benefits of the Enterprise edition][enterprise-benefits] and [compare their features][enterprise-feature-list].

        For licensing information and technical support, please [contact us][contact-page].

    Note:
        Note that S3 is not supported on Windows.

    Args:
        bucket:
            The bucket from which to read the files.

        keys:
            The list of keys (files in the bucket) to be read.

        region:
            The region in which the bucket is located.

        append:
            If a data frame object holding the same ``name`` is
            already present in the getML, should the content of
            the CSV files in `fnames` be appended or replace the
            existing data?

        sep:
            The separator used for separating fields.

        num_lines_read:
            Number of lines read from each file.
            Set to 0 to read in the entire file.

        skip:
            Number of lines to skip at the beginning of each file.

        colnames:
            The first line of a CSV file
            usually contains the column names.
            When this is not the case, you need to explicitly pass them.

        time_formats:
            The list of formats tried when parsing time stamps.

            The formats are allowed to contain the following
            special characters:

            * %w - abbreviated weekday (Mon, Tue, ...)
            * %W - full weekday (Monday, Tuesday, ...)
            * %b - abbreviated month (Jan, Feb, ...)
            * %B - full month (January, February, ...)
            * %d - zero-padded day of month (01 .. 31)
            * %e - day of month (1 .. 31)
            * %f - space-padded day of month ( 1 .. 31)
            * %m - zero-padded month (01 .. 12)
            * %n - month (1 .. 12)
            * %o - space-padded month ( 1 .. 12)
            * %y - year without century (70)
            * %Y - year with century (1970)
            * %H - hour (00 .. 23)
            * %h - hour (00 .. 12)
            * %a - am/pm
            * %A - AM/PM
            * %M - minute (00 .. 59)
            * %S - second (00 .. 59)
            * %s - seconds and microseconds (equivalent to %S.%F)
            * %i - millisecond (000 .. 999)
            * %c - centisecond (0 .. 9)
            * %F - fractional seconds/microseconds (000000 - 999999)
            * %z - time zone differential in ISO 8601 format (Z or +NN.NN)
            * %Z - time zone differential in RFC format (GMT or +NNNN)
            * %% - percent sign

    Returns:
            Handler of the underlying data.

    """

    time_formats = time_formats or constants.TIME_FORMATS

    if isinstance(keys, str):
        keys = [keys]

    if not isinstance(bucket, str):
        raise TypeError("'bucket' must be str.")

    if not _is_non_empty_typed_list(keys, str):
        raise TypeError("'keys' must be either a string or a list of str")

    if not isinstance(region, str):
        raise TypeError("'region' must be str.")

    if not isinstance(append, bool):
        raise TypeError("'append' must be bool.")

    if not isinstance(sep, str):
        raise TypeError("'sep' must be str.")

    if not isinstance(num_lines_read, numbers.Real):
        raise TypeError("'num_lines_read' must be a real number")

    if not isinstance(skip, numbers.Real):
        raise TypeError("'skip' must be a real number")

    if not _is_non_empty_typed_list(time_formats, str):
        raise TypeError("'time_formats' must be a non-empty list of str")

    if colnames is not None and not _is_non_empty_typed_list(colnames, str):
        raise TypeError(
            "'colnames' must be either be None or a non-empty list of str."
        )

    if self.ncols() == 0:
        raise Exception(
            """Reading data is only possible in a DataFrame with more than zero
            columns. You can pre-define columns during
            initialization of the DataFrame or use the classmethod
            from_s3(...)."""
        )

    cmd: Dict[str, Any] = {}

    cmd["type_"] = "DataFrame.read_s3"
    cmd["name_"] = self.name

    cmd["append_"] = append
    cmd["bucket_"] = bucket
    cmd["keys_"] = keys
    cmd["region_"] = region
    cmd["sep_"] = sep
    cmd["time_formats_"] = time_formats
    cmd["num_lines_read_"] = num_lines_read
    cmd["skip_"] = skip

    if colnames is not None:
        cmd["colnames_"] = colnames

    cmd["categorical_"] = self._categorical_names
    cmd["join_keys_"] = self._join_key_names
    cmd["numerical_"] = self._numerical_names
    cmd["targets_"] = self._target_names
    cmd["text_"] = self._text_names
    cmd["time_stamps_"] = self._time_stamp_names
    cmd["unused_floats_"] = self._unused_float_names
    cmd["unused_strings_"] = self._unused_string_names

    comm.send(cmd)

    return self

read_view

read_view(view: View, append: bool = False) -> DataFrame

Read the data from a View.

PARAMETER DESCRIPTION
view

The view to read.

TYPE: View

append

If a data frame object holding the same name is already present in the getML, should the content of the CSV files in fnames be appended or replace the existing data?

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
DataFrame

Handler of the underlying data.

Source code in getml/data/data_frame.py
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
def read_view(
    self,
    view: View,
    append: bool = False,
) -> DataFrame:
    """Read the data from a [`View`][getml.data.View].

    Args:
        view:
            The view to read.

        append:
            If a data frame object holding the same ``name`` is
            already present in the getML, should the content of
            the CSV files in `fnames` be appended or replace the
            existing data?

    Returns:
            Handler of the underlying data.

    """

    if not isinstance(view, View):
        raise TypeError("'view' must be getml.data.View.")

    if not isinstance(append, bool):
        raise TypeError("'append' must be bool.")

    view.check()

    cmd: Dict[str, Any] = {}

    cmd["type_"] = "DataFrame.from_view"
    cmd["name_"] = self.name

    cmd["view_"] = view._getml_deserialize()

    cmd["append_"] = append

    comm.send(cmd)

    return self.refresh()

read_db

read_db(
    table_name: str,
    append: bool = False,
    conn: Optional[Connection] = None,
) -> DataFrame

Fill from Database.

The DataFrame will be filled from a table in the database.

PARAMETER DESCRIPTION
table_name

Table from which we want to retrieve the data.

TYPE: str

append

If a data frame object holding the same name is already present in the getML, should the content of table_name be appended or replace the existing data?

TYPE: bool DEFAULT: False

conn

The database connection to be used. If you don't explicitly pass a connection, the Engine will use the default connection.

TYPE: Optional[Connection] DEFAULT: None

RETURNS DESCRIPTION
DataFrame

Handler of the underlying data.

Source code in getml/data/data_frame.py
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
def read_db(
    self, table_name: str, append: bool = False, conn: Optional[Connection] = None
) -> DataFrame:
    """
    Fill from Database.

    The DataFrame will be filled from a table in the database.

    Args:
        table_name:
            Table from which we want to retrieve the data.

        append:
            If a data frame object holding the same ``name`` is
            already present in the getML, should the content of
            `table_name` be appended or replace the existing data?

        conn:
            The database connection to be used.
            If you don't explicitly pass a connection,
            the Engine will use the default connection.

    Returns:
            Handler of the underlying data.
    """

    if not isinstance(table_name, str):
        raise TypeError("'table_name' must be str.")

    if not isinstance(append, bool):
        raise TypeError("'append' must be bool.")

    if self.ncols() == 0:
        raise Exception(
            """Reading data is only possible in a DataFrame with more than zero
            columns. You can pre-define columns during
            initialization of the DataFrame or use the classmethod
            from_db(...)."""
        )

    conn = conn or database.Connection()

    cmd: Dict[str, Any] = {}

    cmd["type_"] = "DataFrame.from_db"
    cmd["name_"] = self.name
    cmd["table_name_"] = table_name

    cmd["categorical_"] = self._categorical_names
    cmd["join_keys_"] = self._join_key_names
    cmd["numerical_"] = self._numerical_names
    cmd["targets_"] = self._target_names
    cmd["text_"] = self._text_names
    cmd["time_stamps_"] = self._time_stamp_names
    cmd["unused_floats_"] = self._unused_float_names
    cmd["unused_strings_"] = self._unused_string_names

    cmd["append_"] = append

    cmd["conn_id_"] = conn.conn_id

    comm.send(cmd)

    return self

read_pandas

read_pandas(
    pandas_df: DataFrame, append: bool = False
) -> DataFrame

Uploads a pandas.DataFrame.

Replaces the actual content of the underlying data frame in the getML Engine with pandas_df.

PARAMETER DESCRIPTION
pandas_df

Data the underlying data frame object in the getML Engine should obtain.

TYPE: DataFrame

append

If a data frame object holding the same name is already present in the getML Engine, should the content in query be appended or replace the existing data?

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
DataFrame

Handler of the underlying data.

Note: For columns containing pandas.Timestamp there can occur small inconsistencies in the order of microseconds when sending the data to the getML Engine. This is due to the way the underlying information is stored.

Source code in getml/data/data_frame.py
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
def read_pandas(self, pandas_df: pd.DataFrame, append: bool = False) -> DataFrame:
    """Uploads a `pandas.DataFrame`.

    Replaces the actual content of the underlying data frame in
    the getML Engine with `pandas_df`.

    Args:
        pandas_df:
            Data the underlying data frame object in the getML
            Engine should obtain.

        append:
            If a data frame object holding the same ``name`` is
            already present in the getML Engine, should the content in
            `query` be appended or replace the existing data?

    Returns:
            Handler of the underlying data.
    Note:
        For columns containing `pandas.Timestamp` there can
        occur small inconsistencies in the order of microseconds
        when sending the data to the getML Engine. This is due to
        the way the underlying information is stored.
    """

    if not isinstance(pandas_df, pd.DataFrame):
        raise TypeError("'pandas_df' must be of type pandas.DataFrame.")

    if not isinstance(append, bool):
        raise TypeError("'append' must be bool.")

    if self.ncols() == 0:
        raise Exception(
            """Reading data is only possible in a DataFrame with more than zero
            columns. You can pre-define columns during
            initialization of the DataFrame or use the classmethod
            from_pandas(...)."""
        )

    table = pa.Table.from_pandas(pandas_df[self.columns])

    return self.read_arrow(table, append=append)

read_pyspark

read_pyspark(
    spark_df: DataFrame, append: bool = False
) -> DataFrame

Uploads a pyspark.sql.DataFrame.

Replaces the actual content of the underlying data frame in the getML Engine with pandas_df.

PARAMETER DESCRIPTION
spark_df

Data the underlying data frame object in the getML Engine should obtain.

TYPE: DataFrame

append

If a data frame object holding the same name is already present in the getML Engine, should the content in query be appended or replace the existing data?

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
DataFrame

Handler of the underlying data.

Source code in getml/data/data_frame.py
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
def read_pyspark(
    self, spark_df: pyspark.sql.DataFrame, append: bool = False
) -> DataFrame:
    """Uploads a `pyspark.sql.DataFrame`.

    Replaces the actual content of the underlying data frame in
    the getML Engine with `pandas_df`.

    Args:
        spark_df:
            Data the underlying data frame object in the getML
            Engine should obtain.

        append:
            If a data frame object holding the same ``name`` is
            already present in the getML Engine, should the content in
            `query` be appended or replace the existing data?

    Returns:
            Handler of the underlying data.
    """

    if not isinstance(append, bool):
        raise TypeError("'append' must be bool.")

    temp_dir = _retrieve_temp_dir()
    path = temp_dir / str(self.name)
    spark_df.write.mode("overwrite").parquet(str(path))

    filepaths = [
        os.path.join(path, filepath)
        for filepath in os.listdir(path)
        if filepath[-8:] == ".parquet"
    ]

    for i, filepath in enumerate(filepaths):
        self.read_parquet(filepath, append or i > 0)

    shutil.rmtree(path)

    return self

read_query

read_query(
    query: str,
    append: Optional[bool] = False,
    conn: Optional[Connection] = None,
) -> DataFrame

Fill from query

Fills the data frame with data from a table in the database.

PARAMETER DESCRIPTION
query

The query used to retrieve the data.

TYPE: str

append

If a data frame object holding the same name is already present in the getML Engine, should the content in query be appended or replace the existing data?

TYPE: Optional[bool] DEFAULT: False

conn

The database connection to be used. If you don't explicitly pass a connection, the Engine will use the default connection.

TYPE: Optional[Connection] DEFAULT: None

RETURNS DESCRIPTION
DataFrame

Handler of the underlying data.

Source code in getml/data/data_frame.py
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
def read_query(
    self,
    query: str,
    append: Optional[bool] = False,
    conn: Optional[Connection] = None,
) -> DataFrame:
    """Fill from query

    Fills the data frame with data from a table in the database.

    Args:
        query:
            The query used to retrieve the data.

        append:
            If a data frame object holding the same ``name`` is
            already present in the getML Engine, should the content in
            `query` be appended or replace the existing data?

        conn:
            The database connection to be used.
            If you don't explicitly pass a connection,
            the Engine will use the default connection.

    Returns:
            Handler of the underlying data.
    """

    if self.ncols() == 0:
        raise Exception(
            """Reading data is only possible in a DataFrame with more than zero
            columns. You can pre-define columns during
            initialization of the DataFrame or use the classmethod
            from_db(...)."""
        )

    if not isinstance(query, str):
        raise TypeError("'query' must be of type str")

    if not isinstance(append, bool):
        raise TypeError("'append' must be of type bool")

    conn = conn or database.Connection()

    cmd: Dict[str, Any] = {}

    cmd["type_"] = "DataFrame.from_query"
    cmd["name_"] = self.name
    cmd["query_"] = query

    cmd["categorical_"] = self._categorical_names
    cmd["join_keys_"] = self._join_key_names
    cmd["numerical_"] = self._numerical_names
    cmd["targets_"] = self._target_names
    cmd["text_"] = self._text_names
    cmd["time_stamps_"] = self._time_stamp_names
    cmd["unused_floats_"] = self._unused_float_names
    cmd["unused_strings_"] = self._unused_string_names

    cmd["append_"] = append

    cmd["conn_id_"] = conn.conn_id

    comm.send(cmd)

    return self

refresh

refresh() -> DataFrame

Aligns meta-information of the current instance with the corresponding data frame in the getML Engine.

    This method can be used to avoid encoding conflicts. Note that
    [`load`][getml.DataFrame.load] as well as several other
    methods automatically call [`refresh`][getml.DataFrame.refresh].
RETURNS DESCRIPTION
DataFrame

Updated handle the underlying data frame in the getML

DataFrame

Engine.

Source code in getml/data/data_frame.py
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
def refresh(self) -> DataFrame:
    """Aligns meta-information of the current instance with the
            corresponding data frame in the getML Engine.

            This method can be used to avoid encoding conflicts. Note that
            [`load`][getml.DataFrame.load] as well as several other
            methods automatically call [`refresh`][getml.DataFrame.refresh].

    Returns:
            Updated handle the underlying data frame in the getML
            Engine.

    """

    cmd: Dict[str, Any] = {}
    cmd["type_"] = "DataFrame.refresh"
    cmd["name_"] = self.name

    with comm.send_and_get_socket(cmd) as sock:
        msg = comm.recv_string(sock)

    if msg[0] != "{":
        comm.handle_engine_exception(msg)

    roles = json.loads(msg)

    self.__init__(name=cast(str, self.name), roles=roles)

    return self

remove_subroles

remove_subroles(
    cols: Union[
        str,
        FloatColumn,
        StringColumn,
        List[Union[str, FloatColumn, StringColumn]],
    ]
) -> None

Removes all subroles from one or more columns.

PARAMETER DESCRIPTION
cols

The columns or the names thereof.

TYPE: Union[str, FloatColumn, StringColumn, List[Union[str, FloatColumn, StringColumn]]]

Source code in getml/data/data_frame.py
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
def remove_subroles(
    self,
    cols: Union[
        str, FloatColumn, StringColumn, List[Union[str, FloatColumn, StringColumn]]
    ],
) -> None:
    """Removes all [`subroles`][getml.data.subroles] from one or more columns.

    Args:
        cols:
            The columns or the names thereof.
    """

    names = _handle_cols(cols)

    for name in names:
        self._set_subroles(name, append=False, subroles=[])

    self.refresh()

remove_unit

Removes the unit from one or more columns.

PARAMETER DESCRIPTION
cols

The columns or the names thereof.

TYPE: Union[str, FloatColumn, StringColumn, List[Union[str, FloatColumn, StringColumn]]]

Source code in getml/data/data_frame.py
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
def remove_unit(
    self,
    cols: Union[
        str, FloatColumn, StringColumn, List[Union[str, FloatColumn, StringColumn]]
    ],
):
    """Removes the unit from one or more columns.

    Args:
        cols:
            The columns or the names thereof.
    """

    names = _handle_cols(cols)

    for name in names:
        self._set_unit(name, "")

    self.refresh()

save

save() -> DataFrame

Writes the underlying data in the getML Engine to disk.

RETURNS DESCRIPTION
DataFrame

The current instance.

Source code in getml/data/data_frame.py
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
def save(self) -> DataFrame:
    """Writes the underlying data in the getML Engine to disk.

    Returns:
            The current instance.

    """

    cmd: Dict[str, Any] = {}

    cmd["type_"] = "DataFrame.save"
    cmd["name_"] = self.name

    comm.send(cmd)

    return self

set_role

set_role(
    cols: Union[
        str,
        FloatColumn,
        StringColumn,
        List[Union[str, FloatColumn, StringColumn]],
    ],
    role: str,
    time_formats: Optional[Iterable[str]] = None,
)

Assigns a new role to one or more columns.

When switching from a role based on type float to a role based on type string or vice verse, an implicit type conversion will be conducted. The time_formats argument is used to interpret Time Stamps. For more information on roles, please refer to the User Guide.

PARAMETER DESCRIPTION
cols

The columns or the names of the columns.

TYPE: Union[str, FloatColumn, StringColumn, List[Union[str, FloatColumn, StringColumn]]]

role

The role to be assigned.

TYPE: str

time_formats

Formats to be used to parse the time stamps. This is only necessary, if an implicit conversion from a StringColumn to a time stamp is taking place.

TYPE: Optional[Iterable[str]] DEFAULT: None

Example

data_df = dict(
    animal=["hawk", "parrot", "goose"],
    votes=[12341, 5127, 65311],
    date=["04/06/2019", "01/03/2019", "24/12/2018"])
df = getml.DataFrame.from_dict(data_df, "animal_elections")
df.set_role(['animal'], getml.data.roles.categorical)
df.set_role(['votes'], getml.data.roles.numerical)
df.set_role(
    ['date'], getml.data.roles.time_stamp, time_formats=['%d/%m/%Y'])

df
| date                        | animal      | votes     |
| time stamp                  | categorical | numerical |
---------------------------------------------------------
| 2019-06-04T00:00:00.000000Z | hawk        | 12341     |
| 2019-03-01T00:00:00.000000Z | parrot      | 5127      |
| 2018-12-24T00:00:00.000000Z | goose       | 65311     |

Source code in getml/data/data_frame.py
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
def set_role(
    self,
    cols: Union[
        str, FloatColumn, StringColumn, List[Union[str, FloatColumn, StringColumn]]
    ],
    role: str,
    time_formats: Optional[Iterable[str]] = None,
):
    """Assigns a new role to one or more columns.

    When switching from a role based on type float to a role based on type
    string or vice verse, an implicit type conversion will be conducted.
    The `time_formats` argument is used to interpret [Time Stamps][annotating-data-time-stamp]. For more information on
    roles, please refer to the [User Guide][annotating-data].

    Args:
        cols:
            The columns or the names of the columns.

        role:
            The role to be assigned.

        time_formats:
            Formats to be used to parse the time stamps.
            This is only necessary, if an implicit conversion from a StringColumn to
            a time stamp is taking place.

    ??? example
        ```python
        data_df = dict(
            animal=["hawk", "parrot", "goose"],
            votes=[12341, 5127, 65311],
            date=["04/06/2019", "01/03/2019", "24/12/2018"])
        df = getml.DataFrame.from_dict(data_df, "animal_elections")
        df.set_role(['animal'], getml.data.roles.categorical)
        df.set_role(['votes'], getml.data.roles.numerical)
        df.set_role(
            ['date'], getml.data.roles.time_stamp, time_formats=['%d/%m/%Y'])

        df
        ```
        ```
        | date                        | animal      | votes     |
        | time stamp                  | categorical | numerical |
        ---------------------------------------------------------
        | 2019-06-04T00:00:00.000000Z | hawk        | 12341     |
        | 2019-03-01T00:00:00.000000Z | parrot      | 5127      |
        | 2018-12-24T00:00:00.000000Z | goose       | 65311     |
        ```
    """
    # ------------------------------------------------------------

    time_formats = time_formats or constants.TIME_FORMATS

    # ------------------------------------------------------------

    names = _handle_cols(cols)

    if not isinstance(role, str):
        raise TypeError("'role' must be str.")

    if not _is_non_empty_typed_list(time_formats, str):
        raise TypeError("'time_formats' must be a non-empty list of str")

    # ------------------------------------------------------------

    for nname in names:
        if nname not in self.colnames:
            raise ValueError("No column called '" + nname + "' found.")

    if role not in self._all_roles:
        raise ValueError(
            "'role' must be one of the following values: " + str(self._all_roles)
        )

    # ------------------------------------------------------------

    for name in names:
        if self[name].role != role:
            self._set_role(name, role, time_formats)

    # ------------------------------------------------------------

    self.refresh()

set_subroles

set_subroles(
    cols: Union[
        str,
        FloatColumn,
        StringColumn,
        List[Union[str, FloatColumn, StringColumn]],
    ],
    subroles: Optional[
        Union[Subrole, Iterable[str]]
    ] = None,
    append: Optional[bool] = True,
)

Assigns one or several new subroles to one or more columns.

PARAMETER DESCRIPTION
cols

The columns or the names thereof.

TYPE: Union[str, FloatColumn, StringColumn, List[Union[str, FloatColumn, StringColumn]]]

subroles

The subroles to be assigned. Must be from subroles.

TYPE: Optional[Union[Subrole, Iterable[str]]] DEFAULT: None

append

Whether you want to append the new subroles to the existing subroles.

TYPE: Optional[bool] DEFAULT: True

Source code in getml/data/data_frame.py
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
def set_subroles(
    self,
    cols: Union[
        str, FloatColumn, StringColumn, List[Union[str, FloatColumn, StringColumn]]
    ],
    subroles: Optional[Union[Subrole, Iterable[str]]] = None,
    append: Optional[bool] = True,
):
    """Assigns one or several new [`subroles`][getml.data.subroles] to one or more columns.

    Args:
        cols:
            The columns or the names thereof.

        subroles:
            The subroles to be assigned.
            Must be from [`subroles`][getml.data.subroles].

        append:
            Whether you want to append the
            new subroles to the existing subroles.
    """

    names = _handle_cols(cols)

    if isinstance(subroles, str):
        subroles = [subroles]

    if not _is_non_empty_typed_list(subroles, str):
        raise TypeError("'subroles' must be either a string or a list of strings.")

    if not isinstance(append, bool):
        raise TypeError("'append' must be a bool.")

    for name in names:
        self._set_subroles(name, append, subroles)

    self.refresh()

set_unit

set_unit(
    cols: Union[
        str,
        FloatColumn,
        StringColumn,
        List[Union[str, FloatColumn, StringColumn]],
    ],
    unit: str,
    comparison_only: bool = False,
)

Assigns a new unit to one or more columns.

PARAMETER DESCRIPTION
cols

The columns or the names thereof.

TYPE: Union[str, FloatColumn, StringColumn, List[Union[str, FloatColumn, StringColumn]]]

unit

The unit to be assigned.

TYPE: str

comparison_only

Whether you want the column to be used for comparison only. This means that the column can only be used in comparison to other columns of the same unit.

An example might be a bank account number: The number in itself is hardly interesting, but it might be useful to know how often we have seen that same bank account number in another table.

TYPE: bool DEFAULT: False

Source code in getml/data/data_frame.py
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
def set_unit(
    self,
    cols: Union[
        str, FloatColumn, StringColumn, List[Union[str, FloatColumn, StringColumn]]
    ],
    unit: str,
    comparison_only: bool = False,
):
    """Assigns a new unit to one or more columns.

    Args:
        cols:
            The columns or the names thereof.

        unit:
            The unit to be assigned.

        comparison_only:
            Whether you want the column to
            be used for comparison only. This means that the column can
            only be used in comparison to other columns of the same unit.

            An example might be a bank account number: The number in itself
            is hardly interesting, but it might be useful to know how often
            we have seen that same bank account number in another table.
    """

    names = _handle_cols(cols)

    if not isinstance(unit, str):
        raise TypeError("Parameter 'unit' must be a str.")

    if comparison_only:
        unit += COMPARISON_ONLY

    for name in names:
        self._set_unit(name, unit)

    self.refresh()

to_arrow

to_arrow() -> Table

Creates a pyarrow.Table from the current instance.

Loads the underlying data from the getML Engine and constructs a pyarrow.Table.

RETURNS DESCRIPTION
Table

Pyarrow equivalent of the current instance including its underlying data.

Source code in getml/data/data_frame.py
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
def to_arrow(self) -> pa.Table:
    """Creates a `pyarrow.Table` from the current instance.

    Loads the underlying data from the getML Engine and constructs
    a `pyarrow.Table`.

    Returns:
            Pyarrow equivalent of the current instance including its underlying data.
    """
    return to_arrow(self)

to_csv

to_csv(
    fname: str,
    quotechar: str = '"',
    sep: str = ",",
    batch_size: int = DEFAULT_BATCH_SIZE,
    quoting_style: str = "needed",
)

Writes the underlying data into a newly created CSV file.

PARAMETER DESCRIPTION
fname

The name of the CSV file. The ending ".csv" and an optional batch number will be added automatically.

TYPE: str

quotechar

The character used to wrap strings.

TYPE: str DEFAULT: '"'

sep

The character used for separating fields.

TYPE: str DEFAULT: ','

batch_size

Maximum number of lines per file. Set to 0 to read the entire data frame into a single file.

TYPE: int DEFAULT: DEFAULT_BATCH_SIZE

quoting_style

The quoting style to use. Delegated to pyarrow.

The following values are accepted: - "needed" (default): only enclose values in quotes when needed. - "all_valid": enclose all valid values in quotes; nulls are not quoted. - "none": do not enclose any values in quotes; values containing special characters (such as quotes, cell delimiters or line endings) will raise an error.

TYPE: str DEFAULT: 'needed'

Deprecated

1.5: The quotechar parameter is deprecated.

Source code in getml/data/data_frame.py
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
def to_csv(
    self,
    fname: str,
    quotechar: str = '"',
    sep: str = ",",
    batch_size: int = DEFAULT_BATCH_SIZE,
    quoting_style: str = "needed",
):
    """
    Writes the underlying data into a newly created CSV file.

    Args:
        fname:
            The name of the CSV file.
            The ending ".csv" and an optional batch number will
            be added automatically.

        quotechar:
            The character used to wrap strings.

        sep:
            The character used for separating fields.

        batch_size:
            Maximum number of lines per file. Set to 0 to read
            the entire data frame into a single file.

        quoting_style (str):
            The quoting style to use. Delegated to pyarrow.

            The following values are accepted:
            - `"needed"` (default): only enclose values in quotes when needed.
            - `"all_valid"`: enclose all valid values in quotes; nulls are not
              quoted.
            - `"none"`: do not enclose any values in quotes; values containing
              special characters (such as quotes, cell delimiters or line
              endings) will raise an error.

    Deprecated:
       1.5: The `quotechar` parameter is deprecated.
    """

    if quotechar != '"':
        warnings.warn(
            "'quotechar' is deprecated, use 'quoting_style' instead.",
            DeprecationWarning,
        )

    to_csv(self, fname, sep, batch_size, quoting_style)

to_db

to_db(table_name: str, conn: Optional[Connection] = None)

Writes the underlying data into a newly created table in the database.

PARAMETER DESCRIPTION
table_name

Name of the table to be created.

If a table of that name already exists, it will be replaced.

TYPE: str

conn

The database connection to be used. If you don't explicitly pass a connection, the Engine will use the default connection.

TYPE: Optional[Connection] DEFAULT: None

Source code in getml/data/data_frame.py
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
def to_db(self, table_name: str, conn: Optional[Connection] = None):
    """Writes the underlying data into a newly created table in the
    database.

    Args:
        table_name:
            Name of the table to be created.

            If a table of that name already exists, it will be
            replaced.

        conn:
            The database connection to be used.
            If you don't explicitly pass a connection,
            the Engine will use the default connection.
    """

    conn = conn or database.Connection()

    self.refresh()

    if not isinstance(table_name, str):
        raise TypeError("'table_name' must be of type str")

    cmd = {}

    cmd["type_"] = "DataFrame.to_db"
    cmd["name_"] = self.name

    cmd["table_name_"] = table_name

    cmd["conn_id_"] = conn.conn_id

    comm.send(cmd)

to_html

to_html(max_rows: int = 10)

Represents the data frame in HTML format, optimized for an iPython notebook.

PARAMETER DESCRIPTION
max_rows

The maximum number of rows to be displayed.

TYPE: int DEFAULT: 10

Source code in getml/data/data_frame.py
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
def to_html(self, max_rows: int = 10):
    """
    Represents the data frame in HTML format, optimized for an
    iPython notebook.

    Args:
        max_rows:
            The maximum number of rows to be displayed.
    """

    if not _exists_in_memory(self.name):
        return _empty_data_frame().replace("\n", "<br>")

    formatted = self._format()
    formatted.max_rows = max_rows

    footer = self._collect_footer_data()

    return formatted._render_html(footer=footer)

to_json

to_json()

Creates a JSON string from the current instance.

Loads the underlying data from the getML Engine and constructs a JSON string.

Source code in getml/data/data_frame.py
3613
3614
3615
3616
3617
3618
3619
def to_json(self):
    """Creates a JSON string from the current instance.

    Loads the underlying data from the getML Engine and constructs
    a JSON string.
    """
    return self.to_pandas().to_json()

to_pandas

to_pandas() -> DataFrame

Creates a pandas.DataFrame from the current instance.

Loads the underlying data from the getML Engine and constructs pandas.DataFrame.

RETURNS DESCRIPTION
DataFrame

Pandas equivalent of the current instance including

DataFrame

its underlying data.

Source code in getml/data/data_frame.py
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
def to_pandas(self) -> pd.DataFrame:
    """Creates a `pandas.DataFrame` from the current instance.

    Loads the underlying data from the getML Engine and constructs
    `pandas.DataFrame`.

    Returns:
            Pandas equivalent of the current instance including
            its underlying data.

    """
    return to_arrow(self).to_pandas()

to_parquet

to_parquet(
    fname: str,
    compression: Literal[
        "brotli", "gzip", "lz4", "snappy", "zstd"
    ] = "snappy",
)

Writes the underlying data into a newly created parquet file.

PARAMETER DESCRIPTION
fname

The name of the parquet file. The ending ".parquet" will be added automatically.

TYPE: str

compression

The compression format to use. Supported values are "brotli", "gzip", "lz4", "snappy", "zstd"

TYPE: Literal['brotli', 'gzip', 'lz4', 'snappy', 'zstd'] DEFAULT: 'snappy'

Source code in getml/data/data_frame.py
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
def to_parquet(
    self,
    fname: str,
    compression: Literal["brotli", "gzip", "lz4", "snappy", "zstd"] = "snappy",
):
    """
    Writes the underlying data into a newly created parquet file.

    Args:
        fname:
            The name of the parquet file.
            The ending ".parquet" will be added automatically.

        compression:
            The compression format to use.
            Supported values are "brotli", "gzip", "lz4", "snappy", "zstd"
    """
    to_parquet(self, fname, compression)

to_placeholder

to_placeholder(name: Optional[str] = None) -> Placeholder

Generates a Placeholder from the current DataFrame.

PARAMETER DESCRIPTION
name

The name of the placeholder. If no name is passed, then the name of the placeholder will be identical to the name of the current data frame.

TYPE: Optional[str] DEFAULT: None

RETURNS DESCRIPTION
Placeholder

A placeholder with the same name as this data frame.

Source code in getml/data/data_frame.py
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
def to_placeholder(self, name: Optional[str] = None) -> Placeholder:
    """Generates a [`Placeholder`][getml.data.Placeholder] from the
    current [`DataFrame`][getml.DataFrame].

    Args:
        name:
            The name of the placeholder. If no
            name is passed, then the name of the placeholder will
            be identical to the name of the current data frame.

    Returns:
            A placeholder with the same name as this data frame.


    """
    self.refresh()
    return Placeholder(name=name or self.name, roles=self.roles)

to_pyspark

to_pyspark(
    spark: SparkSession, name: Optional[str] = None
) -> DataFrame

Creates a pyspark.sql.DataFrame from the current instance.

Loads the underlying data from the getML Engine and constructs a pyspark.sql.DataFrame.

PARAMETER DESCRIPTION
spark

The pyspark session in which you want to create the data frame.

TYPE: SparkSession

name

The name of the temporary view to be created on top of the pyspark.sql.DataFrame, with which it can be referred to in Spark SQL (refer to pyspark.sql.DataFrame.createOrReplaceTempView). If None is passed, then the name of this DataFrame will be used.

TYPE: Optional[str] DEFAULT: None

RETURNS DESCRIPTION
DataFrame

Pyspark equivalent of the current instance including its underlying data.

Source code in getml/data/data_frame.py
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
def to_pyspark(
    self, spark: pyspark.sql.SparkSession, name: Optional[str] = None
) -> pyspark.sql.DataFrame:
    """Creates a `pyspark.sql.DataFrame` from the current instance.

    Loads the underlying data from the getML Engine and constructs
    a `pyspark.sql.DataFrame`.

    Args:
        spark:
            The pyspark session in which you want to
            create the data frame.

        name:
            The name of the temporary view to be created on top
            of the `pyspark.sql.DataFrame`,
            with which it can be referred to
            in Spark SQL (refer to
            `pyspark.sql.DataFrame.createOrReplaceTempView`).
            If None is passed, then the name of this
            [`DataFrame`][getml.DataFrame] will be used.

    Returns:
            Pyspark equivalent of the current instance including its underlying data.

    """
    return _to_pyspark(self, name, spark)

to_s3

to_s3(
    bucket: str,
    key: str,
    region: str,
    sep: Optional[str] = ",",
    batch_size: Optional[int] = 50000,
)

Writes the underlying data into a newly created CSV file located in an S3 bucket.

Enterprise edition

This feature is exclusive to the Enterprise edition and is not available in the Community edition. Discover the benefits of the Enterprise edition and compare their features.

For licensing information and technical support, please contact us.

Note

Note that S3 is not supported on Windows.

PARAMETER DESCRIPTION
bucket

The bucket from which to read the files.

TYPE: str

key

The key in the S3 bucket in which you want to write the output. The ending ".csv" and an optional batch number will be added automatically.

TYPE: str

region

The region in which the bucket is located.

TYPE: str

sep

The character used for separating fields.

TYPE: Optional[str] DEFAULT: ','

batch_size

Maximum number of lines per file. Set to 0 to read the entire data frame into a single file.

TYPE: Optional[int] DEFAULT: 50000

Example
getml.engine.set_s3_access_key_id("YOUR-ACCESS-KEY-ID")
getml.engine.set_s3_secret_access_key("YOUR-SECRET-ACCESS-KEY")

your_df.to_s3(
    bucket="your-bucket-name",
    key="filename-on-s3",
    region="us-east-2",
    sep=';'
)
Source code in getml/data/data_frame.py
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
def to_s3(
    self,
    bucket: str,
    key: str,
    region: str,
    sep: Optional[str] = ",",
    batch_size: Optional[int] = 50000,
):
    """
    Writes the underlying data into a newly created CSV file
    located in an S3 bucket.

    enterprise-adm: Enterprise edition
        This feature is exclusive to the Enterprise edition and is not available in the Community edition. Discover the [benefits of the Enterprise edition][enterprise-benefits] and [compare their features][enterprise-feature-list].

        For licensing information and technical support, please [contact us][contact-page].

    Note:
        Note that S3 is not supported on Windows.

    Args:
        bucket:
            The bucket from which to read the files.

        key:
            The key in the S3 bucket in which you want to
            write the output. The ending ".csv" and an optional
            batch number will be added automatically.

        region:
            The region in which the bucket is located.

        sep:
            The character used for separating fields.

        batch_size:
            Maximum number of lines per file. Set to 0 to read
            the entire data frame into a single file.

    ??? example
        ```python
        getml.engine.set_s3_access_key_id("YOUR-ACCESS-KEY-ID")
        getml.engine.set_s3_secret_access_key("YOUR-SECRET-ACCESS-KEY")

        your_df.to_s3(
            bucket="your-bucket-name",
            key="filename-on-s3",
            region="us-east-2",
            sep=';'
        )
        ```

    """

    self.refresh()

    if not isinstance(bucket, str):
        raise TypeError("'bucket' must be of type str")

    if not isinstance(key, str):
        raise TypeError("'fname' must be of type str")

    if not isinstance(region, str):
        raise TypeError("'region' must be of type str")

    if not isinstance(sep, str):
        raise TypeError("'sep' must be of type str")

    if not isinstance(batch_size, numbers.Real):
        raise TypeError("'batch_size' must be a real number")

    cmd: Dict[str, Any] = {}

    cmd["type_"] = "DataFrame.to_s3"
    cmd["name_"] = self.name

    cmd["bucket_"] = bucket
    cmd["key_"] = key
    cmd["region_"] = region
    cmd["sep_"] = sep
    cmd["batch_size_"] = batch_size

    comm.send(cmd)

unload

unload()

Unloads the data frame from memory.

Source code in getml/data/data_frame.py
3812
3813
3814
3815
3816
3817
3818
3819
def unload(self):
    """
    Unloads the data frame from memory.
    """

    # ------------------------------------------------------------

    self._delete(mem_only=True)

where

Extract a subset of rows.

Creates a new View as a subselection of the current instance.

PARAMETER DESCRIPTION
index

Indicates the rows you want to select.

TYPE: Union[Integral, slice, BooleanColumnView, FloatColumnView, FloatColumn]

RETURNS DESCRIPTION
View

A new View containing the selected rows.

Example

Generate example data:

data = dict(
    fruit=["banana", "apple", "cherry", "cherry", "melon", "pineapple"],
    price=[2.4, 3.0, 1.2, 1.4, 3.4, 3.4],
    join_key=["0", "1", "2", "2", "3", "3"])

fruits = getml.DataFrame.from_dict(data, name="fruits",
roles={"categorical": ["fruit"], "join_key": ["join_key"], "numerical": ["price"]})

fruits
| join_key | fruit       | price     |
| join key | categorical | numerical |
--------------------------------------
| 0        | banana      | 2.4       |
| 1        | apple       | 3         |
| 2        | cherry      | 1.2       |
| 2        | cherry      | 1.4       |
| 3        | melon       | 3.4       |
| 3        | pineapple   | 3.4       |
Apply where condition. This creates a new DataFrame called "cherries":

cherries = fruits.where(
    fruits["fruit"] == "cherry")

cherries
| join_key | fruit       | price     |
| join key | categorical | numerical |
--------------------------------------
| 2        | cherry      | 1.2       |
| 2        | cherry      | 1.4       |

Source code in getml/data/data_frame.py
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
def where(
    self,
    index: Union[
        numbers.Integral, slice, BooleanColumnView, FloatColumnView, FloatColumn
    ],
) -> View:
    """Extract a subset of rows.

    Creates a new [`View`][getml.data.View] as a
    subselection of the current instance.

    Args:
        index:
            Indicates the rows you want to select.

    Returns:
            A new [`View`][getml.data.View] containing the selected rows.

    ??? example
        Generate example data:
        ```python
        data = dict(
            fruit=["banana", "apple", "cherry", "cherry", "melon", "pineapple"],
            price=[2.4, 3.0, 1.2, 1.4, 3.4, 3.4],
            join_key=["0", "1", "2", "2", "3", "3"])

        fruits = getml.DataFrame.from_dict(data, name="fruits",
        roles={"categorical": ["fruit"], "join_key": ["join_key"], "numerical": ["price"]})

        fruits
        ```
        ```
        | join_key | fruit       | price     |
        | join key | categorical | numerical |
        --------------------------------------
        | 0        | banana      | 2.4       |
        | 1        | apple       | 3         |
        | 2        | cherry      | 1.2       |
        | 2        | cherry      | 1.4       |
        | 3        | melon       | 3.4       |
        | 3        | pineapple   | 3.4       |
        ```
        Apply where condition. This creates a new DataFrame called "cherries":

        ```python
        cherries = fruits.where(
            fruits["fruit"] == "cherry")

        cherries
        ```
        ```
        | join_key | fruit       | price     |
        | join key | categorical | numerical |
        --------------------------------------
        | 2        | cherry      | 1.2       |
        | 2        | cherry      | 1.4       |
        ```

    """

    return _where(self, index)

with_column

with_column(
    col: Union[
        bool,
        str,
        float,
        int,
        datetime64,
        FloatColumn,
        FloatColumnView,
        StringColumn,
        StringColumnView,
        BooleanColumnView,
    ],
    name: str,
    role: Optional[Role] = None,
    subroles: Optional[
        Union[Subrole, Iterable[str]]
    ] = None,
    unit: str = "",
    time_formats: Optional[Iterable[str]] = None,
)

Returns a new View that contains an additional column.

PARAMETER DESCRIPTION
col

The column to be added.

TYPE: Union[bool, str, float, int, datetime64, FloatColumn, FloatColumnView, StringColumn, StringColumnView, BooleanColumnView]

name

Name of the new column.

TYPE: str

role

Role of the new column. Must be from roles.

TYPE: Optional[Role] DEFAULT: None

subroles

Subroles of the new column. Must be from subroles.

TYPE: Optional[Union[Subrole, Iterable[str]]] DEFAULT: None

unit

Unit of the column.

TYPE: str DEFAULT: ''

time_formats

Formats to be used to parse the time stamps.

This is only necessary, if an implicit conversion from a StringColumn to a time stamp is taking place.

The formats are allowed to contain the following special characters:

  • %w - abbreviated weekday (Mon, Tue, ...)
  • %W - full weekday (Monday, Tuesday, ...)
  • %b - abbreviated month (Jan, Feb, ...)
  • %B - full month (January, February, ...)
  • %d - zero-padded day of month (01 .. 31)
  • %e - day of month (1 .. 31)
  • %f - space-padded day of month ( 1 .. 31)
  • %m - zero-padded month (01 .. 12)
  • %n - month (1 .. 12)
  • %o - space-padded month ( 1 .. 12)
  • %y - year without century (70)
  • %Y - year with century (1970)
  • %H - hour (00 .. 23)
  • %h - hour (00 .. 12)
  • %a - am/pm
  • %A - AM/PM
  • %M - minute (00 .. 59)
  • %S - second (00 .. 59)
  • %s - seconds and microseconds (equivalent to %S.%F)
  • %i - millisecond (000 .. 999)
  • %c - centisecond (0 .. 9)
  • %F - fractional seconds/microseconds (000000 - 999999)
  • %z - time zone differential in ISO 8601 format (Z or +NN.NN)
  • %Z - time zone differential in RFC format (GMT or +NNNN)
  • %% - percent sign

TYPE: Optional[Iterable[str]] DEFAULT: None

Source code in getml/data/data_frame.py
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
def with_column(
    self,
    col: Union[
        bool,
        str,
        float,
        int,
        np.datetime64,
        FloatColumn,
        FloatColumnView,
        StringColumn,
        StringColumnView,
        BooleanColumnView,
    ],
    name: str,
    role: Optional[Role] = None,
    subroles: Optional[Union[Subrole, Iterable[str]]] = None,
    unit: str = "",
    time_formats: Optional[Iterable[str]] = None,
):
    """Returns a new [`View`][getml.data.View] that contains an additional column.

    Args:
        col:
            The column to be added.

        name:
            Name of the new column.

        role:
            Role of the new column. Must be from [`roles`][getml.data.roles].

        subroles:
            Subroles of the new column. Must be from [`subroles`][getml.data.subroles].

        unit:
            Unit of the column.

        time_formats:
            Formats to be used to parse the time stamps.

            This is only necessary, if an implicit conversion from
            a [`StringColumn`][getml.data.columns.StringColumn] to a time
            stamp is taking place.

            The formats are allowed to contain the following
            special characters:

            * %w - abbreviated weekday (Mon, Tue, ...)
            * %W - full weekday (Monday, Tuesday, ...)
            * %b - abbreviated month (Jan, Feb, ...)
            * %B - full month (January, February, ...)
            * %d - zero-padded day of month (01 .. 31)
            * %e - day of month (1 .. 31)
            * %f - space-padded day of month ( 1 .. 31)
            * %m - zero-padded month (01 .. 12)
            * %n - month (1 .. 12)
            * %o - space-padded month ( 1 .. 12)
            * %y - year without century (70)
            * %Y - year with century (1970)
            * %H - hour (00 .. 23)
            * %h - hour (00 .. 12)
            * %a - am/pm
            * %A - AM/PM
            * %M - minute (00 .. 59)
            * %S - second (00 .. 59)
            * %s - seconds and microseconds (equivalent to %S.%F)
            * %i - millisecond (000 .. 999)
            * %c - centisecond (0 .. 9)
            * %F - fractional seconds/microseconds (000000 - 999999)
            * %z - time zone differential in ISO 8601 format (Z or +NN.NN)
            * %Z - time zone differential in RFC format (GMT or +NNNN)
            * %% - percent sign

    """
    col, role, subroles = _with_column(
        col, name, role, subroles, unit, time_formats
    )
    return View(
        base=self,
        added={
            "col_": col,
            "name_": name,
            "role_": role,
            "subroles_": subroles,
            "unit_": unit,
        },
    )

with_name

with_name(name: str) -> View

Returns a new View with a new name.

PARAMETER DESCRIPTION
name

The name of the new view.

TYPE: str

RETURNS DESCRIPTION
View

A new view with the new name.

Source code in getml/data/data_frame.py
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
def with_name(self, name: str) -> View:
    """Returns a new [`View`][getml.data.View] with a new name.

    Args:
        name:
            The name of the new view.

    Returns:
        A new view with the new name.
    """
    return View(base=self, name=name)

with_role

with_role(
    cols: Union[
        str,
        FloatColumn,
        StringColumn,
        Union[
            Iterable[str],
            List[FloatColumn],
            List[StringColumn],
        ],
    ],
    role: Role,
    time_formats: Optional[Iterable[str]] = None,
)

Returns a new View with modified roles.

The difference between with_role and set_role is that with_role returns a view that is lazily evaluated when needed whereas set_role is an in-place operation. From a memory perspective, in-place operations like set_role are preferable.

When switching from a role based on type float to a role based on type string or vice verse, an implicit type conversion will be conducted. The time_formats argument is used to interpret time format string: annotating_roles_time_stamp. For more information on roles, please refer to the User Guide.

PARAMETER DESCRIPTION
cols

The columns or the names thereof.

TYPE: Union[str, FloatColumn, StringColumn, Union[Iterable[str], List[FloatColumn], List[StringColumn]]]

role

The role to be assigned.

TYPE: Role

time_formats

Formats to be used to parse the time stamps. This is only necessary, if an implicit conversion from a StringColumn to a time stamp is taking place.

TYPE: Optional[Iterable[str]] DEFAULT: None

Source code in getml/data/data_frame.py
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
def with_role(
    self,
    cols: Union[
        str,
        FloatColumn,
        StringColumn,
        Union[Iterable[str], List[FloatColumn], List[StringColumn]],
    ],
    role: Role,
    time_formats: Optional[Iterable[str]] = None,
):
    """Returns a new [`View`][getml.data.View] with modified roles.

    The difference between [`with_role`][getml.DataFrame.with_role] and
    [`set_role`][getml.DataFrame.set_role] is that
    [`with_role`][getml.DataFrame.with_role] returns a view that is lazily
    evaluated when needed whereas [`set_role`][getml.DataFrame.set_role]
    is an in-place operation. From a memory perspective, in-place operations
    like [`set_role`][getml.DataFrame.set_role] are preferable.

    When switching from a role based on type float to a role based on type
    string or vice verse, an implicit type conversion will be conducted.
    The `time_formats` argument is used to interpret time
    format string: `annotating_roles_time_stamp`. For more information on
    roles, please refer to the [User Guide][annotating-data].

    Args:
        cols:
            The columns or the names thereof.

        role:
            The role to be assigned.

        time_formats:
            Formats to be used to
            parse the time stamps.
            This is only necessary, if an implicit conversion from a StringColumn to
            a time stamp is taking place.
    """
    return _with_role(self, cols, role, time_formats)

with_subroles

with_subroles(
    cols: Union[
        str,
        FloatColumn,
        StringColumn,
        Union[
            Iterable[str],
            List[FloatColumn],
            List[StringColumn],
        ],
    ],
    subroles: Union[Subrole, Iterable[str]],
    append: bool = True,
)

Returns a new view with one or several new subroles on one or more columns.

The difference between with_subroles and set_subroles is that with_subroles returns a view that is lazily evaluated when needed whereas set_subroles is an in-place operation. From a memory perspective, in-place operations like set_subroles are preferable.

PARAMETER DESCRIPTION
cols

The columns or the names thereof.

TYPE: Union[str, FloatColumn, StringColumn, Union[Iterable[str], List[FloatColumn], List[StringColumn]]]

subroles

The subroles to be assigned.

TYPE: Union[Subrole, Iterable[str]]

append

Whether you want to append the new subroles to the existing subroles.

TYPE: bool DEFAULT: True

Source code in getml/data/data_frame.py
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
def with_subroles(
    self,
    cols: Union[
        str,
        FloatColumn,
        StringColumn,
        Union[Iterable[str], List[FloatColumn], List[StringColumn]],
    ],
    subroles: Union[Subrole, Iterable[str]],
    append: bool = True,
):
    """Returns a new view with one or several new subroles on one or more columns.

    The difference between [`with_subroles`][getml.DataFrame.with_subroles] and
    [`set_subroles`][getml.DataFrame.set_subroles] is that
    [`with_subroles`][getml.DataFrame.with_subroles] returns a view that is lazily
    evaluated when needed whereas [`set_subroles`][getml.DataFrame.set_subroles]
    is an in-place operation. From a memory perspective, in-place operations
    like [`set_subroles`][getml.DataFrame.set_subroles] are preferable.

    Args:
        cols:
            The columns or the names thereof.

        subroles:
            The subroles to be assigned.

        append:
            Whether you want to append the
            new subroles to the existing subroles.
    """
    return _with_subroles(self, cols, subroles, append)

with_unit

with_unit(
    cols: Union[
        str,
        FloatColumn,
        StringColumn,
        Union[
            Iterable[str],
            List[FloatColumn],
            List[StringColumn],
        ],
    ],
    unit: str,
    comparison_only: bool = False,
)

Returns a view that contains a new unit on one or more columns.

The difference between with_unit and set_unit is that with_unit returns a view that is lazily evaluated when needed whereas set_unit is an in-place operation. From a memory perspective, in-place operations like set_unit are preferable.

PARAMETER DESCRIPTION
cols

The columns or the names thereof.

TYPE: Union[str, FloatColumn, StringColumn, Union[Iterable[str], List[FloatColumn], List[StringColumn]]]

unit

The unit to be assigned.

TYPE: str

comparison_only

Whether you want the column to be used for comparison only. This means that the column can only be used in comparison to other columns of the same unit.

An example might be a bank account number: The number in itself is hardly interesting, but it might be useful to know how often we have seen that same bank account number in another table.

For more information on units, please refer to the User Guide.

TYPE: bool DEFAULT: False

Source code in getml/data/data_frame.py
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
def with_unit(
    self,
    cols: Union[
        str,
        FloatColumn,
        StringColumn,
        Union[Iterable[str], List[FloatColumn], List[StringColumn]],
    ],
    unit: str,
    comparison_only: bool = False,
):
    """Returns a view that contains a new unit on one or more columns.

    The difference between [`with_unit`][getml.DataFrame.with_unit] and
    [`set_unit`][getml.DataFrame.set_unit] is that
    [`with_unit`][getml.DataFrame.with_unit] returns a view that is lazily
    evaluated when needed whereas [`set_unit`][getml.DataFrame.set_unit]
    is an in-place operation. From a memory perspective, in-place operations
    like [`set_unit`][getml.DataFrame.set_unit] are preferable.

    Args:
        cols:
            The columns or the names thereof.

        unit:
            The unit to be assigned.

        comparison_only:
            Whether you want the column to
            be used for comparison only. This means that the column can
            only be used in comparison to other columns of the same unit.

            An example might be a bank account number: The number in itself
            is hardly interesting, but it might be useful to know how often
            we have seen that same bank account number in another table.

            For more information on units, please refer to the
            [User Guide][annotating-data-units].
    """
    return _with_unit(self, cols, unit, comparison_only)