跳过数据框熊猫时跳过行

时间:2019-03-20 07:04:10

标签: python pandas loops dataframe skip

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

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

问题1是,当我写'index = index + 126'时,由于某种原因python无法理解需要跳过126行。`

问题2是,当我添加一个条件以避免操作列长于反转列时,该条件不起作用(请参见代码注释)。

DateTime appointmentDate = DateTime.UtcNow;
DateTime appointmentDateToStore = new DateTime(
    appointmentDate.Year,
    appointmentDate.Month,
    appointmentDate.Day,
    appointmentDate.Hour,
    appointmentDate.Minute,
    0);

2 个答案:

答案 0 :(得分: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

您可以尝试

答案 1 :(得分: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
相关问题