如何在DataFrames中使用tqdm和map函数

15

我可以在使用map函数遍历数据框/系列行时,使用tqdm进度条吗?

具体而言,对于以下情况:

def example(x):
    x = x + 2
    return x

if __name__ == '__main__':
    dframe = pd.DataFrame([{'a':1, 'b': 1}, {'a':2, 'b': 2}, {'a':3, 'b': 3}])
    dframe['b'] = dframe['b'].map(example)
1个回答

33

由于tqdm与pandas的集成,你可以使用progress_map函数来代替map函数。

注意:为了让它工作,您应该在代码中添加tqdm.pandas()行。

所以请试试这个:

from tqdm import tqdm

def example(x):
    x = x + 2
    return x

tqdm.pandas()  # <- added this line

if __name__ == '__main__':
    dframe = pd.DataFrame([{'a':1, 'b': 1}, {'a':2, 'b': 2}, {'a':3, 'b': 3}])
    dframe['b'] = dframe['b'].progress_map(example)  # <- progress_map here

这里是文档参考:

(添加tqdm.pandas()后)... 你可以使用progress_apply代替applyprogress_map 代替map


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接