Roberto Ash
Roberto Ash

Reputation: 13

Selecting variable based on DataFrame column name

I've just gotten started with Python so I am sure this must be pretty straight-forward but I still cannot find the answer myself.

I am trying to apply a different operation to columns within a DataFrame based on the column name. Here's a very simple example:

import pandas as pd

A = 2
B = 4

df = pd.DataFrame([[1, 2],[3, 4]], columns=['A', 'B'])
columns = list(df)

Now, what I would like to do is use a for loop to iterate over each column and use the column name to figure out which variable to reference. Like this:

for item in columns:
    df[item] = df[item] * item

I other words I would like column A to be multiplied times 2 and column B by 4. The issue is that I don't know how to "convert" the column name into a variable reference.

Upvotes: 1

Views: 754

Answers (1)

jezrael
jezrael

Reputation: 862611

Create dictionary by all possible columns values and then multiple columns maped by Index.map:

A = 2
B = 4

d = {'A':A, 'B':B}

df = pd.DataFrame([[1, 2],[3, 4]], columns=['A', 'B'])

df = df.mul(df.columns.map(d))
print (df)
   A   B
0  2   8
1  6  16

Upvotes: 1

Related Questions