pandas 地图熊猫中的 Lambda 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50303244/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 05:33:14  来源:igfitidea点击:

Lambda function inside map pandas

pythonpandaslambda

提问by Sharvari Gc

I am unable to comprehend the structure of this if else if else in the lambda function defined below. Particularly - the part :

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

if x != x

In this code :

在这段代码中:

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: I get that above code is formatting the ID value and returning a string without the decimal that could be there in the input.

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

采纳答案by jezrael

I think it is for working with NaNs, because:

我认为这是为了与NaNs一起工作,因为:

np.nan != np.nan

so if NaNs it return NaNs else processes strings.

所以如果NaNs 它返回NaNs else 处理字符串。

Sample:

样本:

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

If omit it it working, because converting to strings, but first value is not np.nan, but string nan:

如果省略它工作,因为转换为字符串,但第一个值不是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

If all values are strings with NaNs and remove converting to strings:

如果所有值都是带有NaNs 的字符串并删除转换为字符串:

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

AttributeError: 'float' object has no attribute 'rfind'

AttributeError: 'float' 对象没有属性 'rfind'

a = check['Id'].map(lambda x: x if x != x else ((x)[:(x).rfind('.0')] if (x).rfind('.0') != -1 else (x)))
print (a)
0     NaN
1    0909
2     023
3      09
Name: Id, dtype: object