【问题标题】:Function that creates new column based on filtering input selection基于过滤输入选择创建新列的函数
【发布时间】:2022-11-14 19:22:28
【问题描述】:

如果在变量中选择了名称,我想创建一个将 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)

我认为问题可能出在争论中?感谢您对该功能如何工作的解释! :)

【问题讨论】:

    标签: pandas


    【解决方案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
    

    【讨论】:

    • 谢谢,这可行,但意味着在应用管道时手动将字母“E”更改为“S”。当我在变量中将 E 更改为 S 时,它并没有自动更改,但是当我在管道中更改它时
    • @Hansson - 当然,因为将它传递给函数。
    • 被我耍到了。它现在正在工作。谢谢!
    【解决方案2】:

    你能试试这个:

    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))
    

    【讨论】:

      【解决方案3】:

      您可以使用字典来查找提供的类型的标量,并在 apply 函数中使用该标量。这将为您提供所需的输出:

      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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-10-04
        • 2016-02-14
        相关资源
        最近更新 更多