【问题标题】:How to append a row with specific characteristics to the end of a group?如何将具有特定特征的行附加到组的末尾?
【发布时间】:2019-09-26 14:41:57
【问题描述】:

我想在可以按变量分组的数据框末尾附加一行。
我的数据框如下所示:

|ID | Name1 | Name2 | PointA | PointB | Var1 | Var2 | 
| 1 | AAA   | zzz   | ABC    | BCD    |  1   |  5   | 
| 1 | AAA   | zzz   | BCD    | CDE    |  2   |  5   | 
| 1 | AAA   | zzz   | CDE    | DEF    |  3   |  5   | 
| 2 | BBB   | yyy   | STU    | TUV    |  1   |  6   | 
| 2 | BBB   | yyy   | TUV    | UVW    |  2   |  6   | 
| 2 | BBB   | yyy   | UVW    | VWX    |  3   |  6   | 
| 2 | BBB   | yyy   | VWX    | WXY    |  4   |  6   | 

我想要的是在ID定义的每个类别的末尾添加一行:

|ID | Name1 | Name2 | PointA | PointB | Var1 | Var2 | 
| 1 | AAA   | zzz   | ABC    | BCD    |  1   |  5   | 
| 1 | AAA   | zzz   | BCD    | CDE    |  2   |  5   | 
| 1 | AAA   | zzz   | CDE    | DEF    |  3   |  5   | 
| 1 | AAA   | zzz   | DEF    | ---    |  4   |  0   | 
| 2 | BBB   | yyy   | STU    | TUV    |  1   |  6   | 
| 2 | BBB   | yyy   | TUV    | UVW    |  2   |  6   | 
| 2 | BBB   | yyy   | UVW    | VWX    |  3   |  6   | 
| 2 | BBB   | yyy   | VWX    | WXY    |  4   |  6   | 
| 2 | BBB   | yyy   | WXY    | ---    |  5   |  0   | 

我试过了:(我原来的df叫operacionales

df = pd.DataFrame(columns = operacionales.columns)
val = range(1, 22223)
for x in val:
    test = operacionales.loc[operacionales['ID'] == x]
    li = [test.ID.iloc[0], test.Name1.iloc[0], test.Name2.iloc[0],
test.PointB.iloc[-1], '-', test.Var1.max() + 1, 0]
    t = pd.DataFrame(li).T
    t.columns = test.columns
    test2 = test.append(t)
    df = df.append(test2)

但我收到“IndexError:单个位置索引器超出范围” 我尝试了相同的方法,但在代码中使用索引[-1] 而不是[0],结果是一样的。

如您所见,我要添加的行与组的其他行相同,除了:
1.PointA(我想成为PointB变量的最后一个值),
2.PointB(我想设置为'---'),
3.Var1(我想成为组中最后一个值的 +1),以及
4.Point2(我想设置为0)。

我找到了这个 (append rows to a Pandas groupby object),但它并没有真正帮助我。

任何帮助将不胜感激。

【问题讨论】:

    标签: python pandas append row


    【解决方案1】:

    我会这样做:

    t = df.groupby('ID', as_index=False).last() 
    t[['PointA', 'PointB', 'Var1', 'Var2']] = np.column_stack([t.PointB, ['---']*2, t.Var1+1, [0]*2])
    pd.concat([df, t], ignore_index=True).sort_values('ID')
    
    Out[121]:
       ID Name1 Name2 PointA PointB  Var1  Var2
    0   1   AAA   zzz    ABC    BCD     1     5
    1   1   AAA   zzz    BCD    CDE     2     5
    2   1   AAA   zzz    CDE    DEF     3     5
    7   1   AAA   zzz    DEF    ---     4     0
    3   2   BBB   yyy    STU    TUV     1     6
    4   2   BBB   yyy    TUV    UVW     2     6
    5   2   BBB   yyy    UVW    VWX     3     6
    6   2   BBB   yyy    VWX    WXY     4     6
    8   2   BBB   yyy    WXY    ---     5     0
    

    【讨论】:

      【解决方案2】:

      你可以使用 groupby / apply:

      def append_column_to_group(group):
          result = group
          result = result.append({'ID': 1,
                                  'Name1': group.iloc[0].Name1,
                                  'Name2': group.iloc[0].Name2,
                                  'PointA': group.iloc[-1].PointB,
                                  'PointB': '---',
                                  'Var1': group.iloc[-1].Var1 + 1,
                                  'Var2': 0}, ignore_index=True)
          return result
      df.groupby('Name1').apply(append_column_to_group)
      

      【讨论】:

        【解决方案3】:

        IIUC

        appenddf=df.groupby('ID').tail(1)
        appenddf=appenddf.drop('PointA',1).rename(columns={'PointB':'PointA'}).assign(Var1=appenddf.Var1+1)
        df=pd.concat([df,appenddf],sort=True).sort_index()
        df
        Out[232]: 
           ID Name1 Name2 PointA PointB  Var1  Var2
        0   1   AAA   zzz    ABC    BCD     1     5
        1   1   AAA   zzz    BCD    CDE     2     5
        2   1   AAA   zzz    CDE    DEF     3     5
        2   1   AAA   zzz    DEF    NaN     4     5
        3   2   BBB   yyy    STU    TUV     1     6
        4   2   BBB   yyy    TUV    UVW     2     6
        5   2   BBB   yyy    UVW    VWX     3     6
        6   2   BBB   yyy    VWX    WXY     4     6
        6   2   BBB   yyy    WXY    NaN     5     6
        

        【讨论】:

          【解决方案4】:
          def update_method(series):
              last_row = series.iloc[-1]
              new_row = last_row
              new_row['PointA'] = last_row['PointA']
              new_row['PointB'] = '---'
              new_row['Var1'] = last_row['Var1']+1
              series = series.append(new_row)
              return series
          new_df = df.groupby('Name1').apply(update_method)
          

          【讨论】:

          • 这正是我所需要的!非常感谢。
          猜你喜欢
          • 2015-05-13
          • 2021-09-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-07-14
          • 2022-06-11
          相关资源
          最近更新 更多