Home > Net >  How can I change the number of int value to another number in a column?
How can I change the number of int value to another number in a column?

Time:03-18

The dataframe dataset has two columns 'Review' and 'Label' and dtypes of 'Label' is int. enter image description here

I would like to change the number in the 'Label' column. So I tried to use replace() but it doesn't change well as you can see in the below picture.

enter image description here

CodePudding user response:

A simple and quick solution(besides replace) would be to use a Series.map() method. You could define a dictionary with keys corresponding to the values you want to replace and values set to the new values you wish to have. Then, use an anonymous function(or normal one) to replace your values

d={1:0,2:0,4:1,5:1}
dataset['label']=dataset['label'].map(lambda x: d[x])

This will replace 1 and 2 with 0, and 4 and 5 with 1.

I am not sure what your criteria for "well" is, as the replace method will work for you and essentially achieve the same result(and is more optimized than map for replacement purposes).

What might be causing the issues is that replace has a default arg inplace=False. Thus, your results will not affect each other and you will have to combine them into dataset['label']=dataset['label'].replace([1,2,4,5],[0,0,1,1]) or dataset['label'].replace([1,2,4,5],[0,0,1,1],inplace=True)

  • Related