使用 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
Using Lambda Function Pandas to Set Column Values
提问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 apply
with the parameter axis=1
to insure the function passed to apply
is 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)