bartblons
bartblons

Reputation: 125

Python/Pandas - How to assign value for each row which depends on cells values

I have data frame like this:

  x  y   z
0 AA BB  CC
1 BB NaN CC
2 BB AA  NaN

and dictionary:

d = {'AA': 1, 'BB': 2, 'CC': 3}

I want to compare values from each cell with values from dictionary and add another new column with sum of these values for each row. In result I need something like this:

  x  y   z   sum
0 AA BB  CC   6
1 BB NaN CC   5
2 BB AA  NaN  3

I need the most efficient solution, any ideas?

Upvotes: 2

Views: 87

Answers (1)

jezrael
jezrael

Reputation: 862761

Use replace with sum per row by axis=1, last convert to int by astype:

print (df.replace(d))
   x    y    z
0  1  2.0  3.0
1  2  NaN  3.0
2  2  1.0  NaN

df['sum'] = df.replace(d).sum(axis=1).astype(int)
print (df)
    x    y    z  sum
0  AA   BB   CC    6
1  BB  NaN   CC    5
2  BB   AA  NaN    3

Upvotes: 4

Related Questions