Write a python function to multiply integers to columns in a dataframe

Viewed 47

The below table having 1000 rows but here let's consider 3 rows:

Date B C
2022-07-24 12 1234
2021-02-01 13 6789
2020-04-30 14 4324

I want to write a python function where 2 is multiplied in column B, and 3 is multiplied in columns C.

3 Answers

Dont use loops, because possible vectorize multiple with dictionary:

d = {'B':2, 'C':3}
df[list(d.keys())] *= d
print (df)
         Date   B      C
0  2022-07-24  24   3702
1  2021-02-01  26  20367
2  2020-04-30  28  12972

If need function with argument DataFrame and dictionary use:

def f(data, di):
    data[list(di.keys())] *= di
    return data

d = {'B':2, 'C':3}
df = f(df, d)
print (df)
         Date   B      C
0  2022-07-24  24   3702
1  2021-02-01  26  20367
2  2020-04-30  28  12972

You can simply do df[column] *= number

values = {'B': 2, 'C': 3}
for k, v in values.items():
    df[k] *= v
print(df)

Or one liner

values = {'B': 2, 'C': 3}
df[list(values.keys())] *= values.values()

Output

         Date   B      C
0  2022-07-24  24   3702
1  2021-02-01  26  20367
2  2020-04-30  28  12972

Try this, this might not be the best code but it will work

#data is the dataframe name     
for i in range(len(data)):
        data.loc[i,"b"] = 2*data.loc[i,"b"]
        data.loc[i,"c"] = 3*data.loc[i,"c"]
Related