python - 一起迭代字典和数据框的更快方法?
问题描述
我有一个字典和一个具有相同键/列的 DataFrame。然而,DataFrame 缺少一些数据,我将使用字典填充这些数据。这是一个最小的例子,我的数据集要大得多。
mydict = {'one': ['foo', 'bar'], 'two': ['foo', 'bar']}
mydf = pd.DataFrame({'one': ['N/A', 'bar'], 'two': ['foo', 'N/A'], 'foo': ['foo', 'bar'], 'bar': ['foo', 'bar']})
def myfunc(mydict):
for i,k in mydict.items():
for m in k:
mydf[i].replace(to_replace='N/A', value=mydf[m], inplace=True)
for f,g in mydf.iterrows():
for h in g:
if h != 'N/A':
myfunc(mydict)
for i,v in mydict.items():
mydf.drop(columns=v, inplace=True, errors='ignore')
当我在更大的数据集上运行我的函数时,内核不会停止运行。什么是更快的方法来做到这一点?我想尝试使用 df.apply() 或矢量化功能,但不知道如何。上面示例的输出如下所示:
one two
0 foo foo
1 bar bar
解决方案
试试这个,它应该给你你想要的。
# Fill the values using your dictionary
for k, v in mydict.items():
mydf[k] = v
# Drop the columns you don't want
mydf.drop(columns=['foo','bar'], inplace=True)
你会得到这个:
one two
0 foo foo
1 bar bar
推荐阅读
- python - 使用按钮在具有参数化类的面板中触发操作,当按钮操作完成时更新另一个依赖项(Holoviz)
- spring - 意外字符('-'(代码 45)):需要空格分隔根级值
- r - 如何在 R 中将两个向量“缝合”在一起?
- vue.js - 带有服务器表的 Pagiantion 不适用于 vue js
- r - 计算数据框 R 中每行的值
- java - 如何通过 MIDlet 将对象发送到服务器?
- android - 如何向/从 Parcelable 写入/读取 Map,哪个值是 List
或列表 ? - jquery - 当引导模式已经打开时,如何防止使用 jquery 刷新 div?
- sql - 使用 SQL 分组从数据库中检索每个组中的最后一条记录
- html - 90% 白色和 10% 可缩放图像的页面背景