Skip to content

Chemistry

Chemistry and cheminformatics-oriented data cleaning functions.

maccs_keys_fingerprint(df, mols_column_name)

Convert a column of RDKIT mol objects into MACCS Keys Fingerprints.

Returns a new dataframe without any of the original data. This is intentional to leave the user with the data requested.

This method does not mutate the original DataFrame.

Examples:

Functional usage

>>> import pandas as pd
>>> import janitor.chemistry
>>> df = pd.DataFrame({"smiles": ["O=C=O", "CCC(=O)O"]})
>>> maccs = janitor.chemistry.maccs_keys_fingerprint(
...     df=df.smiles2mol('smiles', 'mols'),
...     mols_column_name='mols'
... )
>>> len(maccs.columns)
167

Method chaining usage

>>> import pandas as pd
>>> import janitor.chemistry
>>> df = pd.DataFrame({"smiles": ["O=C=O", "CCC(=O)O"]})
>>> maccs = (
...     df.smiles2mol('smiles', 'mols')
...         .maccs_keys_fingerprint(mols_column_name='mols')
... )
>>> len(maccs.columns)
167

If you wish to join the maccs keys fingerprints back into the original dataframe, this can be accomplished by doing a join, because the indices are preserved:

>>> joined = df.join(maccs)
>>> len(joined.columns)
169

Parameters:

Name Type Description Default
df DataFrame

A pandas DataFrame.

required
mols_column_name Hashable

The name of the column that has the RDKIT mol objects.

required

Returns:

Type Description
DataFrame

A new pandas DataFrame of MACCS keys fingerprints.

Source code in janitor/chemistry.py
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
@pf.register_dataframe_method
@deprecated_alias(mols_col="mols_column_name")
def maccs_keys_fingerprint(
    df: pd.DataFrame, mols_column_name: Hashable
) -> pd.DataFrame:
    """Convert a column of RDKIT mol objects into MACCS Keys Fingerprints.

    Returns a new dataframe without any of the original data.
    This is intentional to leave the user with the data requested.

    This method does not mutate the original DataFrame.

    Examples:
        Functional usage

        >>> import pandas as pd
        >>> import janitor.chemistry
        >>> df = pd.DataFrame({"smiles": ["O=C=O", "CCC(=O)O"]})
        >>> maccs = janitor.chemistry.maccs_keys_fingerprint(
        ...     df=df.smiles2mol('smiles', 'mols'),
        ...     mols_column_name='mols'
        ... )
        >>> len(maccs.columns)
        167

        Method chaining usage

        >>> import pandas as pd
        >>> import janitor.chemistry
        >>> df = pd.DataFrame({"smiles": ["O=C=O", "CCC(=O)O"]})
        >>> maccs = (
        ...     df.smiles2mol('smiles', 'mols')
        ...         .maccs_keys_fingerprint(mols_column_name='mols')
        ... )
        >>> len(maccs.columns)
        167

        If you wish to join the maccs keys fingerprints back into the
        original dataframe, this can be accomplished by doing a `join`,
        because the indices are preserved:

        >>> joined = df.join(maccs)
        >>> len(joined.columns)
        169

    Args:
        df: A pandas DataFrame.
        mols_column_name: The name of the column that has the RDKIT mol
            objects.

    Returns:
        A new pandas DataFrame of MACCS keys fingerprints.
    """

    maccs = [GetMACCSKeysFingerprint(m) for m in df[mols_column_name]]

    np_maccs = []

    for macc in maccs:
        arr = np.zeros((1,))
        DataStructs.ConvertToNumpyArray(macc, arr)
        np_maccs.append(arr)
    np_maccs = np.vstack(np_maccs)
    fmaccs = pd.DataFrame(np_maccs)
    fmaccs.index = df.index
    return fmaccs

molecular_descriptors(df, mols_column_name)

Convert a column of RDKIT mol objects into a Pandas DataFrame of molecular descriptors.

Returns a new dataframe without any of the original data. This is intentional to leave the user only with the data requested.

This method does not mutate the original DataFrame.

The molecular descriptors are from the rdkit.Chem.rdMolDescriptors:

Chi0n, Chi0v, Chi1n, Chi1v, Chi2n, Chi2v, Chi3n, Chi3v,
Chi4n, Chi4v, ExactMolWt, FractionCSP3, HallKierAlpha, Kappa1,
Kappa2, Kappa3, LabuteASA, NumAliphaticCarbocycles,
NumAliphaticHeterocycles, NumAliphaticRings, NumAmideBonds,
NumAromaticCarbocycles, NumAromaticHeterocycles, NumAromaticRings,
NumAtomStereoCenters, NumBridgeheadAtoms, NumHBA, NumHBD,
NumHeteroatoms, NumHeterocycles, NumLipinskiHBA, NumLipinskiHBD,
NumRings, NumSaturatedCarbocycles, NumSaturatedHeterocycles,
NumSaturatedRings, NumSpiroAtoms, NumUnspecifiedAtomStereoCenters,
TPSA.

Examples:

Functional usage

>>> import pandas as pd
>>> import janitor.chemistry
>>> df = pd.DataFrame({"smiles": ["O=C=O", "CCC(=O)O"]})
>>> mol_desc = (
...     janitor.chemistry.molecular_descriptors(
...         df=df.smiles2mol('smiles', 'mols'),
...         mols_column_name='mols'
...     )
... )
>>> mol_desc.TPSA
0    34.14
1    37.30
Name: TPSA, dtype: float64

Method chaining usage

>>> import pandas as pd
>>> import janitor.chemistry
>>> df = pd.DataFrame({"smiles": ["O=C=O", "CCC(=O)O"]})
>>> mol_desc = (
...     df.smiles2mol('smiles', 'mols')
...     .molecular_descriptors(mols_column_name='mols')
... )
>>> mol_desc.TPSA
0    34.14
1    37.30
Name: TPSA, dtype: float64

If you wish to join the molecular descriptors back into the original dataframe, this can be accomplished by doing a join, because the indices are preserved:

>>> joined = df.join(mol_desc)
>>> len(joined.columns)
41

Parameters:

Name Type Description Default
df DataFrame

A pandas DataFrame.

required
mols_column_name Hashable

The name of the column that has the RDKIT mol objects.

required

Returns:

Type Description
DataFrame

A new pandas DataFrame of molecular descriptors.

