1 回答
TA贡献1786条经验 获得超13个赞
以下解决方案基于这样的假设:只有第四组 IP 发生变化,而前三组 IP 保持不变,如问题所示。
# Splitting IP into 2 parts __.__.__ and __.
# Doing this for IP from df2 along with Start and End columns from df1
ip = pd.DataFrame(df2.IP.str.rsplit('.', 1, expand=True))
ip.columns = ['IP_init', 'IP_last']
start = pd.DataFrame(df1.StartAddress.str.rsplit('.', 1, expand=True))
start.columns = ['start_init', 'start_last']
end = pd.DataFrame(df1.EndAddress.str.rsplit('.', 1, expand=True))
end.columns = ['end_init', 'end_last']
df = pd.concat([ip, start, end], axis=1)
# Checking if any IP belongs to any of the given blocks, if yes, note their index
index = []
for idx, val in enumerate(df.itertuples()):
for i in range(df.start_init.count()):
if df.loc[idx, 'IP_init'] == df.loc[i, 'start_init']:
if df.loc[idx, 'IP_last'] >= df.loc[i, 'start_last']
and df.loc[idx, 'IP_last'] <= df.loc[i, 'end_last']:
index.append(idx)
break
# Creating column IN_CIDR and marking True against the row which exists in IP block
df2['IN_CIDR'] = False
df2.loc[index, 'IN_CIDR'] = True
df2
IP IP_Format IN_CIDR
0 65.13.88.64 65.13.88.64 False
1 148.65.37.88 148.65.37.88 False
2 65.14.88.65 65.14.88.65 True
3 148.77.37.93 148.77.37.93 True
4 66.15.41.132 66.15.41.132 False
注意 - 您也可以使用which results np.whereto 跳过第一次迭代,因此您以后可以只关注行,从而减少开销。np.where(df.IP_init.isin(df.start_init), True, False)[False, False, True, True, False]True
添加回答
举报