【问题标题】:Pandas Insert a new row after every nth rowPandas 在每第 n 行后插入一个新行
【发布时间】:2019-09-17 06:14:39
【问题描述】:

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

 **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

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    您可以通过切片来查看行,将1添加到列C_Type0.5到索引,100%正确切片,因为DataFrame.sort_index中的默认排序方法是quicksort。最后加入,排序索引并按concatDataFrame.reset_indexdrop=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 - 我认为df['C_Type'] 列中有字符串,所以在我的解决方案之前使用df['C_Type'] = df['C_Type'].astype(int)
    • 感谢您的更新。我已将列从 String 更改为 Int 并且现在很好。有什么办法可以去掉我们刚刚插入的第 5 行最后一列的值?
    猜你喜欢
    • 1970-01-01
    • 2018-04-19
    • 1970-01-01
    • 2016-07-16
    • 1970-01-01
    • 2021-06-02
    • 2013-01-13
    • 2018-06-01
    • 2021-04-22
    相关资源
    最近更新 更多