Python 熊猫在每N行之后插入一个新行
我有一个如下所示的数据框:Python 熊猫在每N行之后插入一个新行,python,pandas,dataframe,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
**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_类型)中的值增加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
我搜索了其他线程,但无法找到确切的解决方案:
您可以通过切片查看LCT行,将
1
添加到列C\u Type
中,并将0.5
添加到索引中,以实现100%的排序切片,因为中的默认排序方法是快速排序
。最后连接在一起,对索引进行排序并创建默认值,使用和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:只能将str(而不是“int”)连接到str@Baig-我认为
df['C_-Type']
列中有字符串,所以请使用df['C_-Type']=df['C_-Type']]。在我的解决方案之前使用astype(int)
,谢谢更新。我已经将列从String改为Int,现在可以了。有什么方法可以去掉我们刚刚插入的第五行最后一列中的值吗?