[英]Filling pandas data frame column under certain condition
I have the following data frame with the index as date time stamps and I would like to create an extra column when p2>p1 set the p3('new column') to 1 otherwise set it to 0. I do not want to have to loop. 我有以下数据框,索引作为日期时间戳,我想创建一个额外的列,当p2> p1将p3('新列')设置为1,否则将其设置为0.我不想要环。 I tried to use mask and where but i DID NOT GET IT RIGHT:
我试图使用面具,但我没有得到它的权利:
p1 p2
2018-01-15 07:15:00 -1.0 0.4
2018-01-15 07:30:00 -1.0 0.4
2018-01-15 07:45:00 -3.0 0.4
2018-01-15 08:00:00 -3.0 0.3
2018-01-15 08:15:00 -2.0 0.3
2018-01-15 08:30:00 -2.0 0.3
2018-01-15 08:45:00 -2.0 0.2
2018-01-15 09:00:00 -2.7 0.1
2018-01-15 09:15:00 -2.7 0.0
2018-01-15 09:30:00 -2.7 0.0
2018-01-15 09:45:00 -3.7 0.3
2018-01-15 10:00:00 -3.0 0.3
2018-01-15 10:15:00 -2.0 0.3
2018-01-15 10:30:00 -1.0 0.3
You can convert boolean mask to integers, True
to 1
and False
to 0
: 您可以将布尔掩码转换为整数,将
True
转换为1
,将False
为0
:
df['p3'] = (df.p2>df.p1).astype(int)
print (df)
p1 p2 p3
2018-01-15 07:15:00 1.0 0.4 0 <-changed first value in p1
2018-01-15 07:30:00 -1.0 0.4 1
2018-01-15 07:45:00 -3.0 0.4 1
2018-01-15 08:00:00 -3.0 0.3 1
2018-01-15 08:15:00 -2.0 0.3 1
2018-01-15 08:30:00 -2.0 0.3 1
2018-01-15 08:45:00 -2.0 0.2 1
2018-01-15 09:00:00 -2.7 0.1 1
2018-01-15 09:15:00 -2.7 0.0 1
2018-01-15 09:30:00 -2.7 0.0 1
2018-01-15 09:45:00 -3.7 0.3 1
2018-01-15 10:00:00 -3.0 0.3 1
2018-01-15 10:15:00 -2.0 0.3 1
2018-01-15 10:30:00 -1.0 0.3 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.