Source code in janitor/chemistry.py
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
@pf.register_dataframe_method
@deprecated_alias(mols_col="mols_column_name")
def molecular_descriptors(
    df: pd.DataFrame, mols_column_name: Hashable
) -> pd.DataFrame:
    """Convert a column of RDKIT mol objects into a Pandas DataFrame
    of molecular descriptors.

    Returns a new dataframe without any of the original data. This is
    intentional to leave the user only with the data requested.

    This method does not mutate the original DataFrame.

    The molecular descriptors are from the `rdkit.Chem.rdMolDescriptors`:

    ```text
    Chi0n, Chi0v, Chi1n, Chi1v, Chi2n, Chi2v, Chi3n, Chi3v,
    Chi4n, Chi4v, ExactMolWt, FractionCSP3, HallKierAlpha, Kappa1,
    Kappa2, Kappa3, LabuteASA, NumAliphaticCarbocycles,
    NumAliphaticHeterocycles, NumAliphaticRings, NumAmideBonds,
    NumAromaticCarbocycles, NumAromaticHeterocycles, NumAromaticRings,
    NumAtomStereoCenters, NumBridgeheadAtoms, NumHBA, NumHBD,
    NumHeteroatoms, NumHeterocycles, NumLipinskiHBA, NumLipinskiHBD,
    NumRings, NumSaturatedCarbocycles, NumSaturatedHeterocycles,
    NumSaturatedRings, NumSpiroAtoms, NumUnspecifiedAtomStereoCenters,
    TPSA.
    ```

    Examples:
        Functional usage

        >>> import pandas as pd
        >>> import janitor.chemistry
        >>> df = pd.DataFrame({"smiles": ["O=C=O", "CCC(=O)O"]})
        >>> mol_desc = (
        ...     janitor.chemistry.molecular_descriptors(
        ...         df=df.smiles2mol('smiles', 'mols'),
        ...         mols_column_name='mols'
        ...     )
        ... )
        >>> mol_desc.TPSA
        0    34.14
        1    37.30
        Name: TPSA, dtype: float64

        Method chaining usage

        >>> import pandas as pd
        >>> import janitor.chemistry
        >>> df = pd.DataFrame({"smiles": ["O=C=O", "CCC(=O)O"]})
        >>> mol_desc = (
        ...     df.smiles2mol('smiles', 'mols')
        ...     .molecular_descriptors(mols_column_name='mols')
        ... )
        >>> mol_desc.TPSA
        0    34.14
        1    37.30
        Name: TPSA, dtype: float64

        If you wish to join the molecular descriptors back into the original
        dataframe, this can be accomplished by doing a `join`,
        because the indices are preserved:

        >>> joined = df.join(mol_desc)
        >>> len(joined.columns)
        41

    Args:
        df: A pandas DataFrame.
        mols_column_name: The name of the column that has the RDKIT mol
            objects.

    Returns:
        A new pandas DataFrame of molecular descriptors.
    """
    descriptors = [
        CalcChi0n,
        CalcChi0v,
        CalcChi1n,
        CalcChi1v,
        CalcChi2n,
        CalcChi2v,
        CalcChi3n,
        CalcChi3v,
        CalcChi4n,
        CalcChi4v,
        CalcExactMolWt,
        CalcFractionCSP3,
        CalcHallKierAlpha,
        CalcKappa1,
        CalcKappa2,
        CalcKappa3,
        CalcLabuteASA,
        CalcNumAliphaticCarbocycles,
        CalcNumAliphaticHeterocycles,
        CalcNumAliphaticRings,
        CalcNumAmideBonds,
        CalcNumAromaticCarbocycles,
        CalcNumAromaticHeterocycles,
        CalcNumAromaticRings,
        CalcNumAtomStereoCenters,
        CalcNumBridgeheadAtoms,
        CalcNumHBA,
        CalcNumHBD,
        CalcNumHeteroatoms,
        CalcNumHeterocycles,
        CalcNumLipinskiHBA,
        CalcNumLipinskiHBD,
        CalcNumRings,
        CalcNumSaturatedCarbocycles,
        CalcNumSaturatedHeterocycles,
        CalcNumSaturatedRings,
        CalcNumSpiroAtoms,
        CalcNumUnspecifiedAtomStereoCenters,
        CalcTPSA,
    ]
    descriptors_mapping = {f.__name__.strip("Calc"): f for f in descriptors}

    feats = dict()
    for name, func in descriptors_mapping.items():
        feats[name] = [func(m) for m in df[mols_column_name]]
    return pd.DataFrame(feats)

morgan_fingerprint(df, mols_column_name, radius=3, nbits=2048, kind='counts')

Convert a column of RDKIT Mol objects into Morgan Fingerprints.

Returns a new dataframe without any of the original data. This is intentional, as Morgan fingerprints are usually high-dimensional features.

This method does not mutate the original DataFrame.

Examples:

Functional usage

>>> import pandas as pd
>>> import janitor.chemistry
>>> df = pd.DataFrame({"smiles": ["O=C=O", "CCC(=O)O"]})
  • For "counts" kind
>>> morgans = janitor.chemistry.morgan_fingerprint(
...     df=df.smiles2mol('smiles', 'mols'),
...     mols_column_name='mols',
...     radius=3,      # Defaults to 3
...     nbits=2048,    # Defaults to 2048
...     kind='counts'  # Defaults to "counts"
... )
>>> set(morgans.iloc[0])
{0.0, 1.0, 2.0}
  • For "bits" kind
