Home > Blockchain >  How to replace multiple value in a pandas DataFrame
How to replace multiple value in a pandas DataFrame

Time:02-09

How can I replace multiple values with another different multiple values (stored in an array) in a pandas DataFrame?

In detail: I want to replace the values in every rows of columns called 'Cloud3pm' of the dataframe 'df', in which the value is = -1. I want to replace this cells values respectively with an array of values with length equal to the number of occurrences of values equal to -1 that I will go to find on the dataframe.

CodePudding user response:

Instead of using replace for this, you should be able to just assign a list directly to the dataframe indexed by a mask.

Let's say you have a dataframe in which a total of 5 values in any columns are -1. So there are five -1 values in the dataframe. If you want to replace them with 1, 2, 3, 4, and 5, respectively, you could do this:

df[df == -1] = [1, 2, 3, 4, 5]

If you wanted to do that only for a particular column, you'd do this:

df.loc[df['Your Column'] == -1, 'Your Column'] = [1, 2, 3, 4, 5]

Note that if the list of items you're trying to assign is actually a numpy array, you'll need to call .tolist() on it first, e.g.

df[df == -1] = my_array.tolist()
  •  Tags:  
  • Related