Error replacing values in a column using pandas

738 views python
3

I am trying to replace the values in a column with numbers. These are the unique values in the column:

['R2' '01' '02' 'C1']

So I did this

data = pd.read_csv('file.csv')
df = pd.DataFrame(data)

df['rates'].apply({'R2': 1, '01' : 2, '02' : 3, 'C1' : 4}.get)

But when I try to print out df['rates'] after the supposed replacement, I still got same values:

['R2' '01' '02' 'C1']

This is how my file.csv looks like

amount,id,rates,height
1400,4,R2,3
1389,6,R2,8
10000,1,01,13

answered question

Can you provide code to produce your series? That looks like it should work.

@piRSquared I have added it

You also need to show the contents of the file. Only first few lines.

I have added it @piRSquared

Ohh. I think I know/crosses fingers. Apply doesn’t change the dataframe. You need to assign back to column

How do I do that?

I got it resolved. I needed to assign. See accepted answer

1 Answer

5

Try map:

df['rates'].map({'R2': 1, '01' : 2, '02' : 3, 'C1' : 4},inplace=True)

Or:

df['rates'] = df['rates'].map({'R2': 1, '01' : 2, '02' : 3, 'C1' : 4})

Actually your code works but need to assign:

df['rates']=df['rates'].apply({'R2': 1, '01' : 2, '02' : 3, 'C1' : 4}.get)

posted this

Have an answer?

JD

Please login first before posting an answer.