首页 > 解决方案 > 在python中处理大字典和数据框

问题描述

我有两个pandasshape(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

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

标签: pythonpandasdictionarydataframebigdata

解决方案


首先创建Series,然后unstackDataFrame,转置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

If仅使用by和ofdf1填充:0reindexindexcolumnsdf1

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

推荐阅读