简体   繁体   中英

How to locate and replace values in dataframe based on some criteria

I would like to locate all places when in Col2 there is a change in value (for ex. change from A to C) and then modify value from Col1 (corresponding to row when the change happens, so when A -> C then it will be value in the same row as C) by dividing subtraction current value and previous value by two (in this example will be 1 + (1.5-1)/2 = 1.25.

Output table is result of replacing all that occurrences in whole table

How I can achieve that ?

Col1 Col2
1 A
1.5 C
2.0 A
2.5 A
3.0 D
3.5 D

OUTPUT:

Col1 Col2
1 A
1.25 C
1.75 A
2.5 A
2.75 D
3.5 D

Use np.where and series holding values of your formula

solution = df.Col1.shift() + ((df.Col1 - df.Col1.shift()) / 2)
df['Col1'] = np.where(~df.Col2.eq(df.Col2.shift()), solution.fillna(df.Col1), df.Col1)

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