简体   繁体   English

在一定条件下填充pandas数据框列

[英]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 ,将False0

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.

相关问题 在数据框熊猫的特定行中添加一列 - Adding a column to certain row in a data frame pandas 当且仅当其他列满足特定条件时,Pandas 数据框会计算特定值在列中出现的次数 - Pandas Data frame counting how many times certain value appears in column if and only if other columns meet certain condition 如果满足基于同一数据帧中其他2列的行值的条件,则在数据帧的列行中填充值 - Filling values in rows of column in a data frame, if condition based on 2 other columns row values in the same data frame is met 获取在pandas数据框中满足特定条件的行(字符串)的百分比 - Get percentage of rows (strings) that fulfil a certain condition in a pandas data frame 根据 pandas 数据框中另一列中的条件对一列求和 - Summing a column based on a condition in another column in a pandas data frame 如何检查数据框中的列是否等于Pandas中的某种数据类型? - How to check of a column in a data frame equals a certain data type in Pandas? 如果满足特定条件,则在熊猫数据框中添加列值 - Add column value in panda data frame if certain condition is met 如何在另一个列值中具有条件的子组中筛选熊猫数据帧 - How to filter pandas data frame by subgroups with a condition in another column value Pandas 数据框根据条件替换列中的值 - Pandas data frame replace values in column based on condition 数据框中的 pandas-if 条件获取列名 - pandas-if condition in data frame to get column name
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM