Home > database >  Replace element with specific value to pandas dataframe
Replace element with specific value to pandas dataframe

Time:03-13

I have a pandas dataframe with the following form:

                       cluster number
Robin_lodging_Dorthy          0
Robin_lodging_Phillip         1
Robin_lodging_Elmer           2
        ...                  ...

I want to replace replace every 0 that is in the column cluster number with with the string "low", every 1 with "mid" and every 2 with "high". Any idea of how that can be possible?

CodePudding user response:

You can use replace function with some mappings to change your column values:

values = {
    0: 'low',
    1: 'mid',
    2: 'high'
}
data = {
  'name': ['Robin_lodging_Dorthy', 'Robin_lodging_Phillip', 'Robin_lodging_Elmer'],
  'cluster_number': [0, 1, 2]
}
df = pd.DataFrame(data)
df.replace({'cluster_number': values}, inplace=True)
df

Output:

                    name cluster_number
0   Robin_lodging_Dorthy            low
1  Robin_lodging_Phillip            mid
2    Robin_lodging_Elmer           high

More info on replace function.

  • Related