python - Pandas 在每第 n 行后插入一个新行

标签 python pandas dataframe

我有一个如下所示的数据框:

 **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           
我搜索了其他线程,但无法找出确切的解决方案:
How to insert n DataFrame to another every nth row in Pandas?
Insert new rows in pandas dataframe

最佳答案

您可以通过切片来查看行,添加 1到专栏C_Type0.5索引,用于 100% 正确切片,因为 DataFrame.sort_index 中的默认排序方法是 quicksort .最后连接在一起,排序索引并创建默认值 concat DataFrame.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

关于python - Pandas 在每第 n 行后插入一个新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57968329/

相关文章:

python-3.x - 有条件地乘以 DataFrame 行中的值

python - 如何从两侧找到最大数组

python - Pygame 的网络支持

python - PhantomJS - 权限被拒绝

python - 如何使字典键是 Pandas 数据帧的一列到列?

python - Pandas 按逻辑日期对数据框进行排序

python - 链式 Spark 列表达式具有不同的Windows规范,会产生无效的DAG

python - 变量和损失评估的奇怪顺序

python - 如何将索引列转换为数字?

python-3.x - Pandas .agg() 转换为列表但跳过 nans