【问题标题】:Insert Rows based on Missing numbers in repeated Series using Excel or Python使用 Excel 或 Python 根据重复系列中的缺失数字插入行
【发布时间】:2016-10-13 06:27:47
【问题描述】:

我有一个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

插入缺失的行。

我知道如果数字不重复,下面的 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

【问题讨论】:

  • @fishboen,丢失的数据从何而来?你想要python代码吗..
  • .@fishbone 为什么你不能只重写 cvs 文件而不是你的方法?
  • 没有系列指标吗?类别、类型、组?还是您按数据中的顺序识别系列?
  • python 或 vba 都可以。该数字在一系列中重复,但有时如果数字行没有数据,它将省略。但我需要将那些丢失的数据行添加回文件中。

标签: python excel vba csv pandas


【解决方案1】:

这将创建一个名为 data2 的新数据框,其中插入了行。样本中的第四行有一个额外的变量,所以我还添加了一个额外的列。

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

Original

New

【讨论】:

  • @fishbone 这个人为这个不平凡的问题付出了相当多的努力,你应该接受这个答案,不要那么刻薄。
猜你喜欢
  • 2021-11-06
  • 2023-03-26
  • 2017-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-03
  • 1970-01-01
  • 2013-08-24
相关资源
最近更新 更多