Pandas match dict 'else'

I have a problem:

import pandas

new_dict={
    'a':1,
    'b':2,
    'else':4
}
df=pandas.DataFrame([['new1','a'],['new2','b'],['new3','c'],['new4','d'],['new5','b']],columns=['new','id'])

df like this

    new id
0  new1  a
1  new2  b
2  new3  c
3  new4  d
4  new5  b

the result I wanted:

   new id
0  new1  1
1  new2  2
2  new3  4
3  new4  4
4  new5  2

I am trying to convert a dict to a data framework and use the merge method. but "else" does not match:

import pandas

new_dict={'newid':['a','b','else'],
      'idd':[1,2,4]}
df2=pandas.DataFrame(new_dict,columns=['newid','idd'])
df=pandas.DataFrame([['new1','a'],['new2','b'],['new3','c'],['new4','d'],['new5','b']],columns=['new','id'])

I am trying to use the pandas merge method to solve this problem, but I do not know what the next step should be. Thank!

+4
source share
2 answers

You can use map:

df.id = df.id.map(new_dict).fillna(new_dict['else']).astype(int)
print (df)
    new  id
0  new1   1
1  new2   2
2  new3   4
3  new4   4
4  new5   2

Another solution with numpy.where:

df.id = np.where(df.id.isin(new_dict), df.id.map(new_dict), new_dict['else']).astype(int)
print (df)
    new  id
0  new1   1
1  new2   2
2  new3   4
3  new4   4
4  new5   2
+3
source

map .
, , get, .

def new(x):
    new_dict = dict(a=1, b=2)
    return new_dict.get(x, 4)

df=pd.DataFrame([
    ['new1','a'],['new2','b'],
    ['new3','c'],['new4','d'],
    ['new5','b']],
    columns=['new','id'])


df.id = df.id.map(new)

print(df)

    new  id
0  new1   1
1  new2   2
2  new3   4
3  new4   4
4  new5   2
+2

Source: https://habr.com/ru/post/1667229/


All Articles