1

I need to create some new columns based on the value of a dataframe filed and a look up dataframe with some rates.

Having df1 as

    zone    hh      hhind
0   14      112.0   3.4
1   15      5.0     4.4
2   16      0.0     1.0

and a look_up df as

    ind     per1    per2    per3    per4
0   1.0     1.000   0.000   0.000   0.000
24  3.4     0.145   0.233   0.165   0.457
34  4.4     0.060   0.114   0.075   0.751   

how can i update df1.hh1 by multiplying the look_up.per1 based on df1.hhind and lookup.ind

    zone    hh      hhind  hh1
 0  14      112.0   3.4    16.240
 1  15      5.0     4.4    0.300
 2  16      0.0     1.0    0.000

at the moment im getting the result by merging the tables and the doing the arithmetic.

r = pd.merge(df1, look_up, left_on="hhind", right_on="ind")
r["hh1"] = r.hh *r.per1

i'd like to know if there is a more straight way to accomplish this by not merging the tables?

2 Answers 2

1

You could first set hhind and ind as the index axis of df1 and look_up dataframes respectively. Then, multiply corresponding elements in hh and per1 element-wise.

Map these results to the column hhind and assign these to a new column later as shown:

mapper = df1.set_index('hhind')['hh'].mul(look_up.set_index('ind')['per1'])
df1.assign(hh1=df1['hhind'].map(mapper))

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

1

another solution:

df1['hh1'] = (df1['hhind'].map(lambda x: look_up[look_up["ind"]==x]["per1"])) * df1['hh']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.