迭代地从字典中获取值

问题描述 投票:0回答:1

我有一个数据集,其中我知道有限数量的值,并且根据数据集中的其他值,我可以计算出后续值是什么。我可以用一个巨大的 if 函数来做到这一点,但我知道很久以前有人(在一份我无法再访问代码的工作中)向我展示了如何使用 lambda 和 apply 从字典中获取这些值。

我需要迭代地创建这个,因为虽然我可以计算出“Five_Zero”后的值,但在那之后我没有什么可继续的,需要先前的值来知道下一个。

这就是我的起始数据。
enter image description here

我需要使用 WonLost、OnServeCorrected 和 Score_Shift 的组合,并从可能的列表中获取该组合并返回一个值。这会返回一个错误。我不经常使用 lambda 并且不太理解它 - 我无法找到如何复制它的示例。

这是我收到的错误:
回溯(最近一次调用最后一次): 文件“mappingapplying.py”,第 30 行,位于 touch3["分数"][i] = touch3.var.apply(lambda x:x[d]) 属性错误:“函数”对象没有属性“应用”

缩进可能会关闭,因为代码没有完全复制。

import pandas as pd
import numpy as np


data = [[1, "Won", 1, "Five", "Zero"],
    [2, "Lost", 1, "",""],
    [3, "Lost", 1, "",""],
    [4, "Lost", 0, "Five","Zero"],
    [5, "Lost", 0, "",""],
    [6, "Won", 0, "",""]]
touch3 = pd.DataFrame(data, columns = ["Seconds", "WonLost", "OnServeCorrected", "S_Score", "R_Score"])
touch3["Score"] = touch3.S_Score + "_" + touch3.R_Score
touch3["Score_Shift"] = touch3.Score.shift(1)


d = [['Won_0_Five_Zero', "Five_Five"],
 ['Won_1_Five_Zero', "Three_Zero"],
 ['Lost_0_Five_Zero', "Three_Zero"],
 ['Lost_1_Five_Zero', "Five_Five"],
 ['Won_0_Five_Five', "Five_Three"], 
 ['Lost_0_Five_Five', "Three_Five"], 
 ['Won_1_Five_Five', "Three_Five"], 
 ['Lost_1_Five_Five', "Five_Three"]]

for i in range(len(touch3.Seconds)):
    if touch3.Score[i] not in (["Five_Zero", "Zero_Five"]):
       touch3["var"] = touch3.WonLost[i] + "_" + str(touch3.OnServeCorrected[i]) + "_" + touch3.Score_Shift[i]
    
       touch3["Score"][i] = touch3.var.apply(lambda x:x[d])
else:
    touch3.Score[i] = touch3.Score[i]

预期输出应该是: enter image description here

python pandas dictionary lambda apply
1个回答
0
投票

我不确定我理解是否正确,但您似乎想根据查找表

Score
匹配上一行的分数来填写列
d
中的值。

如果是这种情况,它可能非常简单,不需要 lambda 或 apply。只需将查找表更改为字典,迭代数据并使用前一行索引在每行上填写您的值即可。

d = {
    ('Won', 0, 'Five_Zero'): "Five_Five",
    ('Won', 1, 'Five_Zero'): "Three_Zero",
    ('Lost', 0, 'Five_Zero'): "Three_Zero",
    ('Lost', 1, 'Five_Zero'): "Five_Five",
    ('Won', 0, 'Five_Five'): "Five_Three",
    ('Lost', 0, 'Five_Five'): "Three_Five",
    ('Won', 1, 'Five_Five'): "Three_Five",
    ('Lost', 1, 'Five_Five'): "Five_Three",
}

for i in range(len(touch3.Seconds)):
    if touch3.Score[i] not in (["Five_Zero", "Zero_Five"]):
       touch3.Score[i] = d.get((touch3.WonLost[i], touch3.OnServeCorrected[i], touch3.Score[i-1]),"")

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.