Check for value in one column , take the adjacent value and apply function

67 views Asked by At

I have the following:

df1=pd.DataFrame([[1,10],[2,15],[3,16]], columns=["a","b"])

which result in:

    a   b
0   1   10
1   2   15
2   3   16

I want to create a third column "c" where the value in each row is a product of the value in column "b" form the same row multiplied by a number depending on the value in column "a". So for example

if value in "a" is 1 multiply 10 x 2,

if value in "a" is 2 multiply 15 x 5,

if value in "a" is 3 multiply 16 x 10.

In effect I want to achieve this:

    a   b   c
0   1   10  20
1   2   15  75
2   3   16  160

I have tried something with if and elif but don't get to the right solution. The dataframe is lengthy and the numbers 1, 2, 3 in column "a" appear in random order.

Thanks in advance.

2

There are 2 answers

0
Bhosale Shrikant On BEST ANSWER

Are you looking for something like this, I have extended your Dataframe, please check if it helps

df1=pd.DataFrame([[1,10],[2,15],[3,16],[3,11],[2,12],[1,16]], columns=["a","b"])
dict_prod = {1:2, 2:5, 3:10}
df1['c'] = df1['a'].map(dict_prod)*df1['b']




   a   b    c
0  1  10   20
1  2  15   75
2  3  16  160
3  3  11  110
4  2  12   60
5  1  16   32
0
Alireza Tajadod On

You should be able to just do

df1['c'] = df['a']*your_number * df['b']

or

df1['c'] = some_function(df['a']) * df['b']