我正在努力解决以下问题,似乎没有在网上找到任何解决方案。
我在数据帧上有一个for循环。这个循环应该执行以下操作:如果列'reversal'的内容== 1,用1填充'action'列,跳过125行,用-1填充'action'的下一个第126行,并继续重复从下一行循环。如果列'reversal'!= 1,则继续循环而不填充'action'。
#creating the on/off signal column
df_zinc['action'] = 0
#creating the loop
for index,row in df_zinc.iterrows():
if row.reversal == 1:
df_zinc.loc[index,'action'] = 1
if index<len(df_zinc.index)-126: #the purpose of this condition is to not have the action column longer than the reversal column. Thuogh, it appears not to be working
df_zinc.loc[index+126, 'action'] = -1
index= index + 127
import numpy as np
import pandas as pd
reversal=np.eye(126,dtype=int)
reversal=reversal.reshape(-1)
data=pd.DataFrame({"reverse":reversal})
data['action']=0
for index in range(len(data)):
if data.loc[index,"reverse"] == 1:
data.loc[index,'action'] = 1
if index<len(data.index)-126:
data.loc[index+126, 'action'] = -1
index= index + 127
你可以试试这个
如果可以使用索引,请不要使用itterrows()。
试试这个:
#creating the on/off signal column
# df_zinc['action'] = 0
#
count = 0
# #creating the loop
for index in df_zinc.index:
if index < count:
continue
if df_zinc.at[index , 'reversal'] == 1:
df_zinc.at[index , 'action'] = 1
if index < len(df_zinc)-126: #the purpose of this condition is to not have the action column longer than the reversal column. Thuogh, it appears not to be working
df_zinc.at[index+126, 'action'] = -1
count = index + 127