简体   繁体   English

根据另一列的当前行和同一列的上一行递增一列的值

[英]Increment values of a column based on the current row of another column and the previous row of the same column

I want to create a column with multiple conditions wherein if the column ' Batt' contains 'Discharge' and the previous row contains 'none' then increment the value by 1 starting with 0 if not then return the same value without any increments.我想创建一个具有多个条件的列,其中如果列“Batt”包含“Discharge”并且前一行包含“none”,则将该值从 0 开始递增 1,如果不是,则返回相同的值而无需任何递增。

 Batt Disch            Continous Cycle count   
       None                0   
       None                0   
       Discharge           1  
       Discharge           1  
       None                1   
       Discharge           2  
       Discharge           2

IIUC, You can create a boolean mask and then use Series.cumsum to get the result: IIUC,您可以创建一个boolean mask ,然后使用Series.cumsum得到结果:

df['Continous Cycle count'] = (
    (df['Batt Disch'].eq('Discharge') &
     df['Batt Disch'].shift().eq('None'))
    .cumsum()
)

Result:结果:

  Batt Disch  Continous Cycle count
0       None                      0
1       None                      0
2  Discharge                      1
3  Discharge                      1
4       None                      1
5  Discharge                      2
6  Discharge                      2

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如果同一行的另一列中存在空值,则将列值与前一行合并 - concat column values with previous row if there is null in another column in same row 根据上一行另一列中的值修改1列中的值 - Modify values in 1 column based on the value in another column in the previous row 如果从另一列的同一行看到新值,则重复前一行的值然后求和,然后在 Python 中重复当前行 - repeat previous row's value then sum if new values are seen from the same row of another column, then repeat current row in Python 根据Pandas中第二列的条件,用另一行的同一列的值填充特定行的列中的值 - Fill values in a column of a particular row with the value of same column from another row based on a condition on second column in Pandas 根据上一行更改 timedelta 列的值 - Change values of a timedelta column based on the previous row Pandas - 添加一列,其值根据当前行和前一行中的另一列值计算得出 - Pandas - add a column with value computed based on another column value in current and previous row 根据上一个行值创建一个新列并删除当前行 - Create a new column based on previous row value and delete the current row 根据同一行另一列中的值创建一个数据框列,然后返回一行 - Create a dataframe column based on values in another column on the same row and a row back 根据此行另一列与上一行的差确定一个值 - Determine a value based on the difference between another column of this row and the previous row 如何根据当前行值和上一行值的两个条件分配列值? - How to assign values of a column based on two conditions for current and previous row values?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM