首页 > 解决方案 > 如何优化熊猫中的数据框迭代?

问题描述

我需要迭代一个数据框,对于每一行我需要基于两个现有列创建一个 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

有没有办法让它更快而不用逐行进行?

根据建议的解决方案添加更多信息:

标签: pythonpandasdataframe

解决方案


改用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)

推荐阅读