嗨,我有一个数据框,并且想更新最后一个列'pos1',以便每当列'sigc'下的值是1时,它就一直取整'pos'列中的值,直到'sigc'列下的值为止更改为-1,在这种情况下pos的值应为上方单元格的-ve。
请参阅列['pos1']
长话短说-我有一个表,其中“日期”列到“位置”列,我想添加一个列pos1并显示值。它是如何做到的。我假设它是连续的fwd pandas df操作
检查下表中的“ pos1”列
下面是我的代码,但有点困惑,我必须使用最后一个代码两次才能使其正常工作
df ['pos1'] = np.where(df ['sigc'] == 1,df ['pos'],np.nan)
df ['pos1'] = df ['pos1']。ffill()
df ['pos1'] = np.where(df ['sigc'] == -1,df ['pos1']。shift()* -1,df ['pos1'])
df ['pos1'] = np.where(df ['sigc'] == 0,np.where(df ['sigc']。shift()== -1,0,df ['pos1']。shift ()),df ['pos1'])
df ['pos1'] = np.where(df ['sigc'] == 0,np.where(df ['sigc']。shift()== -1,0,df ['pos1']。shift ()),df ['pos1'])
答案 0 :(得分:0)
所以我创建了一些随机数据:
.Row
然后,如果为1,则将其复制过来。如果它是负数,则反转最后一个值并将其向前拉。如果仍然为空,则向前填充数据。
>>> df = pd.DataFrame([{'flag': 1},{'flag': -1},{'flag': 0},{'flag': 0},{'flag': 0},{'flag': -1},{'flag': 1}])
>>> df['value'] = np.random.randint(1, 100, size=len(df))
Out[26]:
flag value
0 1 27
1 -1 40
2 0 40
3 0 9
4 0 30
5 -1 88
6 1 3
这将产生:
df['new'] = np.where(df['flag'] == 1, df['value'], np.nan)
df['new'] = np.where(df['flag'] == -1, df['new'].shift() * -1, df['new'])
df['new'] = df['new'].ffill()