简体   繁体   English

如何根据某些条件定位和替换数据框中的值

[英]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第 1 列 Col2 Col2
1 1 A一种
1.5 1.5 C C
2.0 2.0 A一种
2.5 2.5 A一种
3.0 3.0 D D
3.5 3.5 D D

OUTPUT:输出:

Col1第 1 列 Col2 Col2
1 1 A一种
1.25 1.25 C C
1.75 1.75 A一种
2.5 2.5 A一种
2.75 2.75 D D
3.5 3.5 D 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.

相关问题 熊猫根据标准替换数据框值 - Pandas replace dataframe values based on criteria PySpark:根据条件替换数据框的值 - PySpark: Replace values of dataframe based on criteria 如何根据 Python 中的某些条件从数据帧或过滤器中提取值? - How can I extract values from a dataframe or filter based on some criteria in Python? 在某些条件下,如何根据不同的数据框列替换一个数据框的列值? - How can we replace the columns values of one dataframe based on different dataframe column using some conditions? 如何根据其他一些 dataframe 替换一个 pandas dataframe 列值? - How to replace one pandas dataframe column values based on some other dataframe? 根据来自另一个数据框的条件在一个数据框中找到行 - Locate rows in one dataframe based on criteria from another dataframe 如何根据某些条件从 dataframe 创建过滤条件? - How to create filter condition from dataframe based on some criteria? 如何根据条件替换熊猫数据框中的值? - How to replace values in a pandas dataframe based on conditions? 如何根据多个条件替换Dataframe中的值? - How to replace values in Dataframe based on multiple conditions? 如何根据另一个 dataframe 中的查找值替换 pandas dataframe 值? - How to replace pandas dataframe values based on lookup values in another dataframe?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM