mercredi 29 janvier 2020

Using if and elif the right way

I have the following dataframe:

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

which results in:

    a
0   1
1   2
2   3

I want to create column b where each value is a multiple (x2,x3,x4) of the respective number in column a. Desired output is like that:

    a   b
0   1   2
1   2   6
2   3   12

I try the following statement but obviously the behavior is not as expected.

for num in df1["a"]:
    if a == 1:
        df1["b"]=df1["a"]*2
    elif a == 2:
        df1["b"]=df1["a"]*3
    elif a ==3:
        df1["b"]=df1["a"]*4

when I run the above I get:

    a   b
0   1   2
1   2   4
2   3   6

help much appreciated

Aucun commentaire:

Enregistrer un commentaire