Peter
Peter

Reputation: 564

Replace 0 for variable by special condition

I am trying to replace all 0 in a column, but there are two constraints.

data

cw=

name         values
google        0
facebook      0
microsoft     0
google        2
facebook      55
microsoft     7
google        5
facebook      80
microsoft     66


My attempts

google =  99999
microsoft = 88888
facebook = 66666


# first attempt
cw.loc[cw['name'] == "Google"].replace(0, google) 
cw.loc[cw['name'] == "Bing"].replace(0, bing) 
cw.loc[cw['name'] == "Facebook"].replace(0, facebook) 



# second attempt
for x in cw.all():
    if cw.name== "Google":
        cw.loc[cw['values'] == 0, 'values'] = google


Neither works..

so the desired output is..

cw=

name         values
google        99999
facebook      66666
microsoft     88888
google        2
facebook      55
microsoft     7
google        5
facebook      80
microsoft     66

Upvotes: 0

Views: 43

Answers (2)

mukulgarg94
mukulgarg94

Reputation: 51

Below solution is a modification of your first attempt

google =  99999
microsoft = 88888
facebook = 66666


cw.loc[cw['name'] == "google",'values'] = cw.loc[df['name'] == "google",'values'].replace(0, google) 

cw.loc[cw['name'] == "microsoft",'values'] = cw.loc[df['name'] == "microsoft",'values'].replace(0, microsoft) 

cw.loc[cw['name'] == "facebook",'values'] = cw.loc[df['name'] == "facebook",'values'].replace(0, facebook)

This works fine and meets the constraint(s).

Upvotes: 1

Quang Hoang
Quang Hoang

Reputation: 150785

IIUC, you want a map, and then it's matter of updating the correct location

maps = {'google':99999, 'microsoft': 88888, 'facebook': 66666}
to_replace = cw['name'].map(maps)

cw['values'] = np.where(cw['values'] == 0, to_replace, cw['values'])

Output:

        name  values
0     google   99999
1   facebook   66666
2  microsoft   88888
3     google       2
4   facebook      55
5  microsoft       7
6     google       5
7   facebook      80
8  microsoft      66

Upvotes: 2

Related Questions