python - 在python中处理大字典和数据框
问题描述
我有两个pandas
shape(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
然而,这个过程需要很长时间。我想知道是否有一种方法可以更有效地浏览字典。或者我是否应该改变存储数据的方式?提前致谢。
解决方案
首先创建Series
,然后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
If仅使用by和ofdf1
填充:0
reindex
index
columns
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
推荐阅读
- swift - 是否可以在 swift 类中编写变异函数?
- django-rest-framework - 如何使用 django rest api 返回自定义响应
- ios - 来自苹果免费帐户 libswiftCore.dylib 的代码签名错误:errSecInternalComponent
- flutter - Dart 中有没有办法将函数标记为抛出异常?
- javascript - Strapi CMS:添加计算字段
- azure - Azure Application Insight 工作项授权错误
- json - Oracle APEX 中的 POST 请求(数组)
- r - 需要在子集中指定年龄区间
- python - 如何用一维数组中的值替换 3D numpy 数组的第一维?
- c# - 如何并行执行任务但每 T 秒不超过 N 个任务?