如果在變數中選擇了名稱,我想創建一個新列,將 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)
我認為問題可能出在引數上?感謝有關該功能如何作業的解釋!:)
uj5u.com熱心網友回復:
使用Series.pipewith pass complete Series to function,還添加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
uj5u.com熱心網友回復:
你能試試這個嗎:
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))
uj5u.com熱心網友回復:
您可以使用字典查找所提供型別的標量,并在應用函式中使用該標量。這為您提供了所需的輸出:
import pandas as pd
df = pd.DataFrame([0.0, 1.0, 1.0, 2.0, 1.0], columns = ["pt_nm"])
r_type = "E"
types = {"E": 60, "S": 25, "EK": 45}
scalar = types[r_type]
df["pt_new"] = df["pt_nm"].apply(lambda x: x*scalar)
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/533414.html
標籤:熊猫
下一篇:熊貓:將列添加到另一列
