Reputation: 13
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