感觉就像我到处都是,我知道它可能很简单.我正在使用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同一列中的先前值
发布评论