跳过 Pandas 数据帧循环中的行

4
我正在处理以下问题,但似乎在网上找不到任何解决方案。
我有一个针对数据框的for循环。此循环应执行以下操作:如果“reversal”列的内容== 1,则将“action”列填充为1,跳过125行,在下一个“action”列中填充第126行为-1,并继续从下一行重复循环。如果“reversal”列!= 1,则继续进行循环而不填充“action”。
问题1是,当我编写“index = index + 126”时,由于某种原因,Python无法理解它需要跳过126行。
问题2是,当我添加条件以避免使“action”列比“reversal”列更长时,该条件不起作用(请参见代码注释)。
#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
2个回答

3

如果可以使用索引,请不要使用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

0
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

你可以试试这个。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接