pandas 在 Python 中映射 if 语句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29247718/
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
Map an if statement in Python
提问by BrandonM
I'm trying to map the following function over a pandas dataframe (basically a list) in python 2.7:
我正在尝试将以下函数映射到 python 2.7 中的 Pandas 数据框(基本上是一个列表)上:
df["Cherbourg"] = df["Embarked"].map(lambda x: if (x == "C") 1 else 0)
But python errors saying using a lambda function like this is a syntax error. Is there some way to map an if statement like this in python?
但是 python 错误说使用这样的 lambda 函数是一个语法错误。有没有办法在python中映射这样的if语句?
回答by pnv
Try
尝试
lambda x: 1 if x == "C" else 0
possible duplicate of Is there a way to perform "if" in python's lambda
可能重复的 是有没有办法在Python的lambda“如果”执行
Example :
例子 :
map(lambda x: True if x % 2 == 0 else False, range(1, 11))
result will be - [False, True, False, True, False, True, False, True, False, True]
结果将是 - [假,真,假,真,假,真,假,真,假,真]
回答by EdChum
It will be simpler to just do this:
这样做会更简单:
df["Cherbourg"] = (df["Embarked"] == "C").astype('int)

