有条件替换基于 pandas 数据框python同一列中的先前值

编程入门 行业动态 更新时间:2024-10-22 23:49:01
本文介绍了有条件替换基于 pandas 数据框python同一列中的先前值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

感觉就像我到处都是,我知道它可能很简单.我正在使用pandas数据框,并希望根据该SAME列中的数据填充/替换其中一列中的数据.我通常更多地是excel用户,并且在excel中非常简单.如果我们有:

Feel like I've looked just about everywhere and I know its probably something very simple. I'm working with a pandas dataframe and looking to fill/replace data in one of the columns based on data from that SAME column. I'm typically more of an excel user and it is sooo simple in excel. If we have:

df = pd.DataFrame([0, -1, -1, -1, 0 , 0, 0, 1, 0]) df.columns = ['A'] df['B'] = df['A']

在excel中,我要执行的操作是"= IF(AND(A2 = 0,B1 = -1),-1,A2),这样我就可以向下拖动列'B'并将其应用于本质上,基于B列的先前数据点和A列的当前值,我需要更新B的当前值.

in excel what I'm trying to do would be " =IF(AND(A2=0, B1=-1), -1, A2) so that I could then drag down column 'B' and that would apply. In essence, based on the prior data point of column B, and the current value of column A, I need to update the current value of B.

我尝试过:

df['B'] = np.where((df['A'] == 0), (df['B'].shift(1) == -1), df['B'].replace(to_value = 0, method = 'ffill'), df['A'])

及其它的许多其他版本,以及变体的变体和其他难以置信的极端变通方法.

and lots of other version of that, as well as variations of iterrows and other incredibly extreme work-arounds with no avail.

任何建议都将不胜感激.

Any suggestions are greatly appreciated.

结果将是:

df['B'] = [0, -1, -1, -1, -1 , -1, -1, 1, 0]

推荐答案

这是一种蛮力方法.可能有些更优雅的方法,但是您可以像这样显式地遍历行:

Here's a kind of brute-force method. There is probably something more elegant, but you could explicitly loop over the rows like this:

df = pd.DataFrame([0, -1, -1, -1, 0 , 0, 0, 1, 0]) df.columns = ['A'] df['B'] = df['A'] # loop here for i in range(1,len(df)): if df.A[i] == 0 and df.B[i-1] == -1: df.B[i] = -1 else: df.B[i] = df.A[i]

这为您提供了您想要的结果:

This gives you the result you seek:

>>> df['B'] 0 0 1 -1 2 -1 3 -1 4 -1 5 -1 6 -1 7 1 8 0

更多推荐

有条件替换基于 pandas 数据框python同一列中的先前值

本文发布于:2023-10-23 05:57:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1519991.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:有条件   先前   数据   pandas   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!