保留索引顺序是棘手的部分。我不确定这是否是最有效的方法,但是它应该可以工作。
x = [2,8,12]rows = []cur = {}for i in df.index: if i in x: cur['index'] = i cur['identifier'] = df.iloc[i].identifier cur['values'] = df.iloc[i]['values'] cur['subid'] = df.iloc[i].subid - 1 rows.append(cur) cur = {}然后,遍历新行列表,并执行增量连接,将每个新行插入正确的位置。
offset = 0; #tracks the number of rows already inserted to ensure rows are inserted in the correct positionfor d in rows: df = pd.concat([df.head(d['index'] + offset), pd.Dataframe([d]), df.tail(len(df) - (d['index']+offset))]) offset+=1df.reset_index(inplace=True)df.drop('index', axis=1, inplace=True)df level_0 identifier subid values0 0 1 1 1011 1 1 1 1022 0 1 1 1033 2 1 2 1034 3 1 2 1045 4 1 2 1056 5 2 3 1067 6 2 3 1078 7 2 3 1089 0 2 3 10910 8 2 4 10911 9 2 4 11012 10 3 5 11113 11 3 5 11214 0 3 5 11315 12 3 6 113


