使用TQDM进度条与Pandas

104

当使用Pandas导入和索引大型数据集时,是否可以使用TQDM进度条呢?这里有一个示例,我正在导入、索引并使用to_datetime转换一些5分钟的数据。这需要一些时间,如果能看到进度条会很好。

#Import csv files into a Pandas dataframes and convert to Pandas datetime and set to index

eurusd_ask = pd.read_csv('EURUSD_Candlestick_5_m_ASK_01.01.2012-05.08.2017.csv')
eurusd_ask.index = pd.to_datetime(eurusd_ask.pop('Gmt time'))

1
不,这是不可能的。 - cs95
5个回答

233

通过形状获取长度

for index, row in tqdm(df.iterrows(), total=df.shape[0]):
   print("index",index)
   print("row",row)

4
我认为这个解决方案比@sonance207的更好,因为它不会将迭代器转换为列表,而是访问给定的属性。 - guerda
1
这个解决方案似乎不能与 df.itertuples() 一起使用? - Giacomo
2
iterrows会大幅减慢处理速度吗? - Matthew
3
对于我和tqdm版本为'4.42.0',使用itertuples也是可行的。示例代码如下:for idx_row, col1, col2, ... in tqdm.tqdm(df.itertuples(), total=len(df)): - gebbissimo
1
同样适用于tqdm_notebook。 - Ofer Rahat
显示剩余2条评论

22
with tqdm(total=Df.shape[0]) as pbar:    
    for index, row in Df.iterrows():
        pbar.update(1)
        ...

在结尾添加pbar.close();,否则循环将会一直运行(不退出),导致无法进入下一个代码块。 - Abhilash Singh Chauhan
2
with语句确实会自动关闭对象。 - meduz

3

对于tqdm > 4.24,有一个解决方法。 根据https://github.com/tqdm/tqdm#pandas-integration的说明:

from tqdm import tqdm
        
# Register `pandas.progress_apply` and `pandas.Series.map_apply` with `tqdm`
# (can use `tqdm_gui`, `tqdm_notebook`, optional kwargs, etc.)
tqdm.pandas(desc="my bar!")
eurusd_ask['t_stamp'] = eurusd_ask['Gmt time'].progress_apply(lambda x: pd.Timestamp)
eurusd_ask.set_index(['t_stamp'], inplace=True)

1
你可以通过正常读取文件并将每一行作为新的行添加到数据框中来逐行填充pandas数据框,尽管这比只使用Pandas自己的读取方法要慢得多。

1

我觉得这很容易实现。你只需要添加总参数即可。

import pandas as pd
df = pd.read_excel(PATH_TO_FILE)


for index, row in tqdm(df.iterrows(),  total=df.shape[0], desc=f'Reading DF'):
        print(row(['df_colum'])


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