>>> morgans = janitor.chemistry.morgan_fingerprint(
...     df=df.smiles2mol('smiles', 'mols'),
...     mols_column_name='mols',
...     radius=3,      # Defaults to 3
...     nbits=2048,    # Defaults to 2048
...     kind='bits'    # Defaults to "counts"
...  )
>>> set(morgans.iloc[0])
{0.0, 1.0}

Method chaining usage

>>> import pandas as pd
>>> import janitor.chemistry
>>> df = pd.DataFrame({"smiles": ["O=C=O", "CCC(=O)O"]})
  • For "counts" kind
>>> morgans = (
...     df.smiles2mol('smiles', 'mols')
...     .morgan_fingerprint(
...         mols_column_name='mols',
...         radius=3,      # Defaults to 3
...         nbits=2048,    # Defaults to 2048
...         kind='counts'  # Defaults to "counts"
...     )
... )
>>> set(morgans.iloc[0])
{0.0, 1.0, 2.0}
  • For "bits" kind
>>> morgans = (
...     df
...     .smiles2mol('smiles', 'mols')
...     .morgan_fingerprint(
...         mols_column_name='mols',
...         radius=3,    # Defaults to 3
...         nbits=2048,  # Defaults to 2048
...         kind='bits'  # Defaults to "counts"
...     )
... )
>>> set(morgans.iloc[0])
{0.0, 1.0}

If you wish to join the morgan fingerprints back into the original dataframe, this can be accomplished by doing a join, because the indices are preserved:

>>> joined = df.join(morgans)
>>> len(joined.columns)
2050

Parameters:

Name Type Description Default
df DataFrame

A pandas DataFrame.

required
mols_column_name str

The name of the column that has the RDKIT mol objects

required
radius int

Radius of Morgan fingerprints.

3
nbits int

The length of the fingerprints.

2048
kind Literal['counts', 'bits']

Whether to return counts or bits.

'counts'

Raises:

Type Description
ValueError

If kind is not one of "counts" or "bits".

Returns:

Type Description
DataFrame

A new pandas DataFrame of Morgan fingerprints.

