【问题标题】:Processing large dictionary and data frame in python在 python 中处理大型字典和数据框
【发布时间】:2019-01-18 04:32:27
【问题描述】:

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

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

【问题讨论】:

标签: python pandas dictionary dataframe bigdata


【解决方案1】:

首先创建Series,然后为DataFrame 创建unstack,通过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 by indexcolumns of 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

【讨论】:

  • 我刚试过这个,第一种方法读取一百万个完整的字典大约需要 30 秒,第二种方法大约需要 14 秒。非常感谢!
猜你喜欢
  • 2020-04-26
  • 2011-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-28
  • 1970-01-01
  • 1970-01-01
  • 2017-02-17
相关资源
最近更新 更多