尝试使用 Pandas Lambda 更改行值时出现语法错误

时间:2021-03-11 23:46:17

标签: python pandas lambda syntax-error

我遇到了以下语法错误:

df['storetype'] = df.apply(lambda x: "TP" if x.storetype == "MT", axis=1)

我正在尝试检查 storetype 列中的值是否为“MT”,如果是,则将其更改为“TP”。 不精通 lambda 函数,因此不胜感激。

1 个答案:

答案 0 :(得分:0)

如评论中所述,此三元形式需要 else。如果你不想在 else 的情况下做任何事情,你可以用 else x.storetype 返回原始值:

df['storetype'] = df.apply(lambda x: "TP" if x.storetype == "MT" else x.storetype, axis=1)