我想创建一个新列,如果在变量中选择了名称,则将pt_nm的列值与预定义值相乘:
df["pt_nm"]看起来像这样
0 0.0
1 1.0
2 1.0
3 2.0
4 1.0
dtype: float64
可供选择的变量如下:
types = ["E", "S", "EK"]
r_type = "E"
pt_s= 25
pt_e = 60
pt_ek = 45
我尝试了下面的操作,但没有成功:
def race (r_type, pt_nm):
if r_type == "E":
pt_nm* pt_e
elif r_type == "S":
pt_nm* pt_s
else:
pt_nm* pt_ek
df["pt_new"] = df["pt_nm"].apply(race, axis = 1)
我想问题可能出在参数上?对该函数如何工作的解释是赞赏的!:)
使用通过完整系列的Series.pipe
功能,还可以添加return
,如:
types = ["E", "S", "EK"]
r_type = "E"
pt_s= 25
pt_e = 60
pt_ek = 45
#swapped arguments
def race (pt_nm, r_type):
if r_type == "E":
return pt_nm* pt_e
elif r_type == "S":
return pt_nm* pt_s
else:
return pt_nm* pt_ek
df["pt_new"] = df["pt_nm"].pipe(race, r_type)
#alternatuive
#df["pt_new"] = race(df["pt_nm"], r_type)
print (df)
pt_nm pt_new
0 0.0 0.0
1 1.0 60.0
2 1.0 60.0
3 2.0 120.0
4 1.0 60.0
你可以试试这个吗:
def race (r_type, pt_nm):
if r_type == "E":
return pt_nm* pt_e
elif r_type == "S":
return pt_nm* pt_s
else:
return pt_nm* pt_ek
df["pt_new"] = df["pt_nm"].apply(lambda x: race(x,r_type=r_type))