栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在pandas数据框中的特定索引处插入新行

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在pandas数据框中的特定索引处插入新行

保留索引顺序是棘手的部分。我不确定这是否是最有效的方法,但是它应该可以工作。

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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/647829.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号