使用 Lambda 函数 Pandas 设置列值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44752968/
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 03:52:45  来源:igfitidea点击:

Using Lambda Function Pandas to Set Column Values

pythonpandasdataframelambda

提问by MarcCharbo

Could anyone suggest a way answer the same question (see link) but by using lambda function: Update a dataframe in pandas while iterating row by row

任何人都可以提出一种方法来回答相同的问题(见链接),但使用 lambda 函数: 在逐行迭代的同时更新 Pandas 中的数据帧

回答by piRSquared

You'll want to use applywith the parameter axis=1to insure the function passed to applyis applied to each row.

您需要apply与参数一起使用axis=1以确保将传递给的函数apply应用于每一行。

The referenced question has an answer that uses this loop.

引用的问题有一个使用此循环的答案。

for i, row in df.iterrows():
    if <something>:
        row['ifor'] = x
    else:
        row['ifor'] = y

    df.ix[i]['ifor'] = x

To use a lambda with the same logic

使用具有相同逻辑的 lambda

df['ifor'] = df.apply(lambda row: x if something else y, axis=1)