Source code in janitor/chemistry.py
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
@pf.register_dataframe_method
@deprecated_alias(mols_col="mols_column_name")
def morgan_fingerprint(
    df: pd.DataFrame,
    mols_column_name: str,
    radius: int = 3,
    nbits: int = 2048,
    kind: Literal["counts", "bits"] = "counts",
) -> pd.DataFrame:
    """Convert a column of RDKIT Mol objects into Morgan Fingerprints.

    Returns a new dataframe without any of the original data. This is
    intentional, as Morgan fingerprints are usually high-dimensional
    features.

    This method does not mutate the original DataFrame.

    Examples:
        Functional usage

        >>> import pandas as pd
        >>> import janitor.chemistry
        >>> df = pd.DataFrame({"smiles": ["O=C=O", "CCC(=O)O"]})

        - For "counts" kind

        >>> morgans = janitor.chemistry.morgan_fingerprint(
        ...     df=df.smiles2mol('smiles', 'mols'),
        ...     mols_column_name='mols',
        ...     radius=3,      # Defaults to 3
        ...     nbits=2048,    # Defaults to 2048
        ...     kind='counts'  # Defaults to "counts"
        ... )
        >>> set(morgans.iloc[0])
        {0.0, 1.0, 2.0}

        - For "bits" kind

        >>> morgans = janitor.chemistry.morgan_fingerprint(
        ...     df=df.smiles2mol('smiles', 'mols'),
        ...     mols_column_name='mols',
        ...     radius=3,      # Defaults to 3
        ...     nbits=2048,    # Defaults to 2048
        ...     kind='bits'    # Defaults to "counts"
        ...  )
        >>> set(morgans.iloc[0])
        {0.0, 1.0}

        Method chaining usage

        >>> import pandas as pd
        >>> import janitor.chemistry
        >>> df = pd.DataFrame({"smiles": ["O=C=O", "CCC(=O)O"]})

        - For "counts" kind

        >>> morgans = (
        ...     df.smiles2mol('smiles', 'mols')
        ...     .morgan_fingerprint(
        ...         mols_column_name='mols',
        ...         radius=3,      # Defaults to 3
        ...         nbits=2048,    # Defaults to 2048
        ...         kind='counts'  # Defaults to "counts"
        ...     )
        ... )
        >>> set(morgans.iloc[0])
        {0.0, 1.0, 2.0}

        - For "bits" kind

        >>> morgans = (
        ...     df
        ...     .smiles2mol('smiles', 'mols')
        ...     .morgan_fingerprint(
        ...         mols_column_name='mols',
        ...         radius=3,    # Defaults to 3
        ...         nbits=2048,  # Defaults to 2048
        ...         kind='bits'  # Defaults to "counts"
        ...     )
        ... )
        >>> set(morgans.iloc[0])
        {0.0, 1.0}

        If you wish to join the morgan fingerprints back into the original
        dataframe, this can be accomplished by doing a `join`,
        because the indices are preserved:

        >>> joined = df.join(morgans)
        >>> len(joined.columns)
        2050

    Args:
        df: A pandas DataFrame.
        mols_column_name: The name of the column that has the RDKIT
            mol objects
        radius: Radius of Morgan fingerprints.
        nbits: The length of the fingerprints.
        kind: Whether to return counts or bits.

    Raises:
        ValueError: If `kind` is not one of `"counts"` or `"bits"`.

    Returns:
        A new pandas DataFrame of Morgan fingerprints.
    """
    acceptable_kinds = ["counts", "bits"]
    if kind not in acceptable_kinds:
        raise ValueError(f"`kind` must be one of {acceptable_kinds}")

    if kind == "bits":
        fps = [
            GetMorganFingerprintAsBitVect(m, radius, nbits, useChirality=True)
            for m in df[mols_column_name]
        ]
    elif kind == "counts":
        fps = [
            GetHashedMorganFingerprint(m, radius, nbits, useChirality=True)
            for m in df[mols_column_name]
        ]

    np_fps = []
    for fp in fps:
        arr = np.zeros((1,))
        DataStructs.ConvertToNumpyArray(fp, arr)
        np_fps.append(arr)
    np_fps = np.vstack(np_fps)
    fpdf = pd.DataFrame(np_fps)
    fpdf.index = df.index
    return fpdf

smiles2mol(df, smiles_column_name, mols_column_name, drop_nulls=True, progressbar=None)

Convert a column of SMILES strings into RDKit Mol objects.

Automatically drops invalid SMILES, as determined by RDKIT.

This method mutates the original DataFrame.

Examples:

Functional usage

>>> import pandas as pd
>>> import janitor.chemistry
>>> df = pd.DataFrame({"smiles": ["O=C=O", "CCC(=O)O"]})
>>> df = janitor.chemistry.smiles2mol(
...    df=df,
...    smiles_column_name='smiles',
...    mols_column_name='mols'
... )
>>> df.mols[0].GetNumAtoms(), df.mols[0].GetNumBonds()
(3, 2)
>>> df.mols[1].GetNumAtoms(), df.mols[1].GetNumBonds()
(5, 4)

Method chaining usage

>>> import pandas as pd
>>> import janitor.chemistry
>>> df = df.smiles2mol(
...     smiles_column_name='smiles',
...     mols_column_name='rdkmol'
... )
>>> df.rdkmol[0].GetNumAtoms(), df.rdkmol[0].GetNumBonds()
(3, 2)

