python - 如何优化熊猫中的数据框迭代?
问题描述
我需要迭代一个数据框,对于每一行我需要基于两个现有列创建一个 ID:名称和性别。最终,我将此新列添加到 df.
df = pd.read_csv(file, sep='\t', dtype=str, na_values="", low_memory=False)
row_ids = []
for index, row in df.iterrows():
if (index % 1000) == 0:
print("Row node index: {}".format(str(index)))
caculated_id = get_id(row['name', row['sex']])
row_ids.append(caculated_id)
df['id'] = row_ids
有没有办法让它更快而不用逐行进行?
根据建议的解决方案添加更多信息:
解决方案
改用apply
:
def func(x):
if (x.name % 1000) == 0:
print("Row node index: {}".format(str(x.name)))
caculated_id = get_id(row['name', row['sex']])
return caculated_id
df['id'] = df.apply(func, axis=1)
推荐阅读
- javascript - 在div中选择ul的id
- vue.js - 在 Vue.js 中,为什么我的选择没有选择默认选项?
- python - Django REST 框架:“BasePermissionMetaclass”对象不可迭代
- macos - 在 jenkins 中执行 shell 脚本以执行自动化脚本的内容
- vba - VBA XMLHTTP“内存不足”状态
- c# - 使用 LINQ 将数组列表转换为 KeyValuePairs 列表
- laravel - Laradock 404 未找到 nginx
- ios - 我想在 ios(swift) 中每五分钟加载一次 facebook 插页式广告
- mysql - 如何在 Mysql+Node JS 的另一个查询中使用一个查询的结果数组?
- git - 如何在 git 中比较不同分支中的相同文件(使用 visualstudio 或 Tortoise git,或使用 Git UI)