[英]How do I delete rows in Excel based on values in column B and C
大熊貓的簡單數據處理。 它非常簡單實用,您可以在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()
您可以在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,然后對每個用戶進行循環迭代以計算出現次數,然后將這些值設置為列。
由於您使用Excel for Windows,因此可以通過連接到Jet / ACE SQL引擎(通常在大多數PC上安裝Windows .dll文件以及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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.