PANDAS:根据多个if条件为特定列中的每一行分配一个值
我对 python 代码真的很陌生,并且在将一些类似问题的答案应用于我自己的案例时遇到了麻烦。请帮忙
所以我有一个包含 A 列和 B 列的数据框,有很多行都
包含负数和正数,我正在尝试使用以下条件创建一个新的 C 列
如果“第 1 行、A 列的值小于 0 ” & “第 1 行 B 列的值小于 0”,在“第 1 行 C 列”中返回 -100
Elif“第 1 行 A 列的值小于 0”& “第 1 行 B 列的值大于 0”,在“第 1 行 C 列”中返回 100
Elif“第 1 行 A 列的值大于 0”& “第 1 行 B 列的值小于 0”,在“第 1 行 C 列”中返回 100
否则:在 C 列中返回 (Column A.Value / Column B.Value)
非常感谢
I'm really new to python codes and having trouble with applying some of the answers for similar questions for my own case. Please help
So I have a dataframe with Column A and B, with numerous rows
Both contains negative and positive numbers, and I'm trying to make a new Column C with following conditions
If "Value of row 1, Column A is less than 0" & "Value of row 1, Column B is less than 0", return -100 in "row 1, Column C"
Elif "Value of row 1, Column A is less than 0" & "Value of row 1, Column B is greater than 0", return 100 in "row 1, Column C"
Elif "Value of row 1, Column A is greater than 0" & "Value of row 1, Column B is less than 0", return 100 in "row 1, Column C"
Else : return (Column A.Value / Column B.Value) in Column C
Thanks a lot
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为您正在寻找
np.select
:输出:
设置 MRE
I think you are looking for
np.select
:Output:
Setup a MRE
实现此目的的一种方法是定义具有所需逻辑的函数,然后将其传递到
沿轴 1 应用
函数(按行)。在这种情况下,该函数可能如下所示:然后我们可以生成一些示例数据用于测试目的:
最后,我们可以将我们的函数应用于示例数据:
One way you could do this is by defining a function with the desired logic and then passing it to the
apply
function along axis 1 (row-wise). In this case, that function might look like the following:We can then generate some sample data for testing purposes:
Finally, we can apply our function to the sample data:
输出:
如果有任何困惑,请告诉我!
OUTPUT:
Let me know if any confusion!