0

I'm quite new to python so bear with me if this is obvious.

I've got a column, 'age', in a dataframe, dff, containing the values 1 to 66. Each value corresponds to a key in the dictionary, di, and I'm trying to replace the values in the column with the corresponding values from the dictionary.

I can do this for a single value, for example:

dff['age'] = dff['age'].replace('1', di.get('1'))

But I want to do it for all 66 values. I tried this:

i = 1
while i <= 66:
    i = str(i)
    dff['age'] = dff['age'].replace(i, di.get(i))
    i = int(i)
    i = i + 1

Which doesn't seem to change the values in the column at all. Any ideas? Thanks.

Todd
  • 1
  • 3
  • 2
    sorry are you wanting `dff['age'] = dff['age'].map(di)`? also your issue with the `for` loop is you're overwriting the entire column on each iteration so the last iteration will persist – EdChum Jul 04 '16 at 11:26
  • Thank for the quick response, @EdChum. I've tried map, but that only ever seems to return NaN for every value. – Todd Jul 04 '16 at 11:42
  • 1
    If "each value corresponds to a key in the dictionary, di" then it should work well. Check the types of the keys if it's returning NaN. – ayhan Jul 04 '16 at 11:44
  • Ah, thanks, @ayhan . My keys are str and the values int. How do I sort this? – Todd Jul 04 '16 at 11:48
  • You can temporarily change the age column `dff[age].astype(str).map(di)` or it would be better to modify the dictionary: `di = {int(k): v for k, v in di.items()}` – ayhan Jul 04 '16 at 11:55

1 Answers1

0

I think .replace() will do a better job. .map() fills nans if a particular match is not found. Purely depends on which is the desired output

dff['age'] = dff['age'].replace(di)

For example

dff = pd.DataFrame(['a', 'b', 'c', 'd', 'a'], columns=['age'])

df['age'].replace({'a': '10-25', 'b': '50-60'})
0    10-25
1    50-60
2        c
3        d
4    10-25
Name: age, dtype: object

Where .map() will introduce nan.

dff['age'].map({'a': '10-25', 'b': '50-60'})
0    10-25
1    50-60
2      NaN
3      NaN
4    10-25
Name: age, dtype: object
Kathirmani Sukumar
  • 10,445
  • 5
  • 33
  • 34