循环数据帧Pandas时跳过行

问题描述 投票:-1回答:2

我正在努力解决以下问题,似乎没有在网上找到任何解决方案。

我在数据帧上有一个for循环。这个循环应该执行以下操作:如果列'reversal'的内容== 1,用1填充'action'列,跳过125行,用-1填充'action'的下一个第126行,并继续重复从下一行循环。如果列'reversal'!= 1,则继续循环而不填充'action'。

问题1我有的是,当我写'index = index + 126'时,由于某种原因,python不明白它需要跳过126行。

问题2是,当我添加一个条件以避免使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
python pandas loops dataframe skip
2个回答
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

你可以试试这个


0
投票

如果可以使用索引,请不要使用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
© www.soinside.com 2019 - 2024. All rights reserved.