How To Replace Values In Pandas DataFrame?


How To Replace Values In Pandas DataFrame?

Table Of Contents:

  1. Syntax ‘replace( )’ Method In Pandas.
  2. Examples ‘replace( )’ Method.

(1) Syntax:

DataFrame.replace(to_replace=None, value=_NoDefault.no_default, *, inplace=False, 
                 limit=None, regex=False, method=_NoDefault.no_default)

Description:

  • Replace values given in to_replace with value.

  • Values of the DataFrame are replaced with other values dynamically.

  • This differs from updating with .loc or .iloc, which requires you to specify a location to update with some value.

Parameters:

  • to_replace: str, regex, list, dict, Series, int, float, or None –
    • How to find the values that will be replaced.
  • value: scalar, dict, list, str, regex, default None –
    • Value to replace any values matching to_replace with. For a DataFrame a dict of values can be used to specify which value to use for each column (columns not in the dict will not be filled). Regular expressions, strings and lists or dicts of such objects are also allowed.
  • inplace: bool, default False –
    • Whether to modify the DataFrame rather than create a new one.
  • limit: int, default None –
    • Maximum size gap to forward or backward fill.
  • regex: bool or same types as to_replace, default False –
    • Whether to interpret to_replace and/or value as regular expressions. If this is True then to_replace must be a string. Alternatively, this could be a regular expression or a list, dict, or array of regular expressions in which case to_replace must be None.
  • method: {‘pad’, ‘ffill’, ‘bfill’} –
    • The method to use when for replacement, when to_replace is a scalar, list or tuple and value is None.

Returns:

  • DataFrame – Object after replacement.

Raises:

  • AssertionError – 
    • If regex is not a bool and to_replace is not None.

  • TypeError
    • If to_replace is not a scalar, array-like, dict, or None

    • If to_replace is a dict and value is not a listdictndarray, or Series

    • If to_replace is None and regex is not compilable into a regular expression or is a list, dict, ndarray, or Series.

    • When replacing multiple bool or datetime64 objects and the arguments to to_replace does not match the type of the value being replaced.

  • ValueError
    • If a list or an ndarray is passed to to_replace and value but they are not the same length.

 

(2) Examples Of replace() Method:

Example-1:

df = pd.DataFrame({'A': [0, 1, 2, 3, 4],
                   'B': [5, 6, 7, 8, 9],
                   'C': ['a', 'b', 'c', 'd', 'e']})
df

Output:

# Replacing ‘0’ With ‘5’

df.replace(0, 5)

Output:

# Replacing Original DataFrame

df.replace(1, 111, inplace=True)
df

Output:

# Replacing Multiple Column Values At A Time

df.replace([1,5,'c'], ['@','#','$'])
df

Output:

Leave a Reply

Your email address will not be published. Required fields are marked *