gpt4 book ai didi

Python 根据条件合并两个 Numpy 数组

转载 作者:太空狗 更新时间:2023-10-29 21:38:32 25 4
gpt4 key购买 nike

如何通过在数组 B 中查找数组 A 的值来合并以下两个数组?

数组A:

array([['GG', 'AB', IPv4Network('1.2.3.41/26')],
['GG', 'AC', IPv4Network('1.2.3.42/25')],
['GG', 'AD', IPv4Network('1.2.3.43/24')],
['GG', 'AE', IPv4Network('1.2.3.47/23')],
['GG', 'AF', IPv4Network('1.2.3.5/24')]],
dtype=object)

和数组B:

array([['123456', 'A1', IPv4Address('1.2.3.5'), nan],
['987654', 'B1', IPv4Address('1.2.3.47'), nan]],
dtype=object)

这里的目标是创建数组 C,通过在数组 A 中查找数组 B 的 IPv4Address 并比较它们,并获取相应数组的第二个值并存储它:

数组 C:

array([['123456', 'A1', IPv4Address('1.2.3.5'), nan, 'AF'],
['987654', 'B1', IPv4Address('1.2.3.47'), nan, 'AE']],
dtype=object)

IP 地址属于这种类型:https://docs.python.org/3/library/ipaddress.html#ipaddress.ip_network

我怎样才能做到这一点?

编辑:

请注意,合并是以 IP 匹配为条件的,因此生成的数组 C 将具有与数组 B 相同数量的数组,但它会多一个值。建议的重复链接没有回答同一个问题。

最佳答案

这应该可以满足您的要求(至少输出正是您想要的),我做了一些小假设来处理您的#dummydata,但这应该不会太重要。

Code:

import numpy as np
import ipaddress as ip

array_A = np.array([['GG', 'AB', ip.ip_network('192.168.0.0/32')],
['GG', 'AC', ip.ip_network('192.168.0.0/31')],
['GG', 'AD', ip.ip_network('192.168.0.0/30')],
['GG', 'AE', ip.ip_network('192.168.0.0/29')],
['GG', 'AF', ip.ip_network('192.168.0.0/28')]],
dtype=object)

array_B = np.array([['123456', 'A1', ip.ip_network('192.168.0.0/28'), np.nan],
['987654', 'B1', ip.ip_network('192.168.0.0/29'), np.nan]],
dtype=object)


def merge_by_ip(A, B):
# initializing an empty array with len(B) rows and 5 columns for the values you want to save in it
C = np.empty([len(B), 5],dtype=object)
for n in range(len(B)):
for a in A:
# checking condition: if ip address in a is ip address in b
if a[2] == B[n][2]:
# add the entry of b with the second value of a to the new Array c
C[n] = np.append(B[n], a[1])
return C


print(merge_by_ip(array_A, array_B))

Output:

[['123456' 'A1' IPv4Network('192.168.0.0/28') nan 'AF']
['987654' 'B1' IPv4Network('192.168.0.0/29') nan 'AE']]

Note:

此解决方案具有 O(m * n) 的复杂性,这不是必需的,有许多开箱即用的 (Pandas) 和自定义的(例如使用 dict) 的方式合并,复杂度较低。

关于Python 根据条件合并两个 Numpy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53740025/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com