Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace values in pandas datatable if in list

Tags:

python

pandas

How can I replace values in the datatable data with information in filllist if a value is in varlist?

import pandas as pd
data = pd.DataFrame({'A' : [5,6,3,4], 'B' : [1,2,3, 10]})
varlist = (5,7,9,10)
fillist = ('a', 'b', 'c', 'd')
data[data.isin(varlist)==True] = 'is in varlist!'

Returns data as:

    A               B
 0  is in varlist!  1
 1  6               2
 2  3               3
 3  4               is in varlist!

But I want:

    A               B
 0  a               1
 1  6               2
 2  3               3
 3  4               d
like image 745
Joost Döbken Avatar asked Oct 24 '25 05:10

Joost Döbken


1 Answers

Use the replace method of the dataframe.

replace_map = dict(zip(varlist, fillist))
data.replace(replace_map)

this gives

   A  B
0  a  1
1  6  2
2  3  3
3  4  d

The documentation is here in case you want to use it in a different way: replace method documentation

like image 195
Davis Kirkendall Avatar answered Oct 26 '25 18:10

Davis Kirkendall