Ramsey
Ramsey

Reputation: 365

Iterate over multiple columns in Pandas dataframe and create new columns

I have a dataframe with measure columns SalesMonth1 -- SalesMonth12 and another columns Index and price.

I am trying to do the following but it does not work. Could you please suggest a better way?

For i in range(12):
     DF['Newcol'] = np.where(DF["Index"] >0,
                             DF["SalesMonth[i]"] * DF["price"],
                             DF["SalesMonth[i]"])

Upvotes: 2

Views: 1966

Answers (2)

cs95
cs95

Reputation: 402493

Use loc for in-place assignment (very cheap, fast).

m = df["Index"] > 0
df.loc[m, 'SalesMonth1':'SalesMonth12'] *= df.loc[m, 'Price']

Upvotes: 1

jpp
jpp

Reputation: 164673

You are close. Try this:

for i in range(12):
    df['newcol'+str(i)] = np.where(df['Index'] > 0,
                                   df['SalesMonth'+str(i)] * df['price'],
                                   df['SalesMonth'+str(i)])

The trick is to convert your integers to strings via str.

Upvotes: 1

Related Questions