如何根据另一列中的条件创建新列
在 pandas 中,如何基于 df
中的列 A
创建新列 B
,例如:
B=1< /code> if
A_(i+1)-A_(i) > 5
或A_(i) <= 10
B=0
如果A_(i+1)-A_(i) <= 5
但是,第一个 B_i
值始终为 1
示例:
A | B |
---|---|
5 | 1(第一个 B_i) |
12 | 1 |
14 | 0 |
22 | 1 |
20 | 0 |
33 | 1 |
In pandas, How can I create a new column B
based on a column A
in df
, such that:
B=1
ifA_(i+1)-A_(i) > 5
orA_(i) <= 10
B=0
ifA_(i+1)-A_(i) <= 5
However, the first B_i
value is always one
Example:
A | B |
---|---|
5 | 1 (the first B_i) |
12 | 1 |
14 | 0 |
22 | 1 |
20 | 0 |
33 | 1 |
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用
diff
< /a> 与您的值进行比较,并使用le
:注意。使用
le(5)
与反转比较可以使第一个值为 1输出:
更新的答案,只需将第二个条件与 OR (
|
) 结合起来:输出:与上面提供的数据相同
Use
diff
with a comparison to your value and convertion from boolean to int usingle
:NB. using a
le(5)
comparison with inversion enables to have 1 for the first valueoutput:
updated answer, simply combine a second condition with OR (
|
):output: same as above with the provided data
我对你的行计数有点困惑,因为如果我们根据条件
A_(i+1)-A_(i)< 计算
B_i
,我们应该在最后一行而不是第一行缺少值/code> (第一行应同时包含A_(i)
和A_(i+1)
,最后一行应缺少A_(i+1)值。
不管怎样,根据你的例子,我假设我们计算
B_(i+1)
。 稍微解释一下
:
df.loc[mask, columnname]=newvalue
允许我们在满足条件(掩码)时更新给定列中的值(df['A']-df['A'].shift(1))>5) + (df['A'].shift(1)<=10)
这里的每个条件都返回 True 或 False。如果我们将它们相加,如果其中任何一个为 True,则结果为 True(简单的 OR)。如果我们需要 AND 我们可以将条件相乘
I was little confused with your rows numeration bacause we should have missing value on last row instead of first if we calcule for
B_i
basing on conditionA_(i+1)-A_(i)
(first row should have both,A_(i)
andA_(i+1)
and last row should be missingA_(i+1)
value.Anyway,basing on your example i assumed that we calculate for
B_(i+1)
.That prints:
I am not sure if it is fastest way, but i guess it should be one of easier to understand.
Little explanation:
df.loc[mask, columnname]=newvalue
allows us to update value in given column if condition (mask) is fulfilled(df['A']-df['A'].shift(1))>5) + (df['A'].shift(1)<=10)
Each condition here returns True or False. If we added them the result is True if any of that is True (which is simply OR). In case we need AND we can multiply the conditions
使用
Series.diff
,在比较大于或等于后将1
的第一个缺失值替换为Series.ge
:Use
Series.diff
, replace first missing value for1
after compare for greater or equal bySeries.ge
: