我正在尝试使用一个函数创建多个新的数据框列。但是,当我运行下面的简单代码时,出现错误“ KeyError:“ ['AdjTime1''AdjTime2']不在索引中。”
如何纠正此问题以将两个新列(“ AdjTime1”和“ AdjTime2”)添加到我的数据框中?
谢谢!
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)
答案 0 :(得分:1)
要做类似的事情(假设您有一个列表值要乘以Time
)
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