gpt4 book ai didi

python - 在Python中处理大型字典和数据帧

转载 作者:行者123 更新时间:2023-12-01 09:09:25 24 4
gpt4 key购买 nike

我有两个 pandas 数据框,形状为 (2500, 2500),数据框如下所示:

>> df1
"a" "b" "c" "d" "e"
"o" 0 0 0 0 0
"p" 0 0 0 0 0
"q" 0 0 0 0 0
"r" 0 0 0 0 0
"s" 0 0 0 0 0

我有两个字典,其中包含“~2,000,000”个键值对。看起来像这样

d1 = {("a", "o"):3, ("b", "p"):10}

我正在尝试将字典中的值填充到数据框中。我现在的解决方案是循环遍历字典:

for key, value in d1.iteritems():
df1.loc[key[0], key[1]] = value

但是这个过程需要很长时间。我想知道是否有一种方法可以更有效地浏览字典。或者我是否应该改变存储数据的方式?提前致谢。

最佳答案

首先创建系列,然后unstack对于 DataFrame,转置为 T最后combine_first用于分配 df1 的值:

d1 = {("a", "o"):3, ("b", "p"):10}
df = pd.Series(d1).unstack().T.combine_first(df1)
print (df)
a b c d e
o 3.0 0.0 0.0 0.0 0.0
p 0.0 10.0 0.0 0.0 0.0
q 0.0 0.0 0.0 0.0 0.0
r 0.0 0.0 0.0 0.0 0.0
s 0.0 0.0 0.0 0.0 0.0

如果df10填充,则仅使用reindex通过df1索引:

df = (pd.Series(d1)
.unstack(fill_value=0)
.T
.reindex(index=df1.index, columns=df1.columns, fill_value=0))
print (df)
a b c d e
o 3 0 0 0 0
p 0 10 0 0 0
q 0 0 0 0 0
r 0 0 0 0 0
s 0 0 0 0 0

关于python - 在Python中处理大型字典和数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51788537/

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