【问题标题】:How to shorten my code with lambda statement in python?如何在 python 中使用 lambda 语句缩短我的代码?
【发布时间】:2017-10-24 23:13:30
【问题描述】:

如果可能的话,我很难用 lambda 缩短我的代码。 bp 是我的数据名称。

我的数据如下所示:

user label 

1        b    

2        b

3        c

我希望有

user   label  Y

1        b    1

2        b    1

3        c    0

这是我的代码:

counts = bp['Label'].value_counts()
def score_to_numeric(x):
    if counts['b'] > counts['s']: 
        if x == 'b':
            return 1
        else: 
            return 0
    else:
        if x =='b':
            return 0
        else:
            return 1
bp['Y'] = bp['Label'].apply(score_to_numeric) # apply above function to convert data 

这是一个函数将名为“标签”的列中的分类数据“b”或“s”转换为数字数据:0或1。counts = bp['Label'].value_counts()行计算列中“b”或“s”的数量'标签'。然后,在score_to_numeric 中,如果 'b' 的计数大于 's',则在名为 'Y' 的新列中将值 1 赋予 b,反之亦然。

我想将我的代码最多缩短为 3-4 行。我想也许使用 lambda 语句可以做到这一点,但我对 lambdas 还不够熟悉。

【问题讨论】:

  • 暂时忘记缩短代码。您在每次调用score_to_numeric时重新计算bd['Label'].value_counts()
  • 我认为向我们展示您的数据和大约 5-10 行的预期输出比展示一个函数并要求某人对其进行优化更有帮助。

标签: python pandas lambda


【解决方案1】:

由于TrueFalse 的计算结果分别为10,您可以简单地返回布尔表达式,转换为整数。

def score_to_numeric(x):
    return int((counts['b'] > counts['s']) == \
               (x == 'b'))

如果两个表达式具有相同的布尔值,则返回 1

【讨论】:

    【解决方案2】:

    我认为您不需要使用apply 方法。像这样简单的东西应该可以工作:

    value_counts = bp.Label.value_counts()
    bp.Label[bp.Label == 'b'] = 1 if value_counts['b'] > value_counts['s'] else 0
    bp.Label[bp.Label == 's'] = 1 if value_counts['s'] > value_counts['b'] else 0
    

    【讨论】:

      【解决方案3】:

      您可以执行以下操作

      counts = bp['Label'].value_counts()
      t = 1 if counts['b'] > counts['s'] else 0
      bp['Y'] = bp['Label'].apply(lambda x: t if x == 'b' else 1 - t)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-11-01
        • 2013-08-23
        • 2022-11-23
        • 1970-01-01
        • 1970-01-01
        • 2016-02-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多