使用Excel或Python在重复序列中基于缺less数字插入行

我有以下格式的csv文件(实际上,重复数大于4):

Number, Time, Speed 1, 12, 5.8 2, 11, 6.2 3, 9, 7.0 4, 3, 11.9 1, 6, 9.5 3, 7.5, 8.2 4, 4.2, 8.2 2, 2.3, 8.1 4, 4.6, 9.2 

我想输出看起来像这样:

 Number, Time, Speed 1, 12, 5.8 2, 11, 6.2 3, 9, 7.0 4, 3, 11.9 1, 6, 9.5 2, 0, 0 3, 7.5, 8.2 4, 4.2, 8.2 1, 0, 0 2, 2.3, 8.1 3, 0, 0 4, 4.6, 9.2 

插入缺less的行。

我知道如果数字不重复,像下面的vba代码可能工作。 但是我的数据是重复系列的。 谁能帮忙?

 Sub InsertRows() Dim x As Long, y As Long For x = Range("A" & Rows.Count).End(xlUp).Row To 2 Step -1 y = Range("A" & x) - Range("A" & x - 1) If y > 1 Then Range("A" & x).Resize(y - 1).EntireRow.Insert xlShiftDown Next End Sub 

这将创build一个名为data2的新数据框,并插入行。 你的示例中的第四行有一个额外的variables,所以我还添加了一个额外的列。

 data = pd.read_csv("soqn.csv") data2 = data.copy() data2_index = 0 for index , row in data.iterrows(): #Set the current value of the number and the next value in the list current_value = data['Number'][index] next_value = data['Number'][min(max(0,index + 1),data['Number'].size-1)] #Write in the value as per normal if the following value is the same if current_value + 1 == next_value or current_value == next_value + 3 or index == 0 : data2.loc[data2_index] = data.loc[index] data2_index = data2_index + 1 else: #Otherwise, add in new rows till we get to the value in the next row in the original df if next_value < current_value: current_value = 0 target_value = next_value - 1 data2.loc[data2_index] = data.loc[index] data2_index = data2_index + 1 for x in range(current_value+1,target_value+1): data2.loc[data2_index] = [x,0,0,0] data2_index = data2_index + 1 

原版的

在这里输入图像说明

在这里输入图像说明