我需要迭代一个数据框,对于每一行,我需要根据两个现有列创建一个 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)
关于python - 如何优化 pandas 中的数据帧迭代?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69430194/