[英]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.我想在 Col2 中的值发生变化时定位所有位置(例如从 A 到 C 的变化),然后从 Col1 修改值(对应于发生变化时的行,所以当 A -> C 那么它会通过将减法当前值和先前值除以二(在此示例中将是 1 + (1.5-1)/2 = 1.25),得到与 C 相同行的值。
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使用
np.where
和系列保存公式的值
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.