简体   繁体   中英

Replace the current row with data with the previous row if the value of a certain column in the current row is 1

I have a pandas dataframe and want to replace the current row with data with the previous row if the value of a certain column in the current row is 1, but had no success yet. Any help appreciated.

It could be done like this:

#B is the column that lets you know if the row should change or not
for i in range(1, len(df)):
    if df.loc[i, 'B'] == 1:
        df.loc[i, :] = df.loc[i-1, :]

This can be done just using the shift operator and assigning. If b is the index we want to condition on, then we create a condition based on b first

import pandas as pd

df = pd.DataFrame({
    'a':[1, 2, 3, 4, 5, 6],
    'b':[0, 1, 1, 0, 0, 1],
    'c':[7, 8, 9, 0, 1, 2]}
)

# this is our condition (which row we're changing)
index_to_change = df['b'] == 1

# this is a list of columns we want to change
cols_to_change = ['a', 'c']

df.loc[index_to_change, cols_to_change] = df[cols_to_change].shift(1).loc[index_to_change]

Output:

In []: df                                                                                                                                                       
Out[]: 
     a  b    c
0  1.0  0  7.0
1  1.0  1  7.0
2  2.0  1  8.0
3  4.0  0  0.0
4  5.0  0  1.0
5  5.0  1  1.0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM