Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/299.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 图中的Lambda函数_Python_Pandas_Lambda - Fatal编程技术网

Python 图中的Lambda函数

Python 图中的Lambda函数,python,pandas,lambda,Python,Pandas,Lambda,我无法理解下面定义的lambda函数中if-else-if-else的结构。特别是——部分: if x != x 在此代码中: check['Id'].map(lambda x: x if x != x else (str(x)[:str(x).rfind('.0')] if str(x).rfind('.0') != -1 else str(x)) PS:我知道上面的代码正在格式化ID值,并返回一个没有小数点的字符串,该字符串可能存在于输入中 我认为这是为了与NaNs合作,因为: np.n

我无法理解下面定义的lambda函数中if-else-if-else的结构。特别是——部分:

if x != x
在此代码中:

check['Id'].map(lambda x: x if x != x else (str(x)[:str(x).rfind('.0')] if str(x).rfind('.0') != -1 else str(x))

PS:我知道上面的代码正在格式化ID值,并返回一个没有小数点的字符串,该字符串可能存在于输入中

我认为这是为了与
NaN
s合作,因为:

np.nan != np.nan
因此,如果
NaN
s,它将返回
NaN
s,否则将处理字符串

样本:

check = pd.DataFrame({'Id':[np.nan, '0909.0', '023', '09.06']})

a = check['Id'].map(lambda x: x if x != x else (str(x)[:str(x).rfind('.0')] if str(x).rfind('.0') != -1 else str(x)))
print (a)
0     NaN
1    0909
2     023
3      09
Name: Id, dtype: object
如果忽略它,它将起作用,因为转换为字符串,但第一个值不是
np.nan
,而是字符串
nan

a = check['Id'].map(lambda x: (str(x)[:str(x).rfind('.0')] if str(x).rfind('.0') != -1 else str(x)))
print (a)
0     nan
1    0909
2     023
3      09
Name: Id, dtype: object
如果所有值都是带
NaN
s的字符串,请删除转换为字符串:

a = check['Id'].map(lambda x: ((x)[:(x).rfind('.0')] if (x).rfind('.0') != -1 else (x)))
print (a)
AttributeError:“float”对象没有属性“rfind”


正如jezrael发布的,它只是过滤掉
NaN
值。 不过,这并不是最通俗易懂的写作方式

如果通过lambda函数运行
NaN
时遇到问题,则应添加参数
na_action='ignore'
,以便映射函数忽略NaN并避免错误

所以你应该试试:

map(lambda x:      your_function_here      , na_action='ignore')
而不是:

map(lambda x: x if x != x else ( your_function_here ) )
您应该期望在两个代码中得到相同的结果,但第一个代码更具python风格和可读性,因为它清楚地表明我们忽略了Na值

map(lambda x: x if x != x else ( your_function_here ) )