0

I am trying to create multiple new dataframe columns using a function. When I run the simple code below, however, I get the error, "KeyError: "['AdjTime1' 'AdjTime2'] not in index."

How can I correct this to add the two new columns ('AdjTime1' & 'AdjTime2') to my dataframe?

Thanks!

import pandas as pd

df = pd.DataFrame({'Runner':['Wade','Brian','Jason'],'Time':[80,75,98]})

def adj_speed(row):
    adjusted_speed1 = row['Time']*1.5
    adjusted_speed2 = row['Time']*2.0

    return adjusted_speed1, adjusted_speed2

df[['AdjTime1','AdjTime2']] = df.apply(adj_speed,axis=1)
3
  • There's no need for apply here; simplicity wins: df['AdjTime1'] = df.Time*1.5 Then write another line for the second. Perhaps with many adjusted values you could make this more functional, but there's really no need for 2 lines with simple multiplication. Commented Apr 29, 2019 at 17:04
  • Thanks for pointing out possible duplicate, Sheldore, but I was unable to draw a parallel to my example which uses .apply and a function. I have also tried to use packing by separating the two new columns but then get a 'too many values to unpack' error. Any additional help would be appreciated. Thanks! Commented Apr 29, 2019 at 17:06
  • Thanks, ALollz. I should have clarified. My example above is drastically simplified. In my actual version I'm trying to create about 10 new columns that all rely on somewhat similar calculations which is why I want to create them using a single function. Commented Apr 29, 2019 at 17:09

1 Answer 1

1

Just do something like (assuming you have a list values you want to multiply Time on):

l=[1.5,2.0]
for e,i in enumerate(l):
    df['AdjTime'+str(e+1)]=df.Time*i
print(df)

  Runner  Time  AdjTime1  AdjTime2
0   Wade    80     120.0     160.0
1  Brian    75     112.5     150.0
2  Jason    98     147.0     196.0
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, Anky. This makes sense for instances in which the calculations don't change from column to column. Is there a way to use .apply in more complex examples? My actual example is more complex than the one above (e.g., adds 10 new columns derived from different calculations, not simply the same calculation with different constants). I should be able to use .apply for this but am running into the key error issue above for some reason. Appreciate any insight you might have into this error. Thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.