我在我的 python 腳本中執行以下操作,并且我想在列印資料框時隱藏索引列。所以我使用 .to_string(index = False) 然后使用 len() 來查看它是否為零。但是,當我執行 to_string() 時,如果資料幀為空,則 len() 不會回傳零。如果我列印 procinject1,它會顯示“Empty DataFrame”。任何解決此問題的幫助將不勝感激。
procinject1=dfmalfind[dfmalfind["Hexdump"].str.contains("MZ") == True].to_string(index = False)
if len(procinject1) == 0:
print(Fore.GREEN "[?]No MZ header detected in malfind preview output")
else:
print(Fore.RED "[!]MZ header detected within malfind preview (Process Injection indicator)")
print(procinject1)
uj5u.com熱心網友回復:
這是 Pandas DataFrame 中的預期行為。
在您的情況下,procinject1存盤資料幀的字串表示形式,即使相應的資料幀為空,它也不是空的。
例如,檢查下面的代碼片段,我在其中創建了一個空資料框df并檢查它的字串表示:
df = pd.DataFrame()
print(df.to_string(index = False))
print(df.to_string(index = True))
對于這兩種情況index = False,index = True輸出將是相同的,如下所示(這是預期的行為)。因此,您的對應len()將始終回傳非零。
Empty DataFrame
Columns: []
Index: []
但是,如果您使用非空資料框,則index = False和index = Truecase 的輸出將不同,如下所示:
data = [{'A': 10, 'B': 20, 'C':30}, {'A':5, 'B': 10, 'C': 15}]
df = pd.DataFrame(data)
print(df.to_string(index = False))
print(df.to_string(index = True))
然后分別為index = False和index = Truecase 的輸出將是 -
A B C
10 20 30
5 10 15
A B C
0 10 20 30
1 5 10 15
由于 pandas 處理空資料幀的方式不同,為了解決您的問題,您應該首先使用pandas.DataFrame.empty檢查您的資料幀是否為空。
然后,如果資料框實際上是非空的,您可以列印該資料框的字串表示,同時保持index = False隱藏索引列。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/474495.html
下一篇:根據先前的值和乘法計算值
