我有一個包含超過 6000 行的 Excel 表。有兩列,“IP 地址 CMDB”包含 IP 地址,另一列稱為“IP 地址 LM”。我正在嘗試在“IP 地址 LM”中查找屬于“IP 地址 CMDB”的 IP 地址,如果“IP 地址 LM”包含該 IP 地址回傳 ABCD。我無法附上excel表格,所以我附上了它的截圖。

for col in report:
if col == "IP Address CMDB":
col_num = report[col]
for num in col_num:
if report["IP Address LM"].str.contains(num):
print("ABCD")
<ipython-input-13-40cfae2bd937>:5: UserWarning: This pattern has match groups. To actually get the groups, use str.extract.
if report["IP Address LM"].str.contains(num):
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-13-40cfae2bd937> in <module>
3 col_num = report[col]
4 for num in col_num:
----> 5 if report["IP Address LM"].str.contains(num):
6 print("ABCD")
7
c:\users\rohit verma\appdata\local\programs\python\python39\lib\site-packages\pandas\core\generic.py in __nonzero__(self)
1535 @final
1536 def __nonzero__(self):
-> 1537 raise ValueError(
1538 f"The truth value of a {type(self).__name__} is ambiguous. "
1539 "Use a.empty, a.bool(), a.item(), a.any() or a.all()."
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
uj5u.com熱心網友回復:
您可以簡單地使用以下代碼檢查IP 地址 LM是否包含屬于IP 地址 CMDB的內容:
checkColumn = []
for index, row in df.iterrows():
Ip = row["IP Address LM"]
toCheck = row["IP Address CMDB"]
if toCheck in Ip:
checkColumn.append("ABCD")
else:
checkColumn.append(None)
df["check"] = checkColumn
解釋
iterrows()函式回圈遍歷資料框的所有行。然后使用邏輯陳述句,例如toCheck in Ip我們試圖檢查值是否存在于上述列中。如果不是,則回傳None,否則,ABCD按要求回傳。
uj5u.com熱心網友回復:
作為我創建的源資料框(報告):
IP Address CMDB IP Address LM
0 10.1.0.36,10.1.53.1 10.1.0.36
1 10.1.11.21 10.1.11.21
2 10.1.148.20,192.168.128.3,10.1.5.130 10.1.5.130
3 10.1.5.100 10.1.5.140
4 10.1.6.120 10.1.6.140
要識別IP 地址 CMDB包含IP 地址 LM的行,您可以運行,例如:
report.apply(lambda row: row['IP Address LM'] in row['IP Address CMDB'], axis=1)
細節:
report.apply- 將給定的 lambda 函式應用于每一行(由于axis=1引數)。row['IP Address LM'] in row['IP Address CMDB']- 從當前行的兩列中創建臨時字串列,并檢查左側串列是否包含在右側串列中。- 回傳的值實際上回答了您的問題(IP 地址 CMDB是否 包含IP 地址 LM)。
結果是:
0 True
1 True
2 True
3 False
4 False
dtype: bool
如您所見,前 3 行中的IP地址 CMDB包含當前行的IP 地址 LM。
如果你想做更多的事情,撰寫你自己的函式,包括你的動作,回傳當前行的一些結果,并用這個函式替換 lambda 函式。
關于您的代碼的注釋: str.contains可用于檢查列的元素是否包含固定值,但您實際上只想檢查當前行中的值的包含情況。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/425820.html
