import pandas as pd
# 读取Excel文件
df = pd.read_excel(r'C:\Users\ComLan\Desktop\网段.xlsx')
# 分组规则
subnet_ranges = {
'UAT网段': ['192.168.1.','192.166.1'],
'DR环境': ['10.120.0.'],
'DEV': ['10.121.1.'],
'PROD环境': ['172.161.1.'],
'Azure测试环境':['10.0.0.'],
'Azure生产环境':['10.130.0.'],
'AzureDR环境':['10.122.2.'],
'AzureINFRA环境':['172.162.1.']
}
#print (subnet_ranges)
# 循环遍历查找IP数据
for subnet_name, subnet_range in subnet_ranges.items():
# 构建筛选条件
conditions = []
for subnet in subnet_range:
condition = df['IP'].str.startswith('subnet')
conditions.append(condition)
# print(conditions)
condition = pd.concat(conditions, axis=0).any()
#print(condition)
# 筛选出特定网段的数据
subnet_df = df[condition]
#
# # 将数据写入Excel文件
subnet_df.to_excel(f'{subnet_name}.xlsx', index=False)
以上代码运行报错
C:\Users\ComLan\PycharmProjects\pythonProject\venv\Scripts\python.exe C:/Users/ComLan/PycharmProjects/pythonProject/网段.py
Traceback (most recent call last):
File "C:\Users\ComLan\PycharmProjects\pythonProject\venv\lib\site-packages\pandas\core\indexes\base.py", line 3802, in get_loc
return self._engine.get_loc(casted_key)
File "pandas\_libs\index.pyx", line 138, in pandas._libs.index.IndexEngine.get_loc
File "pandas\_libs\index.pyx", line 165, in pandas._libs.index.IndexEngine.get_loc
File "pandas\_libs\hashtable_class_helper.pxi", line 5745, in pandas._libs.hashtable.PyObjectHashTable.get_item
File "pandas\_libs\hashtable_class_helper.pxi", line 5753, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: False
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\ComLan\PycharmProjects\pythonProject\网段.py", line 30, in <module>
subnet_df = df[condition]
File "C:\Users\ComLan\PycharmProjects\pythonProject\venv\lib\site-packages\pandas\core\frame.py", line 3807, in __getitem__
indexer = self.columns.get_loc(key)
File "C:\Users\ComLan\PycharmProjects\pythonProject\venv\lib\site-packages\pandas\core\indexes\base.py", line 3804, in get_loc
raise KeyError(key) from err
KeyError: False
第23行的这个参数构建好像不太对吧,把第25行改成这样的试试:
您可以把第25行的
condition = df['IP'].str.startswith('subnet')
改为:
condition = df['IP'].str.startswith(subnet)
如果以上回答对您有所帮助,望采纳~谢谢