如何将tqdm与map用于Dataframes

Gha*_*nem 4 python-3.x pandas tqdm

我可以使用tqdm进度条和map函数来循环遍历数据帧/系列行吗?

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

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)
Run Code Online (Sandbox Code Playgroud)

Teo*_*tic 9

由于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
Run Code Online (Sandbox Code Playgroud)

这是文档参考:

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