gpt4 book ai didi

python - 将 lambda 函数应用于具有 NaN 值的数据框?

转载 作者:行者123 更新时间:2023-12-05 00:46:06 25 4
gpt4 key购买 nike

我正在尝试执行在具有保持一致变量的行之间更改的计算。当一行有不完整的数据时,如何使用这个 lambda 函数?

跟进这个问题:Create a new column based on calculations that change between rows?

#example
import pandas as pd
import numpy as np

conversion = [["a",5],["b",1],["c",10]]
conversion_table = pd.DataFrame(conversion,columns=['Variable','Cost'])

data1 = [[1,"2*a+b"],[2,"c"],[3,"2*c"],[4, np.NaN]]
to_solve = pd.DataFrame(data1,columns=['Day','Q1'])

#Desired dataframe:

desired = [[1,11],[2,10],[3,20]]
desired_table=pd.DataFrame(desired,columns=['Day','desired output'])

#Using lambda to map values does not work when NaN is present.

#Map values
mapping = dict(zip(conversion_table['Variable'], conversion_table['Cost']))

desired_table["solved"]=to_solve['Q1'].map(lambda x: eval(''.join([str(mapping[i]) if i.isalpha() else str(i) for i in x])))

当我的列不包含 NaN 值时,此代码有效,但当我的数据不完整时,我需要此代码。我收到以下错误:'float' 对象不可迭代。我只想将 NaN 值留在原处并填写其余部分。

最佳答案

desired_table["solved"]=to_solve['Q1'].map(lambda x: ..., na_action='ignore')

应该做你想做的。

In [6]: to_solve['Q1'].map(lambda x: eval(''.join([str(mapping[i]) if i.isalpha() else str(i) for i in x])), na_action='ignore')                                                                            
Out[6]:
0 11.0
1 10.0
2 20.0
3 NaN
Name: Q1, dtype: float64

关于python - 将 lambda 函数应用于具有 NaN 值的数据框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61893421/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com