gpt4 book ai didi

python - 连接不同长度的 numpy 数组的字典(尽可能避免手动循环)

转载 作者:太空宇宙 更新时间:2023-11-04 06:14:54 26 4
gpt4 key购买 nike

我有一个与此处讨论的问题类似的问题 Concatenating dictionaries of numpy arrays (avoiding manual loops if possible)

我正在寻找一种方法来连接两个包含任意大小的 numpy 数组的 python 字典中的值,同时避免必须手动遍历字典键。例如:

import numpy as np

# Create first dictionary
n1 = 3
s = np.random.randint(1,101,n1)
n2 = 2
r = np.random.rand(n2)
d = {"r":r,"s":s}
print "d = ",d

# Create second dictionary
n3 = 1
s = np.random.randint(1,101,n3)
n4 = 3
r = np.random.rand(n4)
d2 = {"r":r,"s":s}
print "d2 = ",d2

# Some operation to combine the two dictionaries...
d = SomeOperation(d,d2)

# Updated dictionary
print "d3 = ",d

给出输出

>> d =  {'s': array([75, 25, 88]), 'r': array([ 0.1021227 ,  0.99454874])}
>> d2 = {'s': array([78]), 'r': array([ 0.27610587, 0.57037473, 0.59876391])}
>> d3 = {'s': array([75, 25, 88, 78]), 'r': array([ 0.1021227 , 0.99454874, 0.27610587, 0.57037473, 0.59876391])}

即因此,如果键已经存在,则存储在该键下的 numpy 数组将附加到。

前面讨论中提出的使用包 pandas 的解决方案不起作用,因为它需要具有相同长度的数组(n1=n2 和 n3=n4)。

有没有人知道最好的方法来做到这一点,同时尽量减少使用缓慢的手动 for 循环? (我想避免循环,因为我想合并的词典可能有数百个键)。

感谢(也感谢“Aim”提出了一个非常明确的问题)!

最佳答案

一种方法是使用系列字典(即值是系列而不是数组):

In [11]: d2
Out[11]: {'r': array([ 0.3536318 , 0.29363604, 0.91307454]), 's': array([46])}

In [12]: d2 = {name: pd.Series(arr) for name, arr in d2.iteritems()}

In [13]: d2
Out[13]:
{'r': 0 0.353632
1 0.293636
2 0.913075
dtype: float64,
's': 0 46
dtype: int64}

这样你就可以将它传递给 DataFrame 构造函数:

In [14]: pd.DataFrame(d2)
Out[14]:
r s
0 0.353632 46
1 0.293636 NaN
2 0.913075 NaN

关于python - 连接不同长度的 numpy 数组的字典(尽可能避免手动循环),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16359955/

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