在 Pandas 中每隔 n 行插入一个新行

4

我有一个数据框,看起来像下面这样:

 **L_Type   L_ID    C_Type      E_Code**
    0       1           1         9
    0       1           2         9
    0       1           3         9
    0       1           4         9
    0       2           1         2
    0       2           2         2
    0       2           3         2
    0       2           4         2
    0       3           1         3
    0       3           2         3
    0       3           3         3
    0       3           4         3

我需要在每4行之后插入一行新的数据,并将第三列(C_Type)的值递增01,如下表所示,同时保持前两列的值不变,不要有任何值在最后一列:

 L_Type     L_ID    C_Type          E_Code
    0       1           1           9
    0       1           2           9
    0       1           3           9
    0       1           4           9
    0       1           5           
    0       2           1           2
    0       2           2           2
    0       2           3           2
    0       2           4           2
    0       2           5           
    0       3           1           3
    0       3           2           3
    0       3           3           3
    0       3           4           3
    0       3           5           

我已经搜索了其他线程,但没能找到确切的解决方案:

如何在Pandas中每n行插入一个DataFrame到另一个DataFrame?

在Pandas数据帧中插入新行

1个回答

4
你可以通过切片来选择行,将 C_Type 列加上 1,索引加上 0.5,以实现 100% 准确的切片,因为在 DataFrame.sort_index 中默认的排序方法是 quicksort。最后将它们连接起来,排序索引并使用 concatDataFrame.reset_index (并用 drop=True 删除原来的索引)创建默认值即可。
df['C_Type'] = df['C_Type'].astype(int)

df2 = (df.iloc[3::4]
         .assign(C_Type = lambda x: x['C_Type'] + 1, E_Code = np.nan)
         .rename(lambda x: x + .5))
df1 = pd.concat([df, df2], sort=False).sort_index().reset_index(drop=True)
print (df1)
    L_Type  L_ID  C_Type  E_Code
0        0     1       1     9.0
1        0     1       2     9.0
2        0     1       3     9.0
3        0     1       4     9.0
4        0     1       5     NaN
5        0     2       1     2.0
6        0     2       2     2.0
7        0     2       3     2.0
8        0     2       4     2.0
9        0     2       5     NaN
10       0     3       1     3.0
11       0     3       2     3.0
12       0     3       3     3.0
13       0     3       4     3.0
14       0     3       5     NaN

嗨,jezreal,感谢您的快速回复。当我运行代码时,出现错误消息:TypeError: can only concatenate str (not "int") to str。 - Baig
@Baig - 我认为df['C_Type']列中有字符串,因此在使用我的解决方案之前,请使用df['C_Type'] = df['C_Type'].astype(int) - jezrael
2
谢谢更新。我已将该列从字符串更改为整数,现在没问题了。有没有办法删除我们刚插入的第5行最后一列中的值? - Baig

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接