【问题标题】:function that takes one column value and returns another column value接受一列值并返回另一列值的函数
【发布时间】:2017-08-18 12:29:35
【问题描述】:

抱歉,如果重复,请告诉我,我很乐意删除。

我的数据集:

Index     Col 1      Col 2

0         1       4, 5, 6   
1         2       7, 8, 9
2         3       10, 11, 12   
3         4       13, 14, 15

我正在尝试创建一个函数,该函数将特定的第 1 列值作为其输入,并输出第 1 列值及其对应的第 2 列值。

例如,如果我在第 1 列等于 3 时使用该函数,该函数将返回一个包含 4 个值的列表:3、10、11、12

非常感谢

【问题讨论】:

    标签: python function pandas


    【解决方案1】:
    def f(a):
        return df.loc[df['Col 1'] == a, 'Col 2'].item()
    

    但如果需要更通用的:

    print (df)
       Col 1       Col 2
    0      1     4, 5, 6
    1      1     7, 8, 9
    2      3  10, 11, 12
    3      4  13, 14, 15
    
    def f(a):
        a = df.loc[df['Col 1'] == a, 'Col 2']
        #for no match
        if a.empty:
            return 'no match'
        #for multiple match
        elif len(a) > 1:
            return a
        else:
        #for match one value only
            return a.item()
    
    print (f(1))
    0    4, 5, 6
    1    7, 8, 9
    Name: Col 2, dtype: object
    
    print (f(3))
    10, 11, 12
    
    print (f(6))
    no match
    

    【讨论】:

      【解决方案2】:

      只是一个简单的函数:

      def getColumn(col1):
          beg = 1+3*col1
          return [col1] + list(range(beg, beg+3))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-06-12
        • 2020-03-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-16
        相关资源
        最近更新 更多