【问题标题】:Assigning a value to a column derived from another column in Pandas为从 Pandas 中的另一列派生的列分配值
【发布时间】:2020-05-25 08:44:19
【问题描述】:

我有一个包含三列文本的数据框。一列(column1)由 3 个唯一条目组成; “H”、“D”、“A”。

我想根据包含“H”、“D”或“A”的列中的条目创建一个新列,其中包含其他两列(column2 和 column3)中的条目。

我试着写一个函数:


def func(x):
   if x== "H":
        return column2
   elif x == "A":
        return column3
   else:
        return "D"

然后我尝试使用.apply() 函数:

df["new_col"] = df["column1"].apply(func)

但这不起作用,因为它无法识别第 2 列和第 3 列。如何访问函数内第 2 列和第 3 列的条目?

【问题讨论】:

标签: python python-3.x pandas


【解决方案1】:

您可以将整行发送到函数并访问它的列:

def func(x):
   if x["column1"]== "H":
        return x["column2"]
   elif x["column1"] == "A":
        return x["column3"]
   else:
        return "D"

df["new_col"] = df.apply(lambda x: func(x), axis=1)

【讨论】:

    【解决方案2】:

    不用.apply可以使用np.select根据条件选择元素:

    考虑示例数据框:

    df = pd.DataFrame({
        'column1': ['H', 'D', 'A', 'H', 'A'],
        'column2': [1, 2, 3, 4, 5],
        'column3': [10, 20, 30, 40, 50]
    })
    

    用途:

    import numpy as np
    
    conditions = [
        df['column1'].eq('H'), 
        df['column1'].eq('A')
    ]
    
    choices = [
        df['column2'], 
        df['column3']]
    
    df['new_col'] = np.select(
        conditions, choices, default='D')
    

    结果:

    # print(df)
    
      column1  column2  column3 new_col
    0       H        1       10       1
    1       D        2       20       D
    2       A        3       30      30
    3       H        4       40       4
    4       A        5       50      50
    

    【讨论】:

      【解决方案3】:

      在这里,我正在检索具有所需条件的行并更改 column4 中的相应行。我们可以在pandas dataframe 中使用iloc 来实现这一点。

      import pandas as pd
      
      d = {"column1":["H","D","A","D", "H", "H", "A"],"column2":[1,2,3,4,5,6,7],"column3":[12,23,34,45,56,67,87]}
      df = pd.DataFrame(d)
      df["column4"] = None
      
      df.iloc[list(df[df["column1"] == "H"].index), 3] = df[df["column1"] == "H"]["column2"]
      df.iloc[list(df[df["column1"] == "A"].index), 3] = df[df["column1"] == "A"]["column3"]
      df.iloc[list(df[df["column4"].isnull()].index), 3] = "D"
      

      上述处理的输出如下,

      print(df)
      
        column1  column2  column3 column4
      0       H        1       12       1
      1       D        2       23       D
      2       A        3       34      34
      3       D        4       45       D
      4       H        5       56       5
      5       H        6       67       6
      6       A        7       87      87
      

      【讨论】:

        【解决方案4】:

        你可以使用 np.select() 函数

        import numpy as np
        df['column4'] = np.select([df.column1=='H',df.column1=='A'],
                                   [df.column2,df.column3], default = 'D')
        

        这是一种 case when 语句,其中第一个参数是要比较的值,第二个参数是对应于该比较的输出。默认是 'else' 语句的关键字参数。

        【讨论】:

          【解决方案5】:

          根据我对您的查询的理解,我将以您的为例进行说明。

          考虑这个数据框:

          d = {
              "col1": ["H","D","A","H","D","A"],
              "col2": [172,180,190,156,176,182],
              "col3":[80,75,53,80,100,92]
          }
          
          df = pd.DataFrame(d)
          

          df

            col1  col2    col3
          0   H   172     80
          1   D   180     75
          2   A   190     53
          3   H   156     80
          4   D   176     100
          5   A   182     92
          

          apply 接受一个 Series 对象,并使用与您传递的数据帧相关的适当索引来访问列。在调用 apply 时,必须传递 axis=1 ,因为您需要每行的列值。最后将返回的系列附加到原始数据框中。

          def func(df):
              if df[0] == 'H':
                  return df[1]
              elif df[0] == 'A':
                  return df[2]
              else:
                  return "D"
          
          df['col4'] = df.apply(func, axis=1)
          

          df

            col1  col2    col3    col4
          0   H   172     80      172
          1   D   180     75      D
          2   A   190     53      53
          3   H   156     80      156
          4   D   176     100     D
          5   A   182     92      92
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2018-09-09
            • 1970-01-01
            • 2021-09-02
            • 2014-02-19
            • 2019-02-12
            相关资源
            最近更新 更多