如何在python中修改后在指定位置添加多行? [英] how to add multiple rows in a specified position with modification in python?

查看:66
本文介绍了如何在python中修改后在指定位置添加多行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框,我想按以下方式复制和行

I have a data frame where I want to replicate and rows in the following manner

 d=pd.DataFrame({"col1":["a","b","c","d"],
                "col2":[12,13,14,16]})

所需的输出:想要复制行 a1、a2、b1、b2

required output: want to copy rows a1, a2, b1, b2

col1  col2
a      12
a1     12 
a2     12
b      12
b1     12  
b2     12
c      12 
c1     12
c2     12
d      12 
d1     12
d2     12

推荐答案

IIUC,你可以试试 index.repeatgroupby+cumcount

IIUC, You can try index.repeat with groupby+cumcount

n = 3
out = d.loc[d.index.repeat(n)]
out = out.assign(col1=out['col1']+out.groupby("col1").cumcount()
                  .replace(0,'').astype(str)).reset_index(drop=True)


print(out)

   col1  col2
0     a    12
1    a1    12
2    a2    12
3     b    13
4    b1    13
5    b2    13
6     c    14
7    c1    14
8    c2    14
9     d    16
10   d1    16
11   d2    16

为了以后重复col1的值,你可以使用helper series作为grouper:

For repeating values of col1 later, you can use a helper series as grouper:

d=pd.DataFrame({"col1":["a","b","a","d"],"col2":[12,13,14,16],
                 "col3":[1,2,3,4]})
n = 3
out = d.loc[d.index.repeat(n)]
out = (out.assign(col1=out['col1']+out.groupby(out['col1'].ne(out['col1'].shift())
                               .cumsum()).cumcount().replace(0,'').astype(str))
           .reset_index(drop=True))
print(out)

   col1  col2  col3
0     a    12     1
1    a1    12     1
2    a2    12     1
3     b    13     2
4    b1    13     2
5    b2    13     2
6     a    14     3
7    a1    14     3
8    a2    14     3
9     d    16     4
10   d1    16     4
11   d2    16     4

这篇关于如何在python中修改后在指定位置添加多行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