python - 如何将具有特定特征的行追加到组的末尾?

标签 python pandas append row

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

|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 ),但它并没有真正帮助我。

如有任何帮助,我们将不胜感激。

最佳答案

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)

关于python - 如何将具有特定特征的行追加到组的末尾?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56047943/

相关文章:

Python:httplib getresponse 发出许多 recv() 调用

python - 使用 emacs 的 unicode (Python 3/Julia) 选项卡完成?

python - Google App Engine Django App Admin 登录导致 502

python - pandas:在(多索引)DataFrame上使用每个组中最常见的值执行 fillna() 的最佳方法是什么?

python - Pandas MultiIndex 重新排列列

javascript - JQuery 复制/追加元素,已删除基础对象

python - 分割并保留分割python的字符

python - Pandas 合并给出错误的输出

go - 将整数 slice append 到整数 slice 的 slice 会修改被 append 的 slice

jquery - 使用 jQuery Each 从数组创建多个列表