A progressbar can be optionally used.

  • Pass in "notebook" to show a tqdm notebook progressbar. (ipywidgets must be enabled with your Jupyter installation.)
  • Pass in "terminal" to show a tqdm progressbar. Better suited for use with scripts.
  • None is the default value - progress bar will not be shown.

Parameters:

Name Type Description Default
df DataFrame

pandas DataFrame.

required
smiles_column_name Hashable

Name of column that holds the SMILES strings.

required
mols_column_name Hashable

Name to be given to the new mols column.

required
drop_nulls bool

Whether to drop rows whose mols failed to be constructed.

True
progressbar Optional[str]

Whether to show a progressbar or not.

None

Raises:

Type Description
ValueError

If progressbar is not one of "notebook", "terminal", or None.

Returns:

Type Description
DataFrame

A pandas DataFrame with new RDKIT Mol objects column.

Source code in janitor/chemistry.py
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
@pf.register_dataframe_method
@deprecated_alias(smiles_col="smiles_column_name", mols_col="mols_column_name")
def smiles2mol(
    df: pd.DataFrame,
    smiles_column_name: Hashable,
    mols_column_name: Hashable,
    drop_nulls: bool = True,
    progressbar: Optional[str] = None,
) -> pd.DataFrame:
    """Convert a column of SMILES strings into RDKit Mol objects.

    Automatically drops invalid SMILES, as determined by RDKIT.

    This method mutates the original DataFrame.

    Examples:
        Functional usage

        >>> import pandas as pd
        >>> import janitor.chemistry
        >>> df = pd.DataFrame({"smiles": ["O=C=O", "CCC(=O)O"]})
        >>> df = janitor.chemistry.smiles2mol(
        ...    df=df,
        ...    smiles_column_name='smiles',
        ...    mols_column_name='mols'
        ... )
        >>> df.mols[0].GetNumAtoms(), df.mols[0].GetNumBonds()
        (3, 2)
        >>> df.mols[1].GetNumAtoms(), df.mols[1].GetNumBonds()
        (5, 4)

        Method chaining usage

        >>> import pandas as pd
        >>> import janitor.chemistry
        >>> df = df.smiles2mol(
        ...     smiles_column_name='smiles',
        ...     mols_column_name='rdkmol'
        ... )
        >>> df.rdkmol[0].GetNumAtoms(), df.rdkmol[0].GetNumBonds()
        (3, 2)

    A progressbar can be optionally used.

    - Pass in "notebook" to show a `tqdm` notebook progressbar.
      (`ipywidgets` must be enabled with your Jupyter installation.)
    - Pass in "terminal" to show a `tqdm` progressbar. Better suited for use
      with scripts.
    - `None` is the default value - progress bar will not be shown.

    Args:
        df: pandas DataFrame.
        smiles_column_name: Name of column that holds the SMILES strings.
        mols_column_name: Name to be given to the new mols column.
        drop_nulls: Whether to drop rows whose mols failed to be
            constructed.
        progressbar: Whether to show a progressbar or not.

    Raises:
        ValueError: If `progressbar` is not one of
            `"notebook"`, `"terminal"`, or `None`.

    Returns:
        A pandas DataFrame with new RDKIT Mol objects column.
    """
    valid_progress = ["notebook", "terminal", None]
    if progressbar not in valid_progress:
        raise ValueError(f"progressbar kwarg must be one of {valid_progress}")

    if progressbar is None:
        df[mols_column_name] = df[smiles_column_name].apply(
            lambda x: Chem.MolFromSmiles(x)
        )
    else:
        if progressbar == "notebook":
            tqdmn().pandas(desc="mols")
        elif progressbar == "terminal":
            tqdm.pandas(desc="mols")
        df[mols_column_name] = df[smiles_column_name].progress_apply(
            lambda x: Chem.MolFromSmiles(x)
        )

    if drop_nulls:
        df = df.dropna(subset=[mols_column_name])
    df = df.reset_index(drop=True)
    return df