【问题标题】:skip rows while looping over dataframe Pandas在循环数据框 Pandas 时跳过行
【发布时间】:2019-08-10 19:36:35
【问题描述】:

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

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

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

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

#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


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:
      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
      

      你可以试试这个

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-01-20
        • 2017-04-07
        • 1970-01-01
        • 2019-07-08
        • 2020-08-25
        • 1970-01-01
        • 2017-05-09
        相关资源
        最近更新 更多