0

If I want to set the same value for all matches I can do:

df.loc[df.A.isin(some_list), 'C'] = value

The replace and update methods change existing values in some column, but don't seem to allow changing values in column C for the matching entries in column A as explained below.

Remap values in pandas column with a dict

But what if I have a dictionary (or two aligned lists - one with A and one with C values)?

I can loop over the keys in dict and change the values one-by-one, but that is awfully slow.

mibm
  • 1,328
  • 2
  • 13
  • 23

1 Answers1

0

If I understand your problem correctly then you want to change the values in column C based on values in column A and the actual value assigned to C is looked up in a dictionary but still you want to leave those rows untouched where a value in A is not present in the dictionary mapping.

Dictionary m is used for mapping values from column A to the target value:

df = pandas.DataFrame({'A': [1,2,3,4,5,6,7,8,9], 'C': [0,0,0,0,0,0,0,0,0]})
m = {1:1,3:1,6:1,8:1}

Then you need to select all rows in A that match the keys of the dictionary using select. Then you map the values of column A using m and assign the result to the filtered values of column C. The other values remain like before.

select = df['A'].isin(m.keys())
df.loc[select, 'C'] = df.loc[select, 'A'].map(m)
Viktor
  • 396
  • 1
  • 11
  • Yes, that is exactly what I was looking for, thanks! Is is possible to this in a single command (obviously without doing the selection twice)? – mibm Jul 24 '18 at 09:46
  • There is no inplace parameter for apply or map, so to my knowledge I don't think that is possible unless you accept to overwrite the values from column A. But I made minor change. – Viktor Jul 24 '18 at 12:32