【问题标题】:How to use lambda in DataFrame.assign to solve the ambiguity of truth value of Series?如何在DataFrame.assign中使用lambda解决Series真值的歧义?
【发布时间】:2017-09-27 22:56:58
【问题描述】:

我使用以下代码创建了一个数据框:

import pandas as pd
from numpy import exp
import random

moves = [(1, 2), (1, 3), (1, 4), (2, 1), (2, 3), (2, 4)]

data = {'moves': list(map(lambda i: moves[i] if divmod(i, len(moves))[0] != 1 else moves[divmod(i, len(moves))[1]],
                       [i for i in range(2 * len(moves))])),
    'player': list(map(lambda i: 1 if i >= len(moves) else 2,
                       [i for i in range(2 * len(moves))])),
    'wins': [random.randint(0, 2) for i in range(2 * len(moves))],
    'playout_number': [random.randint(0,1) for i in range(2 * len(moves))]
    }
frame = pd.DataFrame(data)

我想使用下面的代码向数据框添加另一列:

total = sum(map(lambda a, b: exp(a/b) if b != 0 else 0, frame['wins'], frame['playout_number']))
frame = frame.assign(weight=lambda a: exp(a.wins/a.playout_number) / total if a.playout_number != 0 else 0)

当我使用上面的代码时,我得到了这个错误:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

我了解错误的原因,但我不知道如何重写 lambda 函数来处理错误。我想要一个函数,如果 frame['playout'] 不为零,则返回 exp(frame['wins'] / frame['playout_number']),如果 playout_number 为零,则返回零。 你们能帮我解决这个问题吗?

【问题讨论】:

    标签: pandas lambda python-3.5


    【解决方案1】:
    #use apply to create the new weight column.
    frame['weight'] = frame.apply(lambda x: exp(x['wins'] / x['playout_number']) / total if x['playout_number'] !=0 else 0, axis=1)
    
    frame
    Out[117]: 
         moves  player  playout_number  wins    weight
    0   (1, 2)       2               0     0  0.000000
    1   (1, 3)       2               0     1  0.000000
    2   (1, 4)       2               1     0  0.070885
    3   (2, 1)       2               1     0  0.070885
    4   (2, 3)       2               0     1  0.000000
    5   (2, 4)       2               1     2  0.523774
    6   (1, 2)       1               1     1  0.192686
    7   (1, 3)       1               0     1  0.000000
    8   (1, 4)       1               0     0  0.000000
    9   (2, 1)       1               1     0  0.070885
    10  (2, 3)       1               1     0  0.070885
    11  (2, 4)       1               0     2  0.000000
    

    【讨论】:

    • 感谢您简洁明了的回答。做得好!你能赞成这个问题吗?谢谢!
    • assign 不起作用但 apply 起作用的原因是什么?
    猜你喜欢
    • 1970-01-01
    • 2011-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-03
    • 2018-10-24
    相关资源
    最近更新 更多