【问题标题】:How do I delete rows in Excel based on values in column B and C如何根据 B 列和 C 列中的值删除 Excel 中的行
【发布时间】:2017-06-29 22:14:27
【问题描述】:

我在下面的电子表格中有 15,000 行,我需要保留这些行:

其中 status > 0 和 lastvalidationattemptdistance

【问题讨论】:

  • 查看pandas
  • 这里不能有一个简单的过滤器帮助吗?您真的不需要编程任何东西,只需激活过滤器选项并过滤状态和 lastvalidationattemptdistance 列。我在这里错过了什么吗?
  • 我认为它不会考虑 A、B 和 C 列相关的事实,但它有效,谢谢。现在我必须计算一个用户 ID 在 A 列中出现了多少次,想法?
  • 使用CountIF()内置的excel函数
  • 不确定 CountIF() 是否有效,因为我必须为所有 userId 执行此操作!基本上我需要查看每个 userId 在 A 列中出现的频率,然后计算每个 userId 的平均重复出现次数。

标签: python excel vba pandas


【解决方案1】:

pandas 中的简单数据操作。非常简单实用,10分钟就能学会。

import pandas as pd

df = pd.read_excel('excel.xlsx', 'sheet_name', index_col=None, na_values=['NA'])

df = df.loc[df['status'] > 0]
df = df.loc[df['lastValidationAttemptDistance'] < 50]

writer = pd.ExcelWriter('new_execel.xlsx')
df.to_excel(writer, 'sheet_name', index=False)
writer.save()

【讨论】:

    【解决方案2】:

    您可以在 excel 中使用 VBA 删除您需要的内容,然后找到一个 UserId。

    Sub Delete()
    '
    ' Delete and Find Macro
    '
    
    
        Dim aRows As Integer, LVAD As Integer, Stat As Integer, UserId As Integer, UIDCount As Integer
        Dim Rng As Range, Rng2 As Range
    
        LVAD = 50 'Min value to keep
        Stat = 0 'Min value to keep
        UIDCount = 0 'Initial count number
        UserId = 3526 'Exact number of userId
    
        With ActiveSheet
        aRows = .Cells(.Rows.Count, "A").End(xlUp).Row
        End With
    
        For i = 1 To aRows
            If Range("B" & i).Value <= 0 Then
                If Range("C" & i).Value > 50 Then
                    If Rng Is Nothing Then
                        Set Rng = Range("A" & i & ":C" & i)
                    Else
                        Set Rng2 = Range("A" & i & ":C" & i)
                        Set Rng = Application.Union(Rng, Rng2)
                    End If
                End If
            End If
        Next
    
        For i = 1 To aRows
            If Range("A" & i).Value = UserId Then
                UIDCount = UIDCount + 1
            End If
        Next
    
        If Not Rng Is Nothing Then
            Rng.Select
            Selection.Delete Shift:=xlUp
        End If
        MsgBox "UserId: " & UserId & " was found " & UIDCount & " times."
    End Sub
    

    要单独计算每个用户的 userId,您可以计算所有唯一 id,然后对每个用户进行循环迭代以计算出现次数,然后可以将这些值设置为列。

    【讨论】:

      【解决方案3】:

      由于您使用 Excel for Windows,请考虑通过连接到 Jet/ACE SQL 引擎(Windows .dll 文件通常安装在大多数 PC 和 MS Access 引擎上)的 SQL 解决方案。您可以在 WHERE 子句中使用您的确切标准。不需要For 循环或嵌套If 逻辑或公式。

      以下假设数据位于名为DATA 的工作表中,并且工作簿中存在一个名为RESULTS 的空工作表,它将保存SQL 查询的输出,包括标题。包括两种连接类型,即 ODBC 驱动程序和 OLEDB 提供程序。只需更改 Excel 数据文件的路径即可。

      Public Sub RunSQL()
          Dim conn As Object, rst As Object
          Dim strConnection As String, strSQL As String
          Dim i As Integer
      
          Set conn = CreateObject("ADODB.Connection")
          Set rst = CreateObject("ADODB.Recordset")
      
          ' DRIVER AND PROVIDER CONNECTION TYPES
      '    strConnection = "DRIVER={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};" _
      '                      & "DBQ=C:\Path\To\Workbook.xlsm;"
          strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" _
                             & "Data Source='C:\Path\To\Workbook.xlsm';" _
                             & "Extended Properties=""Excel 12.0;HDR=YES;"";"
      
          strSQL = " SELECT * FROM [DATA$]" _
                      & " WHERE [status] > 0 AND [lastvalidationattemptdistance] < 50;"
      
          ' OPEN DB CONNECTION
          conn.Open strConnection
          rst.Open strSQL, conn
      
          ' COLUMN HEADERS
          For i = 1 To rst.Fields.Count
              Worksheets("RESULTS").Cells(1, i) = rst.Fields(i - 1).Name
          Next i    
      
          ' DATA ROWS
          Worksheets("RESULTS").Range("A2").CopyFromRecordset rst
      
          ' CLOSE OBJECTS AND FREE RESOURCES
          rst.Close: conn.Close
          Set rst = Nothing: Set conn = Nothing
      End Sub
      

      【讨论】:

        猜你喜欢
        • 2021-04-21
        • 2019-07-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-10-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多